{
 "lead": "nested-trades: taker re-enters (second adapter take, forceDeallocate, deposit/withdraw/accrueInterest) from inside its own Midnight callback while trading with a MidnightAdapter offer",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No candidate. The lead was dismissed with passing Foundry tests at the pinned commit (real Midnight, real VaultV2, forge --isolate so that each top-level call is its own tx). Why it holds: (1) Midnight updates positions and sets the seller's liquidation lock (Midnight.sol:437) before any callback runs. (2) While the adapter is the seller, the taker's onBuy runs before the adapter's onSell, and in that window the adapter's realAssets still uses the stored pre-sale netCredit (MidnightAdapter.sol:848-850). The value does not drop and the cash has not arrived, so totalAssets is the pre-sale value. If lossFactor != 0, realAssets reverts with OtherSellInProgress (line 852), which only blocks the taker's own tx. (3) VaultV2 freezes totalAssets for the whole tx at the first accrual (firstTotalAssets, VaultV2.sol:184,614,627), so a nested deposit gets the same shares as a deposit in the next tx: 49963688980049280464788 vs 49963688980049280464788, and those shares redeem for 49999999999999999999999 of 50000000000000000000000 deposited. (4) Nested forceDeallocate on the locked market reverts with SellInProgress (MidnightAdapter.sol:433). A nested sale with a shortfall in another market reverts with OtherSellInProgress (line 656), so the stale stored credit of the locked market never feeds the shortfall spread. (5) A nested forceDeallocate and a par sale in another market succeed, and afterwards stored netCredit equals Midnight credit in both markets and the vault's adapter allocation equals their sum (69000e18). (6) When the adapter is the buyer, its onBuy runs before the taker's onSell and finishes accrueInterest and allocate before the taker gets control. The inProgressBuy transient state is cleared before any untrusted code runs (lines 561-576), and the nested deposit and nested second buy are priced and accounted exactly. Duration caps and vault caps see the stale (higher) stored credit of the market being sold, which is stricter rather than a bypass.",
 "lowInfo": [
  {
   "title": "Any vault accrual inside a taker's onBuy reverts while an adapter sale is in progress in a market with lossFactor != 0",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:851-853",
    "lib/midnight/src/Midnight.sol:437-466"
   ],
   "detail": "realAssets() requires !liquidationLocked for a market with nonzero lossFactor. A taker of an adapter sell offer in such a market therefore cannot deposit, withdraw or accrueInterest on the parent vault, nor trade with another adapter offer that triggers accrual, from inside its onBuy callback. This only affects the taker's own composability (self-DoS) and does not change any price or accounting. Not exercised by a test here (UNVERIFIED); the lossFactor==0 path was tested."
  },
  {
   "title": "Cap checks during a nested buy count the stored (pre-sale) credit of a market whose sale is in progress",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:591-603",
    "src/adapters/midnight/MidnightAdapter.sol:817-829"
   ],
   "detail": "If a taker takes an adapter buy offer in market B from inside its onBuy for an adapter sale in market A, durationAllocations and the vault allocations still include A's pre-sale netCredit (onSell(A) has not run yet). This makes the cap check stricter, never looser, so it can only cause a revert. testNestedForceDeallocateAndSecondSale shows that stored state and allocations reconcile exactly after the outer sale (vault adapter allocation 69000e18 = stored A 35000e18 + stored B 34000e18)."
  }
 ],
 "covered": {
  "tests": "test/poc/NestedTradesPoC.t.sol (inherits MidnightAdapterIntegrationTest): 11 passed, 0 failed (3 new nested-trade tests + the 8 inherited integration tests)",
  "scenarios": [
   "taker buys an adapter sell offer and deposits inside onBuy: shares equal those of a next-tx deposit, and the redeem value does not exceed the deposit",
   "inside the same callback: accrueInterest succeeds, forceDeallocate on the locked market reverts SellInProgress, forceDeallocate on another market succeeds, a shortfall sale in another market reverts OtherSellInProgress, and a par sale in another market succeeds; stored credit, Midnight credit and vault allocation reconcile",
   "taker sells into an adapter buy offer and, inside onSell, deposits and takes a second adapter buy offer in another market: pricing is exact and storage reconciles"
  ],
  "poc": {
   "path": "test/poc/NestedTradesPoC.t.sol",
   "command": "XDG_DATA_HOME=$TMPDIR/xdg forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol test/poc/NestedTradesPoC.t.sol && forge test --isolate --match-path test/poc/NestedTradesPoC.t.sol --skip '*/integration/Morpho*' --skip '*/test/*Test.sol' --skip '*/test/examples/*' --skip '*/test/periphery/*' -vv",
   "forge": "1.8.3",
   "output": "No files changed, compilation skipped\nRan 11 tests for test/poc/NestedTradesPoC.t.sol:NestedTradesPoCTest\n[PASS] testForceDeallocate() (gas: 1751928)\n[PASS] testForceSell() (gas: 1653955)\n[PASS] testMakerBuy() (gas: 1130920)\n[PASS] testMakerSell() (gas: 1922551)\n[PASS] testNestedDepositAndBuyDuringAdapterBuy() (gas: 7426260)\nLogs:\n  nested deposit ok / nested buy ok: true true\n  totalAssets before / in callback / after: 120072674817836646698146 120072674817836646698146 130072674817836646698146\n  share price before / after: 1000726748178366466981464593717253207 1000726748178366466981470213217566373\n  nested shares / reference shares next tx: 9992737796009856092957 9992737796009856092957\n  redeem value of nested shares vs deposit: 9999999999999999999999 10000000000000000000000\n  stored vs Midnight A: 45000000000000000000000 45000000000000000000000\n  stored vs Midnight B: 45000000000000000000000 45000000000000000000000\n[PASS] testNestedDepositDuringAdapterSale() (gas: 5004547)\nLogs:\n  totalAssets before / in callback / after: 100072674817836646698146 100072674817836646698146 150072674817836646698146\n  adapter realAssets before / in callback / after: 79600730817836646698146 79600730817836646698146 69659723817866854270826\n  shortfallAllowance consumed: 8384921111211219809\n  share price (1e36 shares->assets) before / after: 1000726748178366466981459992732518216 1000726748178366466981465859252513444\n  nested deposit shares / same deposit in next tx: 49963688980049280464788 49963688980049280464788\n  nested shares redeem value now vs deposited: 49999999999999999999999 50000000000000000000000\n[PASS] testNestedForceDeallocateAndSecondSale() (gas: 9317786)\nLogs:\n  accrueInterest true\n  forceDeallocate(A, locked) false\n  0xb2082406\n  forceDeallocate(B) true\n  take B sale with shortfall false\n  0x779999c6\n  take B sale at par true\n  stored netCredit A before/after, Midnight credit A: 40000000000000000000000 35000000000000000000000 35000000000000000000000\n  stored netCredit B before/after, Midnight credit B: 40000000000000000000000 34000000000000000000000 34000000000000000000000\n  vault allocation adapterId vs stored A+B: 69000000000000000000000 69000000000000000000000\n  totalAssets before / after: 101072674817836646698146 101052674817836646698146\n[PASS] testRepayWithdrawRedeem() (gas: 1781972)\n[PASS] testTakerBuy() (gas: 1167522)\n[PASS] testTakerSell() (gas: 1960229)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17209500)\nSuite result: ok. 11 passed; 0 failed; 0 skipped; finished in 70.87ms (55.45ms CPU time)\nRan 1 test suite in 73.17ms (70.87ms CPU time): 11 tests passed, 0 failed, 0 skipped (11 total tests)\n",
   "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {IERC20} from \"../../src/interfaces/IERC20.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\n\n/// @dev Taker that runs a scripted list of calls inside each of its Midnight callbacks (k-th callback runs script k).\ncontract NestedTaker {\n    struct Call {\n        address target;\n        bytes data;\n    }\n\n    mapping(uint256 => Call[]) internal scripts;\n    uint256 public callbackCount;\n    mapping(uint256 => mapping(uint256 => bool)) public ok;\n    mapping(uint256 => mapping(uint256 => bytes)) public ret;\n    mapping(uint256 => uint256) public vaultTotalAssetsAtEntry;\n    mapping(uint256 => uint256) public adapterRealAssetsAtEntry;\n    mapping(uint256 => bool) public adapterRealAssetsOk;\n    IVaultV2 public vault;\n    address public adapter;\n\n    constructor(IVaultV2 _vault, address _adapter) {\n        vault = _vault;\n        adapter = _adapter;\n    }\n\n    function addCall(uint256 k, address target, bytes calldata data) external {\n        scripts[k].push(Call(target, data));\n    }\n\n    function exec(address target, bytes calldata data) external returns (bytes memory) {\n        (bool s, bytes memory r) = target.call(data);\n        if (!s) {\n            assembly (\"memory-safe\") {\n                revert(add(r, 32), mload(r))\n            }\n        }\n        return r;\n    }\n\n    function _run() internal {\n        uint256 k = callbackCount++;\n        vaultTotalAssetsAtEntry[k] = vault.totalAssets();\n        (bool s, bytes memory r) = adapter.staticcall(abi.encodeWithSignature(\"realAssets()\"));\n        adapterRealAssetsOk[k] = s;\n        if (s) adapterRealAssetsAtEntry[k] = abi.decode(r, (uint256));\n        Call[] storage calls = scripts[k];\n        for (uint256 i; i < calls.length; i++) {\n            (ok[k][i], ret[k][i]) = calls[i].target.call(calls[i].data);\n        }\n    }\n\n    function onBuy(bytes32, Market memory, uint256, uint256, uint256, address, bytes memory)\n        external\n        returns (bytes32)\n    {\n        _run();\n        return keccak256(\"morpho.midnight.callbackSuccess\");\n    }\n\n    function onSell(bytes32, Market memory, uint256, uint256, uint256, address, address, bytes memory)\n        external\n        returns (bytes32)\n    {\n        _run();\n        return keccak256(\"morpho.midnight.callbackSuccess\");\n    }\n}\n\n/// @dev Run with --isolate so that each top-level call is its own transaction (transient firstTotalAssets resets).\ncontract NestedTradesPoCTest is MidnightAdapterIntegrationTest {\n    NestedTaker internal taker;\n    Market internal mA;\n    Market internal mB;\n\n    function _adapterBuyOffer(Market memory market, uint256 units) internal returns (Offer memory offer, bytes memory rd) {\n        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\", market.maturity, 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        rd = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n    }\n\n    function _adapterSellOffer(Market memory market, uint256 units, uint256 tick)\n        internal\n        returns (Offer memory offer, bytes memory rd)\n    {\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\", market.maturity, 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 Adapter buys `units` in `market` from the borrower (borrower is the taker).\n    function _borrowerSellsTo(Market memory market, uint256 units) internal {\n        (Offer memory offer, bytes memory rd) = _adapterBuyOffer(market, units);\n        uint256 collateral = units * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, collateral);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        midnight.take(offer, rd, units, borrower, borrower, address(0), \"\");\n        vm.stopPrank();\n    }\n\n    function _setUpPositions() internal {\n        mA = _market(7 days);\n        mB = _market(6 days);\n        _borrowerSellsTo(mA, 40_000 * oneToken);\n        _borrowerSellsTo(mB, 40_000 * oneToken);\n        taker = new NestedTaker(IVaultV2(address(vault)), address(adapter));\n        deal(address(underlyingToken), address(taker), 1_000_000 * oneToken);\n        taker.exec(address(underlyingToken), abi.encodeCall(IERC20.approve, (address(midnight), type(uint256).max)));\n        taker.exec(address(underlyingToken), abi.encodeCall(IERC20.approve, (address(vault), type(uint256).max)));\n        taker.exec(address(underlyingToken), abi.encodeCall(IERC20.approve, (address(adapter), type(uint256).max)));\n        taker.exec(address(midnight), abi.encodeCall(IMidnight.setIsAuthorized, (address(adapter), true, address(taker))));\n        vm.warp(block.timestamp + 1 days);\n        vault.accrueInterest();\n    }\n\n    function _takeCall(Offer memory offer, bytes memory rd, uint256 units) internal view returns (bytes memory) {\n        return abi.encodeCall(IMidnight.take, (offer, rd, units, address(taker), address(0), address(taker), \"\"));\n    }\n\n    function _sharePrice() internal view returns (uint256) {\n        return vault.convertToAssets(1e18 * 1e18);\n    }\n\n    /// @dev Taker buys adapter credit in market A and, inside its onBuy (A liquidation-locked, stored net credit stale), deposits.\n    /// Compares the shares obtained with a plain deposit in a separate tx.\n    function testNestedDepositDuringAdapterSale() public {\n        _setUpPositions();\n        uint256 units = 10_000 * oneToken;\n        uint256 dep = 50_000 * oneToken;\n        (Offer memory offer, bytes memory rd) = _adapterSellOffer(mA, units, TICK);\n        taker.addCall(0, address(vault), abi.encodeWithSignature(\"deposit(uint256,address)\", dep, address(taker)));\n        uint256 priceBefore = _sharePrice();\n        uint256 taBefore = vault.totalAssets();\n        uint256 raBefore = adapter.realAssets();\n        uint256 allowanceBefore = adapter.shortfallAllowance();\n        taker.exec(address(midnight), _takeCall(offer, rd, units));\n        require(taker.ok(0, 0), \"nested deposit failed\");\n        uint256 nestedShares = abi.decode(taker.ret(0, 0), (uint256));\n        uint256 taAfter = vault.totalAssets();\n        uint256 priceAfter = _sharePrice();\n        // Reference: same deposit right after, in its own tx.\n        uint256 refShares = vault.previewDeposit(dep);\n        console.log(\"totalAssets before / in callback / after:\", taBefore, taker.vaultTotalAssetsAtEntry(0), taAfter);\n        console.log(\"adapter realAssets before / in callback / after:\", raBefore, taker.adapterRealAssetsAtEntry(0), adapter.realAssets());\n        console.log(\"shortfallAllowance consumed:\", allowanceBefore - adapter.shortfallAllowance());\n        console.log(\"share price (1e36 shares->assets) before / after:\", priceBefore, priceAfter);\n        console.log(\"nested deposit shares / same deposit in next tx:\", nestedShares, refShares);\n        uint256 redeemValue = vault.previewRedeem(nestedShares);\n        console.log(\"nested shares redeem value now vs deposited:\", redeemValue, dep);\n        assertLe(redeemValue, dep, \"nested depositor gained\");\n    }\n\n    /// @dev Inside its onBuy for an adapter sale in A, the taker tries forceDeallocate on A and on B,\n    /// takes an adapter sale in B at a shortfall and at no shortfall, and calls accrueInterest.\n    function testNestedForceDeallocateAndSecondSale() public {\n        _setUpPositions();\n        uint256 units = 5_000 * oneToken;\n        (Offer memory offerA, bytes memory rdA) = _adapterSellOffer(mA, units, TICK);\n        (Offer memory offerBShort, bytes memory rdBShort) = _adapterSellOffer(mB, units, TICK);\n        (Offer memory offerBPar, bytes memory rdBPar) = _adapterSellOffer(mB, units, MAX_TICK);\n        // Taker needs a vault share for forceDeallocate.\n        taker.exec(address(vault), abi.encodeWithSignature(\"deposit(uint256,address)\", 1000 * oneToken, address(taker)));\n        bytes memory fdA = abi.encodeWithSignature(\"forceDeallocate(address,bytes,uint256,address)\", address(adapter), abi.encode(mA, address(taker)), 1000 * oneToken, address(taker));\n        bytes memory fdB = abi.encodeWithSignature(\"forceDeallocate(address,bytes,uint256,address)\", address(adapter), abi.encode(mB, address(taker)), 1000 * oneToken, address(taker));\n        taker.addCall(0, address(vault), abi.encodeWithSignature(\"accrueInterest()\"));\n        taker.addCall(0, address(vault), fdA);\n        taker.addCall(0, address(vault), fdB);\n        taker.addCall(0, address(midnight), _takeCall(offerBShort, rdBShort, units));\n        taker.addCall(0, address(midnight), _takeCall(offerBPar, rdBPar, units));\n        uint256 creditA0 = adapter.marketData(IdLib.toId(mA)).netCredit;\n        uint256 creditB0 = adapter.marketData(IdLib.toId(mB)).netCredit;\n        uint256 ta0 = vault.totalAssets();\n        taker.exec(address(midnight), _takeCall(offerA, rdA, units));\n        string[5] memory names = [\"accrueInterest\", \"forceDeallocate(A, locked)\", \"forceDeallocate(B)\", \"take B sale with shortfall\", \"take B sale at par\"];\n        for (uint256 i; i < 5; i++) {\n            bytes memory r = taker.ret(0, i);\n            bytes4 sel = r.length >= 4 ? bytes4(r) : bytes4(0);\n            console.log(names[i], taker.ok(0, i));\n            if (!taker.ok(0, i)) console.logBytes4(sel);\n        }\n        uint256 creditA1 = adapter.marketData(IdLib.toId(mA)).netCredit;\n        uint256 creditB1 = adapter.marketData(IdLib.toId(mB)).netCredit;\n        (uint128 cA,,) = midnight.updatePositionView(mA, IdLib.toId(mA), address(adapter));\n        (uint128 cB,,) = midnight.updatePositionView(mB, IdLib.toId(mB), address(adapter));\n        console.log(\"stored netCredit A before/after, Midnight credit A:\", creditA0, creditA1, cA);\n        console.log(\"stored netCredit B before/after, Midnight credit B:\", creditB0, creditB1, cB);\n        console.log(\"vault allocation adapterId vs stored A+B:\", vault.allocation(keccak256(abi.encode(\"this\", address(adapter)))), creditA1 + creditB1);\n        console.log(\"totalAssets before / after:\", ta0, vault.totalAssets());\n        assertFalse(taker.ok(0, 1), \"forceDeallocate on locked market succeeded\");\n        assertFalse(taker.ok(0, 3), \"shortfall sale while other sale in progress succeeded\");\n        assertEq(creditA1, cA);\n        assertEq(creditB1, cB);\n        assertEq(vault.allocation(keccak256(abi.encode(\"this\", address(adapter)))), creditA1 + creditB1);\n    }\n\n    /// @dev Taker (borrower) sells credit into an adapter buy offer in B; inside its onSell it deposits and takes an adapter buy offer in A.\n    function testNestedDepositAndBuyDuringAdapterBuy() public {\n        _setUpPositions();\n        uint256 units = 5_000 * oneToken;\n        // Fund the vault again so the adapter can buy.\n        deal(address(underlyingToken), depositor, 20_000 * oneToken);\n        vm.startPrank(depositor);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), type(uint256).max);\n        vault.deposit(20_000 * oneToken, depositor);\n        vm.stopPrank();\n        (Offer memory offerB, bytes memory rdB) = _adapterBuyOffer(mB, units);\n        (Offer memory offerA, bytes memory rdA) = _adapterBuyOffer(mA, units);\n        deal(address(collateralToken), address(taker), units * 10e18 / oneToken);\n        taker.exec(address(collateralToken), abi.encodeCall(IERC20.approve, (address(midnight), type(uint256).max)));\n        taker.exec(address(midnight), abi.encodeCall(IMidnight.supplyCollateral, (mA, 0, units * 4e18 / oneToken, address(taker))));\n        taker.exec(address(midnight), abi.encodeCall(IMidnight.supplyCollateral, (mB, 0, units * 4e18 / oneToken, address(taker))));\n        uint256 dep = 10_000 * oneToken;\n        taker.addCall(0, address(vault), abi.encodeWithSignature(\"deposit(uint256,address)\", dep, address(taker)));\n        taker.addCall(0, address(midnight), abi.encodeCall(IMidnight.take, (offerA, rdA, units, address(taker), address(taker), address(taker), \"\")));\n        uint256 ta0 = vault.totalAssets();\n        uint256 p0 = _sharePrice();\n        taker.exec(address(midnight), abi.encodeCall(IMidnight.take, (offerB, rdB, units, address(taker), address(taker), address(taker), \"\")));\n        console.log(\"nested deposit ok / nested buy ok:\", taker.ok(0, 0), taker.ok(0, 1));\n        if (!taker.ok(0, 1)) console.logBytes(taker.ret(0, 1));\n        uint256 shares = taker.ok(0, 0) ? abi.decode(taker.ret(0, 0), (uint256)) : 0;\n        console.log(\"totalAssets before / in callback / after:\", ta0, taker.vaultTotalAssetsAtEntry(0), vault.totalAssets());\n        console.log(\"share price before / after:\", p0, _sharePrice());\n        console.log(\"nested shares / reference shares next tx:\", shares, vault.previewDeposit(dep));\n        console.log(\"redeem value of nested shares vs deposit:\", vault.previewRedeem(shares), dep);\n        assertLe(vault.previewRedeem(shares), dep);\n        uint256 sA = adapter.marketData(IdLib.toId(mA)).netCredit;\n        uint256 sB = adapter.marketData(IdLib.toId(mB)).netCredit;\n        (uint128 cA,,) = midnight.updatePositionView(mA, IdLib.toId(mA), address(adapter));\n        (uint128 cB,,) = midnight.updatePositionView(mB, IdLib.toId(mB), address(adapter));\n        console.log(\"stored vs Midnight A:\", sA, cA);\n        console.log(\"stored vs Midnight B:\", sB, cB);\n        assertEq(sA, cA);\n        assertEq(sB, cB);\n        assertEq(vault.allocation(keccak256(abi.encode(\"this\", address(adapter)))), sA + sB);\n    }\n}\n"
  }
 },
 "notCovered": [
  "Nested trades where Midnight lossFactor != 0 (bad debt realised in the market being sold, or liquidation inside the callback)",
  "Two different adapters of the same vault trading against each other in a nested way",
  "Enter-gated markets (admit/unadmit during a nested forceDeallocate)",
  "A taker callback that partially fills the same adapter offer twice (the shortfallAllowance piecewise-fill issue is already held and was excluded)",
  "Full repository test suite: only the Midnight integration tests (8 inherited) were run, because a full build was killed by this machine (solc SIGKILL)",
  "Prior-audit PDFs were not read text-by-text, since no candidate needed a check against them"
 ]
}