{
 "lead": "funding: buy funding and mid-buy valuation in MidnightAdapter.onBuy (idle funding, liquidity/other adapter funding, another MidnightAdapter as funding adapter, self-funding from another market and from the bought market; order of stored writes, transient pre-buy values used by realAssets during vault.accrueInterest, funding withdrawal, duration and vault cap checks, vault.allocate)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "blocked": false,
 "hasCandidates": false,
 "candidates": [],
 "summary": "No fault found in the onBuy funding path that an untrusted account can drive. Every funding mode was exercised on the real Midnight and VaultV2 (MidnightAdapterIntegrationTest base) with a ratified maker buy offer taken by an untrusted seller: recorded totalAssets and the share price are unchanged by the buy, idle assets are unchanged when funding comes from a market or another adapter, the vault's cap allocations equal the adapter's stored net credit after every mode, and no loan token is left on either adapter. The only value movements are (a) rate-rounding dust in the vault's favour (3,895,798,665 wei on 1.5e23, below 1e-12), which NatSpec accepts, and (b) the discount on repaid credit being realised when it is withdrawn at par to fund a buy, which is the same effect as an allocator deallocate and is bounded by the vault's maxRate. Nothing was fabricated; all numbers below are printed by the test.",
 "verificationTests": {
  "path": "test/poc/FundingOnBuyPoc.t.sol",
  "inherits": "test/integration/MidnightAdapterIntegrationTest.sol (real Midnight, real VaultV2, price sub-ratifier)",
  "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol && forge test --match-path test/poc/FundingOnBuyPoc.t.sol -vv",
  "note": "The sandbox's solc store was read-only; compilers were fetched into a writable XDG_DATA_HOME. forge test --match-path still compiled the whole tree once (about 6 minutes), after which reruns were instant.",
  "output": "Compiler run successful!\nRan 15 tests for test/poc/FundingOnBuyPoc.t.sol:FundingOnBuyPoc\n[PASS] testDustTakesEarlyInterest() (gas: 27867499)\nLogs:\n  buyerAssets paid over 100 dust takes 0\n  realAssets before/after              49705035000015209812937 49705035000015209813036\n  netRate before/after                 9812017633 9812017633\n  realAssets gain                      99\n[PASS] testForceDeallocate() (gas: 1751851)\n[PASS] testForceSell() (gas: 1654014)\n[PASS] testFundingFromOtherMidnightAdapter() (gas: 13173462)\nLogs:\n  buyerAssets                  994100700000000000000\n  A netCredit before/after     20000000000000000000000 19005899300000000000000\n  B netCredit                  1000000000000000000000\n  vault idle before/after      80117986000000000000000 80117986000000000000000\n  totalAssets before/after     100000000000000000000000 100000000000000000000000\n  A alloc / B alloc            19005899300000000000000 1000000000000000000000\n  A / B token balance          0 0\n[PASS] testIdleFundingShareholderTakerNoGain() (gas: 1782878)\nLogs:\n  buyerAssets            9941007000000000000000\n  sellerAssets           9941007000000000000000\n  totalAssets before     150000000000000000000000\n  totalAssets after      150000000000000000000000\n  idle+realAssets before 150000000000000000000000\n  idle+realAssets after  150000000000003895798665\n  previewRedeem before   50000000000000000000000\n  previewRedeem after    50000000000000000000000\n  adapter token balance  0\n  adapterId allocation   10000000000000000000000\n  stored netCredit       10000000000000000000000\n[PASS] testMakerBuy() (gas: 1130891)\n[PASS] testMakerSell() (gas: 1922650)\n[PASS] testRepayWithdrawRedeem() (gas: 1781958)\n[PASS] testSelfFundingOtherMarket() (gas: 2856067)\nLogs:\n  buyerAssets               9941007000000000000000\n  vault idle before/after   50294965000000000000000 50294965000000000000000\n  Z netCredit before/after  50000000000000000000000 40058993000000000000000\n  X netCredit               10000000000000000000000\n  totalAssets before/after  100000000000000000000000 100000000000000000000000\n  idle+real before/after    100000000000045094075678 100058644982634270427825\n  adapterId alloc before/after 50000000000000000000000 50058993000000000000000\n  adapter token balance     0\n  real assets gain from par withdrawal 58644982589176352147\n  expected gain (buyerAssets discount) 58644982586134389561\n[PASS] testSelfFundingSameMarket() (gas: 2442065)\nLogs:\n  buyerAssets               9941007000000000000000\n  vault idle before/after   80117986000000000000000 80117986000000000000000\n  X netCredit before/after  20000000000000000000000 20058993000000000000000\n  totalAssets before/after  100000000000000000000000 100000000000000000000000\n  idle+real before/after    100000000000006083925174 100058644982601201870624\n  adapterId allocation      20058993000000000000000\n  adapter token balance     0\n[PASS] testSelfFundingSameMarketFreshAdapterReverts() (gas: 12729370)\n[PASS] testTakeOneSecondBeforeMaturity() (gas: 1233317)\nLogs:\n  buyerAssets 9941007000000000000000\n  netRate (per second, WAD) 5934308264746217\n  realAssets now       9941007000000000003558\n  realAssets at maturity 10000000000000000000000\n[PASS] testTakerBuy() (gas: 1167651)\n[PASS] testTakerSell() (gas: 1960244)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17210136)\nSuite result: ok. 15 passed; 0 failed; 0 skipped; finished in 121.51ms (295.63ms CPU time)\nRan 1 test suite in 133.99ms (121.51ms CPU time): 15 tests passed, 0 failed, 0 skipped (15 total tests)\n",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {MidnightAdapterIntegrationTest} from \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\nimport {IMidnightAdapter, IMidnightAdapterBase, MarketData} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {IMidnightAdapterFactory} from \"../../src/adapters/midnight/interfaces/IMidnightAdapterFactory.sol\";\nimport {IVaultV2} from \"../../src/interfaces/IVaultV2.sol\";\nimport {ErrorsLib} from \"../../src/libraries/ErrorsLib.sol\";\nimport {SafeERC20Lib} from \"../../src/libraries/SafeERC20Lib.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {Market, Offer} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {HashLib} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {TickLib} from \"../../lib/midnight/src/libraries/TickLib.sol\";\n\n/// @dev PoC checks for lead \"funding\": buy funding and mid-buy valuation in MidnightAdapter.onBuy.\ncontract FundingOnBuyPoc is MidnightAdapterIntegrationTest {\n    address internal attacker = makeAddr(\"attacker\");\n    uint256 internal salt;\n\n    function _ratifiedBuyOffer(IMidnightAdapter _adapter, Market memory market, uint256 units, bytes memory callbackData)\n        internal\n        returns (Offer memory offer, bytes memory ratifierData)\n    {\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(\"poc buy\", market.maturity, units, salt++)),\n            callback: address(_adapter),\n            callbackData: callbackData,\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        bytes32[] memory proof = new bytes32[](0);\n        ratifierData = abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), proof, address(0)));\n    }\n\n    function _collateralize(Market memory market, uint256 units) internal {\n        uint256 collateral = units * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, collateralToken.balanceOf(borrower) + collateral);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        vm.stopPrank();\n    }\n\n    /// @dev Borrower sells `units` of credit to the adapter through a ratified maker buy offer with the given funding.\n    function _sellToAdapter(IMidnightAdapter _adapter, Market memory market, uint256 units, bytes memory callbackData)\n        internal\n        returns (uint256 buyerAssets, uint256 sellerAssets)\n    {\n        (Offer memory offer, bytes memory ratifierData) = _ratifiedBuyOffer(_adapter, market, units, callbackData);\n        _collateralize(market, units);\n        vm.prank(borrower);\n        (buyerAssets, sellerAssets) = midnight.take(offer, ratifierData, units, borrower, borrower, address(0), \"\");\n    }\n\n    function _repay(Market memory market, uint256 units) internal {\n        deal(address(underlyingToken), borrower, underlyingToken.balanceOf(borrower) + units);\n        vm.startPrank(borrower);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), units);\n        midnight.repay(market, units, borrower, address(0), \"\");\n        vm.stopPrank();\n    }\n\n    function _netCredit(IMidnightAdapter _adapter, Market memory market) internal view returns (uint256 nc) {\n        (nc,,,,,) = _adapterMarketData(_adapter, IdLib.toId(market));\n    }\n\n    function _adapterMarketData(IMidnightAdapter _adapter, bytes32 id)\n        internal\n        view\n        returns (uint128 netCredit, uint64 netRate, uint40 maturity, uint8 index, bool forceSellable, bool forceRemoved)\n    {\n        MarketData memory md = _adapter.marketData(id);\n        return (md.netCredit, md.netRate, md.maturity, md.index, md.forceSellable, md.forceRemoved);\n    }\n\n    function _realTotal() internal view returns (uint256) {\n        return underlyingToken.balanceOf(address(vault)) + adapter.realAssets();\n    }\n\n    /* 1. Idle funding: a shareholder taker cannot move the share price. */\n    function testIdleFundingShareholderTakerNoGain() public {\n        Market memory market = _market(7 days);\n        uint256 units = 10_000 * oneToken;\n\n        // Attacker is a shareholder and the credit seller (borrower role is replayed by attacker's own position).\n        deal(address(underlyingToken), attacker, 50_000 * oneToken);\n        vm.startPrank(attacker);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), 50_000 * oneToken);\n        uint256 shares = vault.deposit(50_000 * oneToken, attacker);\n        vm.stopPrank();\n\n        vm.warp(vm.getBlockTimestamp() + 1 days);\n        uint256 priceBefore = vault.previewRedeem(shares);\n        uint256 totalBefore = vault.totalAssets();\n        uint256 realBefore = _realTotal();\n\n        (uint256 buyerAssets, uint256 sellerAssets) = _sellToAdapter(adapter, market, units, abi.encode(address(0), \"\"));\n\n        uint256 priceAfter = vault.previewRedeem(shares);\n        uint256 totalAfter = vault.totalAssets();\n        uint256 realAfter = _realTotal();\n        console.log(\"buyerAssets           \", buyerAssets);\n        console.log(\"sellerAssets          \", sellerAssets);\n        console.log(\"totalAssets before    \", totalBefore);\n        console.log(\"totalAssets after     \", totalAfter);\n        console.log(\"idle+realAssets before\", realBefore);\n        console.log(\"idle+realAssets after \", realAfter);\n        console.log(\"previewRedeem before  \", priceBefore);\n        console.log(\"previewRedeem after   \", priceAfter);\n        console.log(\"adapter token balance \", underlyingToken.balanceOf(address(adapter)));\n        console.log(\"adapterId allocation  \", vault.allocation(adapter.adapterId()));\n        console.log(\"stored netCredit      \", _netCredit(adapter, market));\n\n        assertEq(totalAfter, totalBefore, \"totalAssets moved by the buy\");\n        assertEq(priceAfter, priceBefore, \"share price moved by the buy\");\n        // Rounding of the rate down can only add dust in favour of the vault.\n        assertGe(realAfter, realBefore);\n        // The rate is stored per second in WAD and rounded down: the dust left is below 1e-12 of total assets.\n        assertLe(realAfter - realBefore, realBefore / 1e12, \"real assets changed by more than rate rounding\");\n        assertEq(underlyingToken.balanceOf(address(adapter)), 0, \"tokens left on adapter\");\n        assertEq(vault.allocation(adapter.adapterId()), _netCredit(adapter, market), \"cap allocation != stored net credit\");\n    }\n\n    /* 2. Self-funding from another market of the same adapter. */\n    function testSelfFundingOtherMarket() public {\n        Market memory z = _market(14 days);\n        Market memory x = _market(7 days);\n        uint256 unitsZ = 50_000 * oneToken;\n        _sellToAdapter(adapter, z, unitsZ, abi.encode(address(0), \"\"));\n        // Early repayment creates withdrawable liquidity in Z.\n        _repay(z, 20_000 * oneToken);\n\n        uint256 idleBefore = underlyingToken.balanceOf(address(vault));\n        uint256 totalBefore = vault.totalAssets();\n        uint256 realBefore = _realTotal();\n        uint256 zBefore = _netCredit(adapter, z);\n        uint256 allocBefore = vault.allocation(adapter.adapterId());\n\n        uint256 unitsX = 10_000 * oneToken;\n        (uint256 buyerAssets,) = _sellToAdapter(adapter, x, unitsX, abi.encode(address(adapter), abi.encode(z)));\n\n        uint256 idleAfter = underlyingToken.balanceOf(address(vault));\n        uint256 realAfter = _realTotal();\n        console.log(\"buyerAssets              \", buyerAssets);\n        console.log(\"vault idle before/after  \", idleBefore, idleAfter);\n        console.log(\"Z netCredit before/after \", zBefore, _netCredit(adapter, z));\n        console.log(\"X netCredit              \", _netCredit(adapter, x));\n        console.log(\"totalAssets before/after \", totalBefore, vault.totalAssets());\n        console.log(\"idle+real before/after   \", realBefore, realAfter);\n        console.log(\"adapterId alloc before/after\", allocBefore, vault.allocation(adapter.adapterId()));\n        console.log(\"adapter token balance    \", underlyingToken.balanceOf(address(adapter)));\n\n        assertEq(idleAfter, idleBefore, \"idle changed\");\n        assertEq(_netCredit(adapter, z), zBefore - buyerAssets, \"Z not reduced by buyerAssets\");\n        assertEq(_netCredit(adapter, x), unitsX, \"X net credit\");\n        assertEq(vault.totalAssets(), totalBefore, \"recorded totalAssets moved\");\n        assertEq(vault.allocation(adapter.adapterId()), _netCredit(adapter, z) + _netCredit(adapter, x), \"allocation drift\");\n        assertEq(underlyingToken.balanceOf(address(adapter)), 0, \"tokens left on adapter\");\n        // Withdrawing repaid credit at par realizes the discount on the withdrawn credit (design, same as deallocate).\n        console.log(\"real assets gain from par withdrawal\", realAfter - realBefore);\n        uint256 zRate;\n        (, zRate,,,,) = _adapterMarketData(adapter, IdLib.toId(z));\n        uint256 ttmZ = z.maturity - block.timestamp;\n        uint256 expectedGain = buyerAssets - buyerAssets * WAD / (WAD + zRate * ttmZ);\n        console.log(\"expected gain (buyerAssets discount)\", expectedGain);\n        assertApproxEqRel(realAfter - realBefore, expectedGain, 1e9); // 1e-9 relative, rate rounding only\n    }\n\n    /* 3. Self-funding from the market being bought. */\n    function testSelfFundingSameMarket() public {\n        Market memory x = _market(7 days);\n        uint256 units1 = 20_000 * oneToken;\n        _sellToAdapter(adapter, x, units1, abi.encode(address(0), \"\"));\n        _repay(x, 15_000 * oneToken);\n\n        uint256 idleBefore = underlyingToken.balanceOf(address(vault));\n        uint256 totalBefore = vault.totalAssets();\n        uint256 realBefore = _realTotal();\n        uint256 xBefore = _netCredit(adapter, x);\n\n        uint256 units2 = 10_000 * oneToken;\n        (uint256 buyerAssets,) = _sellToAdapter(adapter, x, units2, abi.encode(address(adapter), abi.encode(x)));\n\n        console.log(\"buyerAssets              \", buyerAssets);\n        console.log(\"vault idle before/after  \", idleBefore, underlyingToken.balanceOf(address(vault)));\n        console.log(\"X netCredit before/after \", xBefore, _netCredit(adapter, x));\n        console.log(\"totalAssets before/after \", totalBefore, vault.totalAssets());\n        console.log(\"idle+real before/after   \", realBefore, _realTotal());\n        console.log(\"adapterId allocation     \", vault.allocation(adapter.adapterId()));\n        console.log(\"adapter token balance    \", underlyingToken.balanceOf(address(adapter)));\n        assertEq(underlyingToken.balanceOf(address(vault)), idleBefore);\n        assertEq(_netCredit(adapter, x), xBefore + units2 - buyerAssets);\n        assertEq(vault.allocation(adapter.adapterId()), _netCredit(adapter, x));\n        assertEq(vault.totalAssets(), totalBefore);\n        assertEq(underlyingToken.balanceOf(address(adapter)), 0);\n    }\n\n    /* 3b. A fresh adapter cannot fund its first buy of a family from that same market: deallocate runs before allocate. */\n    function testSelfFundingSameMarketFreshAdapterReverts() public {\n        Market memory x = _market(7 days);\n        _sellToAdapter(adapter, x, 20_000 * oneToken, abi.encode(address(0), \"\"));\n        _repay(x, 15_000 * oneToken);\n\n        IMidnightAdapter b = _deploySecondAdapter();\n        uint256 units = 1_000 * oneToken;\n        (Offer memory offer, bytes memory ratifierData) =\n            _ratifiedBuyOffer(b, x, units, abi.encode(address(b), abi.encode(x)));\n        _collateralize(x, units);\n        vm.prank(borrower);\n        vm.expectRevert(ErrorsLib.ZeroAllocation.selector);\n        midnight.take(offer, ratifierData, units, borrower, borrower, address(0), \"\");\n    }\n\n    /* 4. Funding from a second MidnightAdapter of the same vault. */\n    function testFundingFromOtherMidnightAdapter() public {\n        Market memory x = _market(7 days);\n        _sellToAdapter(adapter, x, 20_000 * oneToken, abi.encode(address(0), \"\"));\n        _repay(x, 15_000 * oneToken);\n        IMidnightAdapter b = _deploySecondAdapter();\n\n        uint256 idleBefore = underlyingToken.balanceOf(address(vault));\n        uint256 totalBefore = vault.totalAssets();\n        uint256 aBefore = _netCredit(adapter, x);\n        uint256 units = 1_000 * oneToken;\n        (uint256 buyerAssets,) = _sellToAdapter(b, x, units, abi.encode(address(adapter), abi.encode(x)));\n\n        console.log(\"buyerAssets                 \", buyerAssets);\n        console.log(\"A netCredit before/after    \", aBefore, _netCredit(adapter, x));\n        console.log(\"B netCredit                 \", _netCredit(b, x));\n        console.log(\"vault idle before/after     \", idleBefore, underlyingToken.balanceOf(address(vault)));\n        console.log(\"totalAssets before/after    \", totalBefore, vault.totalAssets());\n        console.log(\"A alloc / B alloc           \", vault.allocation(adapter.adapterId()), vault.allocation(b.adapterId()));\n        console.log(\"A / B token balance         \", underlyingToken.balanceOf(address(adapter)), underlyingToken.balanceOf(address(b)));\n        assertEq(_netCredit(adapter, x), aBefore - buyerAssets);\n        assertEq(_netCredit(b, x), units);\n        assertEq(underlyingToken.balanceOf(address(vault)), idleBefore);\n        assertEq(vault.totalAssets(), totalBefore);\n        assertEq(vault.allocation(adapter.adapterId()), _netCredit(adapter, x));\n        assertEq(vault.allocation(b.adapterId()), units);\n        assertEq(underlyingToken.balanceOf(address(adapter)), 0);\n        assertEq(underlyingToken.balanceOf(address(b)), 0);\n    }\n\n    /* 5. Dust takes: units = 1 at price 0.994 give buyerAssets = 0; measure the early-interest effect. */\n    function testDustTakesEarlyInterest() public {\n        Market memory x = _market(7 days);\n        _sellToAdapter(adapter, x, 50_000 * oneToken, abi.encode(address(0), \"\"));\n        uint256 realBefore = adapter.realAssets();\n        (, uint64 rateBefore,,,,) = _adapterMarketData(adapter, IdLib.toId(x));\n\n        (Offer memory offer, bytes memory ratifierData) = _ratifiedBuyOffer(adapter, x, 1000, abi.encode(address(0), \"\"));\n        _collateralize(x, 1000);\n        uint256 totalBuyer;\n        for (uint256 i; i < 100; i++) {\n            vm.prank(borrower);\n            (uint256 bA,) = midnight.take(offer, ratifierData, 1, borrower, borrower, address(0), \"\");\n            totalBuyer += bA;\n        }\n        (, uint64 rateAfter,,,,) = _adapterMarketData(adapter, IdLib.toId(x));\n        console.log(\"buyerAssets paid over 100 dust takes\", totalBuyer);\n        console.log(\"realAssets before/after             \", realBefore, adapter.realAssets());\n        console.log(\"netRate before/after                \", rateBefore, rateAfter);\n        console.log(\"realAssets gain                     \", adapter.realAssets() - realBefore);\n        assertEq(totalBuyer, 0);\n    }\n\n    /* 6. Take one second before maturity: implied rate is huge but fits; value jumps to par at maturity. */\n    function testTakeOneSecondBeforeMaturity() public {\n        Market memory x = _market(7 days);\n        vm.warp(x.maturity - 1);\n        uint256 units = 10_000 * oneToken;\n        (uint256 buyerAssets,) = _sellToAdapter(adapter, x, units, abi.encode(address(0), \"\"));\n        (, uint64 rate,,,,) = _adapterMarketData(adapter, IdLib.toId(x));\n        console.log(\"buyerAssets\", buyerAssets);\n        console.log(\"netRate (per second, WAD)\", rate);\n        console.log(\"realAssets now      \", adapter.realAssets());\n        vm.warp(x.maturity);\n        console.log(\"realAssets at maturity\", adapter.realAssets());\n        assertEq(adapter.realAssets(), units);\n    }\n\n    function _deploySecondAdapter() internal returns (IMidnightAdapter b) {\n        uint256[] memory durations = new uint256[](1);\n        durations[0] = 7 days;\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight)))\n        );\n        b = IMidnightAdapter(factory.createMidnightAdapter(address(vault), durations, address(0), bytes32(0)));\n        _submitAndSet(address(b), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (90 days)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(b))));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(b), true)));\n        vm.prank(allocator);\n        b.setIsSubRatifier(address(priceSubRatifier), true);\n        _increaseCaps(abi.encode(\"this\", address(b)));\n        _increaseCaps(abi.encode(\"this/duration\", address(b), 7 days));\n    }\n}\n"
 },
 "lowInfo": [
  {
   "title": "Self-funding a buy from the bought market is impossible for the first position of a market family: vault.deallocate runs before vault.allocate and requires a non-zero allocation",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:579-584",
    "src/adapters/midnight/MidnightAdapter.sol:606-611",
    "src/VaultV2.sol:576-581"
   ],
   "detail": "In onBuy the funding withdrawal (withdrawToVault + vault.deallocate with the negative change) is executed before vault.allocate adds the bought net credit. VaultV2.deallocateInternal requires `_caps.allocation > 0` for every returned id before applying the change. When the adapter holds nothing yet in the market's adapterId, family id or collateral-token id (a fresh adapter, or the first market of a family), funding the buy from that same market's withdrawable liquidity reverts with ZeroAllocation even though the position would be positive after the buy. Test testSelfFundingSameMarketFreshAdapterReverts shows the revert for a second adapter of the same vault (first branch buys 20,000 units into market X, borrower repays 15,000, the second adapter's buy of 1,000 units funded from X reverts with ErrorsLib.ZeroAllocation). When the family already has an allocation (testSelfFundingSameMarket) the same flow succeeds and the final allocation equals stored net credit (20,058,993,000,000,000,000,000 after buying 10,000 units and withdrawing 9,941.007). Impact: operational only; allocators must fund the first buy of a family from idle or another source. Suggested fix: document the constraint in the BUYING NatSpec, or, if desired, let the vault tolerate a zero pre-allocation for duration-free ids when the caller is the adapter itself (a VaultV2 change, likely not worth it)."
  },
  {
   "title": "Funding a buy from a market with early-repaid credit realises the whole discount of the withdrawn credit immediately",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:579-581",
    "src/adapters/midnight/MidnightAdapter.sol:716-738",
    "src/adapters/midnight/MidnightAdapter.sol:19-21",
    "src/adapters/midnight/MidnightAdapter.sol:836-863"
   ],
   "detail": "realAssets values every unit of net credit at netCredit / (1 + netRate * ttm) until maturity, including credit that borrowers have already repaid and that is withdrawable at par on Midnight. withdrawToVault (used by self-funded buys and by allocator deallocates) moves `withdrawnAssets` units out at par, so the adapter's book value jumps by withdrawnAssets * netRate * ttm / (1 + netRate * ttm) in that transaction. testSelfFundingOtherMarket: market Z bought at price 0.994 with 14 days to maturity, 20,000 units repaid early; a 10,000-unit buy in market X self-funded from Z withdraws 9,941.007 and raises idle+realAssets by 58,644,982,589,176,352,147 wei (58.64 tokens, 0.59% of the withdrawal), matching the formula within rate rounding (expected 58,644,982,586,134,389,561). Recorded totalAssets does not move in the transaction (the mid-buy accrueInterest runs before the withdrawal and firstTotalAssets is already set), so the gain is distributed by later accruals under maxRate; an untrusted taker cannot choose the funding source because callbackData is part of the ratified offer hash (HashLib.hashOffer includes keccak256(offer.callbackData)). This is conservative valuation, not a loss, and matches what an allocator deallocate already does. Suggested improvement: mention in the VALUATION NatSpec that repaid (withdrawable) credit is still discounted until withdrawn, so withdrawals and self-funded buys realise interest early by design."
  }
 ],
 "covered": [
  "Idle funding (callbackData abi.encode(address(0), \"\")): taker who is also a shareholder deposits 50,000, sells 10,000 units; totalAssets 150,000e18 before and after, previewRedeem identical, adapter token balance 0, adapterId allocation == stored netCredit (10,000e18). Only rate-rounding dust (3,895,798,665 wei) is added to idle+realAssets, in the vault's favour, as accepted by the VALUATION NatSpec (\"Rates are rounded down on buys and sales, which can accrue some interest earlier\").",
  "Self-funding from another market of the same adapter (abi.encode(adapter, abi.encode(Z))): idle unchanged, Z stored net credit reduced by exactly buyerAssets, X stored net credit == units, adapterId allocation == sum of stored net credits, no tokens left, recorded totalAssets unchanged.",
  "Self-funding from the bought market itself: same invariants hold; final net credit = old + units - buyerAssets; allocation consistent; fresh-family case reverts with ZeroAllocation (Informational 1).",
  "Funding from a second MidnightAdapter of the same vault (its deallocate routes sender != self to withdrawToVault): A's stored net credit falls by buyerAssets, B's equals units, idle unchanged, both allocations consistent, no tokens left on A or B.",
  "Order of stored writes vs. the mid-buy vault.accrueInterest: realAssets returns the pre-buy (netCredit - boughtNetCredit, oldNetRate) pair for the in-progress market and the stored maturity, which is set before the call when the market is new; verified indirectly by totalAssets being unchanged in every mode, including when the adapter's onBuy accrual is the first accrual of the transaction.",
  "Cap checks: vault ids receive change = newNetCredit - oldNetCredit in allocate after the funding deallocate applied its own negative change; duration allocations are computed from stored net credit after both updates; relative caps use firstTotalAssets fixed by the first accrual, so a flash deposit by the taker cannot inflate them.",
  "Tokens left on the adapter: zero after every mode (withdraw -> vault pulls buyerAssets -> vault pushes buyerAssets -> Midnight pulls buyerAssets).",
  "Dust takes (units = 1, price 0.994 => buyerAssets = 0): 100 takes add 99 wei to realAssets and leave netRate unchanged; the taker gives credit away, no gain. Accepted in NatSpec (0-asset buys).",
  "Take one second before maturity: implied rate 5,934,308,264,746,217 WAD/s fits uint64, realAssets reaches par (10,000e18) at maturity; no overflow at the price ratifier's tick.",
  "Taker cannot alter the funding source: callbackData is hashed into the ratified offer (HashLib.hashOffer / hashPriceRatifierV1Offer).",
  "Checked against prior audit drafts' scope and the two excluded items (split shortfall allowance, sub-gate revocation leaving signatures valid): neither item above overlaps."
 ],
 "notCovered": [
  "Nested trade: a taker contract whose own onBuy (when buying from an adapter sell offer) takes an adapter buy offer in another market, so the adapter's onBuy accrues the vault while its stored net credit for the market being sold is stale (NatSpec MISC acknowledges adapters of the same vault may not be able to trade with each other). Not tested for lack of time; belongs to the reentrancy lead.",
  "Funding from a MorphoMarketV1AdapterV2 or MorphoVaultV1Adapter liquidity adapter: reasoned from VaultV2.deallocateInternal (no accrual, pulls `assets` from the funding adapter) but not executed.",
  "Markets with a non-zero loss factor or a non-zero continuous/settlement fee in the funding path (loss-realisation lead).",
  "The full repository test suite was not run; the 9 inherited MidnightAdapterIntegrationTest tests pass in the PoC run above.",
  "The prior audit PDFs (audits/2026-10-12-*.pdf) were present in the clone but not text-extracted here; the overlap check relied on the two excluded items named in the brief."
 ]
}