{
 "angle": "loss realisation and bad debt",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No Medium+ finding survived on this angle. Bad debt is reflected in realAssets immediately (lossFactor != 0 switches realAssets to live Midnight net credit), netRate is untouched, and a later sync or forceDeallocate does not realize the loss a second time (verified by PoC). Only Informational observations remain.",
 "lowInfo": [
  {
   "title": "After bad debt, stored netCredit, vault cap allocations and duration allocations keep counting lost credit until an allocator/sentinel syncs",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:25-26",
    "src/adapters/midnight/MidnightAdapter.sol:715-735 (withdrawToVault)",
    "src/adapters/midnight/MidnightAdapter.sol:803-819 (durationAllocations)",
    "src/adapters/midnight/MidnightAdapter.sol:822-850 (realAssets)"
   ],
   "detail": "When Midnight realizes bad debt (lossFactor > 0) realAssets reads currentNetCredit, so the share price drops at once, but marketData.netCredit, vault.allocation(ids) and durationAllocations still hold the pre-loss stored net credit. In the PoC (test/poc/LossBadDebtStaleAllocation.t.sol, real Midnight + VaultV2 via the integration setup) a ~50% loss drops realAssets from 100000000000030600145311 to 50000000000015300072655 while the adapter allocation stays at 100593430826474621736007 (about 2x the real exposure) until vault.deallocate(adapter, abi.encode(market), 0) syncs it to 50296715413237310868003. Effect: caps (absolute, relative and duration caps) are over-consumed by phantom credit, so allocators can be blocked from new buys in the same families/collateral ids until someone with the allocator or sentinel role syncs; stale netCredit also feeds the duration-cap check in onBuy. No depositor value is lost and the sync does not realize the loss twice (asserted). The NatSpec documents the sync path ('Can be called with withdrawnAssets == 0 to synchronize marketData after a loss'), so this is design-acknowledged; suggestion: sync stored netCredit opportunistically in onBuy/onSell for markets with lossFactor > lastLossFactor, or note in README that caps must be synced after bad debt. Command: forge build test/imports/MidnightImport.sol test/poc/LossBadDebtStaleAllocation.t.sol && forge test --skip \"*Test.sol\" --match-path test/poc/LossBadDebtStaleAllocation.t.sol --match-test testBadDebt -vv. PoC source:\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {console} from \"../../lib/forge-std/src/Test.sol\";\n\n/// @notice Loss/bad-debt behaviour of the MidnightAdapter against the real Midnight and VaultV2.\ncontract LossBadDebtStaleAllocationTest is MidnightAdapterIntegrationTest {\n    using MathLib for uint256;\n\n    function testBadDebtRealAssetsDropsButAllocationStaysUntilSync() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        bytes32 marketId = IdLib.toId(market);\n        bytes32 adapterId = adapter.adapterId();\n\n        uint256 storedBefore = adapter.marketData(marketId).netCredit;\n        uint64 rateBefore = adapter.marketData(marketId).netRate;\n        uint256 realBefore = adapter.realAssets();\n        uint256 totalBefore = vault.totalAssets();\n        uint256 allocBefore = vault.allocation(adapterId);\n        console.log(\"stored netCredit before\", storedBefore);\n        console.log(\"realAssets before     \", realBefore);\n        console.log(\"vault totalAssets bef.\", totalBefore);\n        console.log(\"adapter allocation bef\", allocBefore);\n\n        // Collateral crashes; anyone realizes bad debt on the borrower.\n        oracle.setPrice(ORACLE_PRICE_SCALE * oneToken / 1e18 / 4);\n        midnight.liquidate(market, 0, 0, 0, borrower, false, address(this), address(0), \"\");\n        assertGt(midnight.lossFactor(marketId), 0, \"bad debt realized\");\n\n        uint256 realAfter = adapter.realAssets();\n        uint256 totalAfter = vault.totalAssets();\n        console.log(\"lossFactor            \", uint256(midnight.lossFactor(marketId)));\n        console.log(\"realAssets after      \", realAfter);\n        console.log(\"vault totalAssets aft.\", totalAfter);\n        console.log(\"stored netCredit after\", uint256(adapter.marketData(marketId).netCredit));\n        console.log(\"adapter allocation aft\", vault.allocation(adapterId));\n        console.log(\"duration alloc (7d)   \", adapter.durationAllocations(1)[0]);\n\n        // Loss is reflected at once in realAssets / totalAssets, netRate unchanged (documented).\n        assertLt(realAfter, realBefore, \"realAssets dropped\");\n        assertLt(totalAfter, totalBefore, \"share price dropped\");\n        assertEq(adapter.marketData(marketId).netRate, rateBefore, \"netRate unchanged\");\n        // Cap bookkeeping still counts the lost credit until someone syncs.\n        assertEq(adapter.marketData(marketId).netCredit, storedBefore, \"stored netCredit stale\");\n        assertEq(vault.allocation(adapterId), allocBefore, \"allocation stale\");\n        assertEq(adapter.durationAllocations(1)[0], storedBefore, \"duration allocation stale\");\n\n        // Sync: allocator/sentinel withdraws 0 assets.\n        vm.prank(allocator);\n        vault.deallocate(address(adapter), abi.encode(market), 0);\n        uint256 storedSynced = adapter.marketData(marketId).netCredit;\n        console.log(\"stored netCredit synced\", storedSynced);\n        console.log(\"allocation synced      \", vault.allocation(adapterId));\n        assertLt(storedSynced, storedBefore, \"sync drops stored credit\");\n        assertEq(vault.allocation(adapterId), allocBefore - (storedBefore - storedSynced), \"allocation synced\");\n        assertEq(adapter.realAssets(), realAfter, \"sync does not realize the loss twice\");\n    }\n}\nOutput:\n\nRan 1 test for test/poc/LossBadDebtStaleAllocation.t.sol:LossBadDebtStaleAllocationTest\n[PASS] testBadDebtRealAssetsDropsButAllocationStaysUntilSync() (gas: 1760596)\nLogs:\n  stored netCredit before 100593430826474621736007\n  realAssets before      100000000000030600145311\n  vault totalAssets bef. 100000000000000000000000\n  adapter allocation bef 100593430826474621736007\n  lossFactor             170141183460469231731685612341188336919\n  realAssets after       50000000000015300072655\n  vault totalAssets aft. 50000000000015300072656\n  stored netCredit after 100593430826474621736007\n  adapter allocation aft 100593430826474621736007\n  duration alloc (7d)    100593430826474621736007\n  stored netCredit synced 50296715413237310868003\n  allocation synced       50296715413237310868003\n\nSuite result: ok. 1 passed; 0 failed; 0 skipped; finished in 8.16ms (1.88ms CPU time)\n\nRan 1 test suite in 17.13ms (8.16ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)"
  },
  {
   "title": "Shareholders can exit at the pre-loss price before permissionless bad-debt realization (loss front-running)",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:822-850",
    "lib/midnight/src/Midnight.sol:575-640 (liquidate)"
   ],
   "detail": "realAssets only reflects a loss once Midnight's liquidate raises lossFactor. A holder who sees an under-collateralised borrower can withdraw idle vault liquidity (or call liquidate themselves right after withdrawing, in one transaction) and leave the loss to remaining holders. This is the generic Vault V2 loss-timing property, not specific to the adapter, and it is bounded by idle liquidity because the Midnight adapter cannot be the liquidity adapter; forceDeallocate does not help an escaper because it hands over credit that bears the same loss at one asset per unit plus penalty. No PoC written; likely accepted risk."
  },
  {
   "title": "Sales in a market with bad debt cannot be valued mid-callback (realAssets reverts OtherSellInProgress)",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:840-843"
   ],
   "detail": "While the adapter is the seller in a market with lossFactor != 0, realAssets reverts, so any vault accrual/deposit/withdraw nested in that take reverts. Existing tests (testBackingCallbackFirstValuationAfterDefaultBlocked) show this is intended to stop share-price reads during the sale; noted for completeness only."
  }
 ],
 "covered": [
  "Read src/adapters/midnight/README.md, MidnightAdapter.sol (realAssets, onSell shortfall loop, forceSellable branch, forceRemove, forceDeallocate branch of deallocate, withdrawToVault, removeMarket, durationAllocations), VaultV2 accrueInterest/deallocateInternal, Midnight take/withdraw/liquidate/lossFactor.",
  "Wrote and ran a PoC against the pinned commit with real Midnight and VaultV2 (integration setup) that realizes ~50% bad debt: realAssets and totalAssets drop at once, netRate unchanged, stored netCredit/allocation/duration allocation stale, sync with withdraw 0 corrects allocations without a second loss. The 8 inherited integration tests also passed in the same run.",
  "Checked double realization: the shortfall loop and realAssets both use currentNetCredit when lossFactor != 0, so absorbed shortfall and bad debt use the same base; forceDeallocate after an unsynced loss decrements allocation by sold credit + loss (consistent with existing test testForceDeallocateAfterUnsyncedLoss).",
  "Checked total loss (lossFactor = max): currentNetCredit becomes 0, realAssets contributes 0, the sync removes the market; new buys are impossible (Midnight MarketLossFactorMaxedOut).",
  "Checked forceSellable sales: loss realized immediately via sellerAssets vs stored value with no rate change and no shortfallAllowance use, bounded by minForceSellPrice (curator-set, trusted).",
  "Checked forceRemove: removes stored netCredit from allocations and the amortized value from realAssets in one step (documented, timelocked)."
 ],
 "notCovered": [
  "The prior audit drafts (audits/2026-10-12-midnight-adapter-cantina-draft.pdf and -trustsec-draft.pdf) could not be read on this machine (no PDF text tools; raw stream extraction gave no readable text), so the Informational items were not checked against them and may duplicate them.",
  "The full test suite could not be run here: compiling the whole project with via_ir was killed by the OS (solc SIGKILL); only the PoC plus the integration suite were compiled and run.",
  "No fuzz or invariant campaign on loss accounting; no PoC for the loss-front-running and mid-sale valuation notes (marked unverified)."
 ]
}