{
 "group": "fix-force-ratify",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "blocked": false,
 "fixes": [
  {
   "priorId": "TRST-L-1",
   "change": "The forceDeallocate branch no longer takes a caller-supplied buy offer. It decodes (Market, taker), builds its own sell offer (maker and ratifier = adapter, tick 0, reduceOnly, callback 0, group 0, maxAssets = uint128 max), pulls assets + settlement fee from the caller, and takes that offer on Midnight on behalf of the taker with itself as buyer callback and payer. The caller must be the taker or Midnight-authorized by the taker, the taker must hold at least 1 vault share and must have authorized the adapter on Midnight. isRatified is bypassed through the transient inForceDeallocate, cleared in onBuy.",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:421-483",
    "src/adapters/midnight/MidnightAdapter.sol:488-493",
    "src/adapters/midnight/MidnightAdapter.sol:519-526",
    "lib/midnight/src/Midnight.sol:320-472"
   ],
   "tested": true,
   "note": "The reported problem (a third party spending the victim's offer) is gone: no user offer exists any more. Tested for new faults: (1) numbers of one exit with a 0.005% settlement fee: 1000000000000000000007 units bought, 1000050000000000000008 paid, vault idle +1000000000000000000007, adapter dust 0, both transient flags false afterwards (test_01); (2) the self-made offer cannot be taken outside the force path, three ratifierData variants revert, two of them with IncorrectCallbackAddress 0x30119bd7 (test_02); (3) a zero-asset call on a sibling-maturity market the adapter does not hold changes nothing, 1 wei reverts with MakerCreditOrDebtIncreased (test_03); (4) Midnight's consumed[adapter][0] stays 0 because tickToPrice(0) is 0, so allocator offers of group 0 are not eaten (test_04) and setConsumed(0, uint128 max) does not block exits (test_05). Both hypotheses of (4) were my candidates and the tests refuted them. Between setting the flag and onBuy, Midnight.take only calls isRatified and the view gate functions, so I found no reentry window. No new fault found."
  },
  {
   "priorId": "3.2.2",
   "change": "isRatified now requires offer.market.midnight == midnight. It still does not bind msg.sender. A new early return `if (inForceDeallocate) return CALLBACK_SUCCESS;` sits before every check.",
   "status": "partial",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:488-506"
   ],
   "tested": true,
   "note": "Binding to the Midnight named in the offer is there: an offer naming another Midnight reverts with NotMidnight even when its root is ratified (test_09). The caller is still unbound, and while the transient flag is set the function approves any offer for any caller. That window only exists inside the adapter's own take (see lowInfo 1). No new fault found."
  },
  {
   "priorId": "TRST-R-12",
   "change": "Same change as 3.2.2: offer.market.midnight is checked. No chain id check and no explanatory comment were added.",
   "status": "partial",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:494-497",
    "lib/midnight/src/Midnight.sol:750-754"
   ],
   "tested": true,
   "note": "test_09: for a root-ratified offer whose market.chainId is block.chainid + 1, adapter.isRatified still returns success, and Midnight.take reverts (market creation requires market.chainId == block.chainid). The remaining gap is the reported one (an external reader of isRatified), not a new one."
  },
  {
   "priorId": "3.2.9",
   "change": "None in the reported respect: isRatified has no check that offer.ratifier equals the adapter.",
   "status": "unchanged",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:488-506"
   ],
   "tested": false,
   "note": "The register marks it present. Read only. Midnight still calls the ratifier named in the offer, so this stays a concern for direct readers only."
  },
  {
   "priorId": "3.5.1",
   "change": "The factory no longer stores a durations array. Each createMidnightAdapter call passes durations as calldata; the adapter constructor validates them (at most 8, strictly increasing so the first is > 0, each <= uint32 max) and packs them once into the immutable packedDurations.",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:26-41",
    "src/adapters/midnight/MidnightAdapter.sol:152-171",
    "src/adapters/midnight/libraries/PackedDurationsLib.sol:1-31"
   ],
   "tested": true,
   "note": "The storage array the gas note was about is gone. test_08: 8 durations with uint32 max at index 7 round-trip through pack and durations() (4294967295); 9 durations, a zero, 2^32 and equal neighbours all revert; an empty array deploys. No packing or overflow fault found: each value is bounded to 32 bits before the shift and get() masks 32 bits."
  },
  {
   "priorId": "TRST-R-1",
   "change": "Durations are per deployment: createMidnightAdapter(parentVault, durations, enterGateFactory, preSalt).",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:29-41",
    "src/adapters/midnight/MidnightAdapter.sol:161-169"
   ],
   "tested": true,
   "note": "Two adapters of one vault can now have different ladders (test_08 deploys three on the same vault). The ladder is immutable per adapter, and duration ids contain the adapter address, so a duration cap never spans two adapters (the adapter-local point of TRST-R-10 remains)."
  },
  {
   "priorId": "TRST-R-4",
   "change": "salt = keccak256(abi.encode(preSalt, msg.sender)); the mapping midnightAdapter[parentVault][salt] was removed, isMidnightAdapter was renamed isCreated.",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:15,28,35-39"
   ],
   "tested": true,
   "note": "test_07: an attacker who front-runs with the victim's arguments and preSalt gets 0x1c8e1561958999eAf5f7D7b88d4F78c56f7AD160, the victim still deploys 0xE5864780419774B5864884aF7F953eEaCEa179Ad. A second identical call by the same sender reverts (CREATE2 collision). The NatSpec states the remaining case: a shared msg.sender such as a bundler must put the initiator into preSalt."
  },
  {
   "priorId": "TRST-R-5",
   "change": "None in the reported respect: the direct setIsRootRatified takes no nonce and does not increment rootNonce. It only gained the onBehalf parameter.",
   "status": "unchanged",
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:33-48",
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:37-52"
   ],
   "tested": true,
   "note": "test_06 prints rootNonce 1 after a signed ratification and still 1 after a sentinel's direct revocation. An already used signature cannot re-ratify (RatifiedStatusChanged), but a signature for the current nonce that was not yet submitted would, as the report says. Known, not reported as new."
  },
  {
   "priorId": "TRST-R-6",
   "change": "setIsRootRatifiedWithSig no longer requires the caller to hold a vault role. The recovered signer must be an allocator (or a sentinel when unratifying) and the caller must be the signer or authorized by the signer on the adapter's Midnight. The direct setter got the same shape through onBehalf.",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:50-92",
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:54-94"
   ],
   "tested": true,
   "note": "test_06: another allocator, a sentinel and a stranger all get Unauthorized when they submit an allocator's signature; the signer succeeds; a Midnight delegate of an allocator can ratify directly; a sentinel can only unratify. Checked for a new fault: the adapter is itself an allocator of its vault and is self-authorized on Midnight, so onBehalf = adapter would pass the role check, but only the adapter could be the caller and it never calls a ratifier (a stranger gets Unauthorized). A shareholder who authorized the adapter for an exit gains nothing. Only the Price ratifier was run; the Rate ratifier has the same code for these two functions (diff of the two files shows only the type hash and the rate check)."
  },
  {
   "priorId": "3.6.2",
   "change": "The duration id preimage is now abi.encode(\"this/duration\", adapter, duration) in both the NatSpec and onBuy.",
   "status": "fixed",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:64-66",
    "src/adapters/midnight/MidnightAdapter.sol:594"
   ],
   "tested": true,
   "note": "test_08: a buy passes with a cap on keccak256(abi.encode(\"this/duration\", adapter, 7 days)) (absoluteCap 340282366920938463463374607431768211455) and none on the audited \"duration\" preimage (0). I compared the encodings of the four id families of this adapter and found no collision: the first ABI word differs (0x40 for (string,address), 0x60 for (string,address,uint256), 0xa0 for the family id) and the strings differ."
  },
  {
   "priorId": "TRST-R-10",
   "change": "ids() now returns the adapter id, one joint id over (collateralParams, rcfThreshold, liquidatorGate, enterGate) and one id per collateral token. The separate enterGate, liquidatorGate, rcfThreshold and per-collateralParams ids are gone.",
   "status": "partial",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:787-809",
    "src/adapters/midnight/MidnightAdapter.sol:594",
    "src/adapters/midnight/MidnightAdapter.sol:816-834"
   ],
   "tested": true,
   "note": "Ids are still hard-coded and duration caps still adapter-local, so the recommendation is only partly taken. The joint id ignores maturity, loan token and adapter. test_03 shows the consequence in the force path: a market that differs only by maturity passes the vault's ZeroAllocation check although the adapter holds nothing in it; with 0 assets nothing changes and with 1 wei Midnight reverts, so I found no fault."
  },
  {
   "priorId": "3.6.3",
   "change": "Notes 1, 2 and 4 are addressed (stale comment gone, transient variables public, factory immutable assigned). Notes 3, 5, 6, 7 and 8 are as before: no comment at the self-authorization, allocate ignores its selector, createMidnightAdapter does not check that parentVault is a VaultV2, setConsumed forwards the amount as is.",
   "status": "partial",
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:102,114-121,153,158",
    "src/adapters/midnight/MidnightAdapter.sol:342-346",
    "src/adapters/midnight/MidnightAdapter.sol:404-414",
    "src/adapters/midnight/MidnightAdapterFactory.sol:29-41"
   ],
   "tested": true,
   "note": "Only note 7 was run: test_07 deploys an adapter for a contract that only has asset() and the factory reports isCreated = true for it. The others were read. Note 8 in the new code: setConsumed(0, uint128 max) leaves forceDeallocate working (test_05)."
  }
 ],
 "hasCandidates": false,
 "candidates": [],
 "lowInfo": [
  {
   "title": "isRatified approves every offer for every caller while inForceDeallocate is set",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:465-469",
    "src/adapters/midnight/MidnightAdapter.sol:493",
    "src/adapters/midnight/MidnightAdapter.sol:520-526",
    "lib/midnight/src/Midnight.sol:343-344,384-393,437-446",
    "lib/midnight/src/interfaces/IGate.sol:6-7"
   ],
   "detail": "The early return checks neither msg.sender nor the offer. Safety rests on what Midnight.take does between the adapter setting the flag and onBuy clearing it: it calls the ratifier and, for a credit increase, the market's enter gate, whose functions are declared view. Read from the code, not shown by a reentrancy test; test_02 shows the same offer is refused once the flag is off. A cheap hardening is to return early only when msg.sender == midnight and the offer is the adapter's own (maker == address(this), callback == address(0), tick == 0, reduceOnly)."
  },
  {
   "title": "The force path depends on tick 0 having price exactly 0",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:436-452",
    "lib/midnight/src/Midnight.sol:346-361,408",
    "lib/midnight/src/libraries/TickLib.sol:46-53"
   ],
   "detail": "The self-made offer uses group 0 and maxAssets, so Midnight adds sellerAssets to consumed[adapter][0], the counter allocator offers of group 0 also use and that allocators and sentinels can raise with setConsumed. With the pinned Midnight tickToPrice(0) is 0 (printed by test_01), sellerAssets is 0 and the counter never moves: test_04 shows 0 after a 1000 token exit, test_05 shows an exit succeeding after setConsumed(0, uint128 max). With any price above 0 at tick 0, every exit would use up group 0 capacity and that setConsumed call would block all exits for good. Nothing in the adapter states or checks this assumption; a comment and a test would pin it."
  },
  {
   "title": "Factory registers adapters of any parentVault, and the enter gate trusts isCreated",
   "class": "Low",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:29-41",
    "src/adapters/midnight/MidnightAdapter.sol:429-431,457-464",
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:40-48"
   ],
   "detail": "Cantina 3.6.3 note 7 is unchanged (test_07: isCreated is true for an adapter whose vault is a stub). New since the audits, IKRCompatibleEnterGate.admit accepts any adapter created by a registered factory, and the share check in forceDeallocate reads the adapter's own parentVault, which such a deployer controls. UNVERIFIED as exploitable: from reading, admission lasts only during that adapter's own zero-price sale and is cleared in onBuy before any transfer, and such an adapter needs credit in the gated market first, which the gate does not give it. I did not run this path. Belongs to the gates angle."
  },
  {
   "title": "A holder of 1 wei of shares can run the force path with 0 assets on any created market of the loan token",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:427-477",
    "src/VaultV2.sol:567-580"
   ],
   "detail": "test_03: the call succeeds for a sibling-maturity market the adapter never held, costs no penalty, changes no allocation and emits ForceDeallocate plus a Midnight Take event with the adapter as maker. UNVERIFIED part, from reading only: on a held market with a realized loss the same call rewrites the stored net credit from Midnight, the synchronisation that withdrawToVault(0) reserves for allocators and sentinels."
  },
  {
   "title": "Midnight authorization is reused as ratification rights across all vaults",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:20-21,38-44,74-80",
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:42-48,76-82"
   ],
   "detail": "Any address an allocator authorized on Midnight for its own trading can ratify roots for every adapter of every vault where that address is allocator, and relaying a signature requires that same full authorization (test_06: a delegate ratifies on behalf of the allocator). The NatSpec states it. A narrower, per-ratifier delegation would avoid handing a relayer control over the allocator's Midnight positions."
  },
  {
   "title": "A duration cap stops counting a position one second after a buy made at exactly that duration",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:586-603",
    "src/adapters/midnight/MidnightAdapter.sol:816-834"
   ],
   "detail": "test_08: durationAllocations(1)[0] is 100593430826474621736007 right after buying a 7 day market against a 7 day duration and 0 one second later. This matches the NatSpec (a position counts toward every duration <= its remaining time to maturity) and means a duration D never limits markets bought with D - 1 seconds left."
  },
  {
   "title": "No lookup of an adapter by vault and salt any more; a repeated deployment burns the forwarded gas",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:15,35-39"
   ],
   "detail": "The audited mapping midnightAdapter[parentVault][salt] was removed with the salt change, so integrations must compute the CREATE2 address (now also a function of msg.sender, durations and enterGateFactory) or read the event. A second identical call by the same sender fails by CREATE2 collision (test_07, about 1.05e9 gas used in the test run)."
  }
 ],
 "covered": [
  "Clone at bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with submodules; 6476e9d9 confirmed an ancestor; forge 1.9.0 build of src, lib/midnight/src/Midnight.sol and lib/midnight/src/ratifiers succeeded.",
  "Existing test/integration/MidnightAdapterIntegrationTest.sol: 8 passed, 0 failed.",
  "Diff of the audited src/adapters/MidnightAdapter.sol, MidnightAdapterFactory.sol and ratifiers/MidnightAdapterPriceRatifierV1.sol against the pinned files for the deallocate branch, isRatified, constructor, ids, factory and the two root setters.",
  "forceDeallocate branch end to end against the real Midnight and VaultV2: authorization of caller and taker, payment and fee rounding, the self-made offer, the flag and admission lifetime, consumed accounting, zero-asset and unheld-market calls (tests 01 to 05).",
  "isRatified: Midnight binding, the missing chain id binding, the order of the force bypass (tests 02 and 09).",
  "Both adapter ratifiers read; authorization and signature submission run on the Price ratifier (test 06).",
  "Factory salt, duplicate deployment, vault provenance (test 07).",
  "Per-deployment durations, PackedDurationsLib bounds and round trip, duration and family cap id preimages (tests 03 and 08).",
  "All 12 prior ids of this group. Result: no candidate. Two hypotheses about Midnight's consumed counter were tested and refuted."
 ],
 "notCovered": [
  "The full existing test suite was not run, only the integration file and the review test.",
  "The two audit PDFs were not read here; prior findings come from the register (batch known).",
  "The Rate ratifier was read and diffed against the Price ratifier, not run.",
  "No reentrancy test with a hostile enter gate, token or oracle inside the force path; the absence of a window is from reading Midnight.take.",
  "The force path with a registered IKRCompatibleEnterGate (admit and unadmit) was not exercised by the review test; the repository's own testWrapperGateForceDeallocateAfterRevocation passes.",
  "Loss and bad debt in the force path (stored net credit after a slash), continuous fees above 0 and post-maturity exits were reasoned about, not run.",
  "No fuzz or invariant runs.",
  "Everything outside this group: buy and sell accounting, shortfall, caps other than the id preimages, the gates and whitelists themselves."
 ],
 "reviewTest": {
  "path": "test/poc/ForceRatifyReview.t.sol",
  "note": "Not a PoC of a finding. It is the test behind every `tested: true` above; place it at this path in a clone of the pinned commit. It inherits test/integration/MidnightAdapterIntegrationTest.sol (real Midnight and VaultV2). The build step is needed first because setUp deploys by artifact name.",
  "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers && forge test --match-path test/poc/ForceRatifyReview.t.sol --match-test test_0 -vv",
  "output": "No files changed, compilation skipped\n\nRan 9 tests for test/poc/ForceRatifyReview.t.sol:ForceRatifyReviewTest\n[PASS] test_01_ForcePathNumbers() (gas: 1971801)\nLogs:\n  fee setter set / market fee set (1 = yes): 1 1\n  tickToPrice(0): 0\n  settlementFee (WAD): 50000000000000\n  units bought by taker: 1000000000000000000007\n  assets paid by sender: 1000050000000000000008\n  vault idle increase: 1000000000000000000007\n  adapter net credit decrease: 1000000000000000000007\n  penalty shares burnt: 20000000000000000001\n  adapter leftover balance (dust): 0\n  consumed[adapter][0] before: 0\n  consumed[adapter][0] after: 0\n\n[PASS] test_02_SelfOfferNotTakeableOutsideForce() (gas: 1650732)\nLogs:\n  price of the self-made offer per unit (WAD): 0\n  take with empty ratifierData succeeded (0 = reverted): 0\n  take naming attacker as sub-ratifier succeeded (0 = reverted): 0\n  0x30119bd7\n  take naming the real sub-ratifier succeeded (0 = reverted): 0\n  0x30119bd7\n\n[PASS] test_03_ZeroAssetsOnUnheldSiblingMaturity() (gas: 2238158)\nLogs:\n  allocation(adapterId) before: 100593430826474621736007\n  allocation(adapterId) after : 100593430826474621736007\n  marketIdsLength before/after: 1 1\n  1 wei force call on unheld market succeeded (0 = reverted): 0\n\n[PASS] test_04_GroupZeroConsumedUntouched() (gas: 2301672)\nLogs:\n  consumed[adapter][0] after a 1000 token force call: 0\n  allocator's group-0 offer of 1000000000000000000000 units filled in full; consumed now: 1000000000000000000000\n\n[PASS] test_05_SetConsumedMaxDoesNotBlockForce() (gas: 1748965)\nLogs:\n  consumed[adapter][0]: 340282366920938463463374607431768211455\n  units bought by taker after the cancel: 1000000000000000000000\n\n[PASS] test_06_RatifierAuthorizationAndSig() (gas: 924492)\nLogs:\n  rootNonce after signed ratification: 1\n  rootNonce after direct revocation: 1\n\n[PASS] test_07_FactorySaltAndProvenance() (gas: 1045339072)\nLogs:\n  front-runner's adapter: 0x1c8e1561958999eAf5f7D7b88d4F78c56f7AD160\n  victim's adapter      : 0xE5864780419774B5864884aF7F953eEaCEa179Ad\n  adapter of a contract that is no VaultV2, isCreated (1 = yes): 1\n\n[PASS] test_08_DurationsEdges() (gas: 10611372)\nLogs:\n  durations()[7] round trip: 4294967295\n  absoluteCap of this/duration id: 340282366920938463463374607431768211455\n  absoluteCap of the audited duration id: 0\n  durationAllocations(1)[0]: 100593430826474621736007\n  stored net credit        : 100593430826474621736007\n  durationAllocations(1)[0] one second later: 0\n\n[PASS] test_09_IsRatifiedBinding() (gas: 1763101)\nLogs:\n  isRatified for a root-ratified offer of another chain id returns success (1 = yes): 1\n\nSuite result: ok. 9 passed; 0 failed; 0 skipped; finished in 23.31ms (46.10ms CPU time)\n\nRan 1 test suite in 35.98ms (23.31ms CPU time): 9 tests passed, 0 failed, 0 skipped (9 total tests)\n",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {console} from \"../../lib/forge-std/src/console.sol\";\nimport {IRatifier} from \"../../lib/midnight/src/interfaces/IRatifier.sol\";\n\ncontract FakeVault {\n    address public asset;\n\n    constructor(address _asset) {\n        asset = _asset;\n    }\n}\n\n/// @dev Review of the code changed since the 2026-10-12 audits: forceDeallocate, isRatified, ratifier authorization,\n/// factory salt, per-deployment durations, cap id preimages. Run against bbeda7b2.\ncontract ForceRatifyReviewTest is MidnightAdapterIntegrationTest {\n    address internal attacker = makeAddr(\"attacker\");\n\n    function _flag(string memory sig) internal view returns (bool) {\n        (bool ok, bytes memory ret) = address(adapter).staticcall(abi.encodeWithSignature(sig));\n        require(ok, \"flag getter\");\n        return abi.decode(ret, (bool));\n    }\n\n    function _sel(bytes memory ret) internal pure returns (bytes4 s) {\n        if (ret.length >= 4) s = bytes4(ret);\n    }\n\n    function _bal(address who) internal view returns (uint256) {\n        return ERC20Mock(address(underlyingToken)).balanceOf(who);\n    }\n\n    /// @dev Copy of the offer the adapter builds for itself in the forceDeallocate branch.\n    function _selfOffer(Market memory market) internal view returns (Offer memory) {\n        return Offer({\n            market: market,\n            buy: false,\n            maker: address(adapter),\n            start: 0,\n            expiry: type(uint256).max,\n            tick: 0,\n            group: bytes32(0),\n            callback: address(0),\n            callbackData: hex\"\",\n            receiverIfMakerIsSeller: address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: true,\n            maxUnits: 0,\n            maxAssets: type(uint128).max,\n            continuousFeeCap: type(uint256).max\n        });\n    }\n\n    function _makerSellOffer(Market memory market, uint256 units, bytes32 group) internal view returns (Offer memory) {\n        return Offer({\n            market: market,\n            buy: false,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: group,\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    }\n\n    function _ratify(Offer memory offer) internal returns (bytes memory ratifierData) {\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 _setSettlementFee(bytes32 id) internal {\n        vm.prank(owner);\n        (bool ok1,) = address(midnight).call(abi.encodeWithSignature(\"setFeeSetter(address)\", owner));\n        uint256[4] memory fees = [uint256(1e14), 5e13, 1e13, 1e12];\n        bool ok2;\n        for (uint256 i; i < 4 && !ok2; i++) {\n            vm.prank(owner);\n            (ok2,) = address(midnight)\n                .call(abi.encodeWithSignature(\"setMarketSettlementFee(bytes32,uint256,uint256)\", id, 2, fees[i]));\n        }\n        console.log(\"fee setter set / market fee set (1 = yes):\", ok1 ? 1 : 0, ok2 ? 1 : 0);\n    }\n\n    function _prepareForce(address who, uint256 funds) internal {\n        deal(address(underlyingToken), who, funds);\n        vm.startPrank(who);\n        ERC20Mock(address(underlyingToken)).approve(address(adapter), type(uint256).max);\n        midnight.setIsAuthorized(address(adapter), true, who);\n        vm.stopPrank();\n    }\n\n    /* 1. forceDeallocate branch: numbers, flags cleared, dust, consumed */\n\n    function test_01_ForcePathNumbers() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        bytes32 id = IdLib.toId(market);\n        _setSettlementFee(id);\n        uint256 units = 1000 * oneToken + 7;\n        uint256 fee = midnight.settlementFee(id, 7 days);\n        console.log(\"tickToPrice(0):\", TickLib.tickToPrice(0));\n        console.log(\"settlementFee (WAD):\", fee);\n\n        uint256 netCreditBefore = adapter.marketData(id).netCredit;\n        uint256 idleBefore = _bal(address(vault));\n        uint256 sharesBefore = vault.balanceOf(depositor);\n        uint256 consumedBefore = midnight.consumed(address(adapter), bytes32(0));\n        _prepareForce(depositor, 2 * units);\n\n        vm.prank(depositor);\n        vault.forceDeallocate(address(adapter), abi.encode(market, depositor), units, depositor);\n\n        console.log(\"units bought by taker:\", midnight.credit(id, depositor));\n        console.log(\"assets paid by sender:\", 2 * units - _bal(depositor));\n        console.log(\"vault idle increase:\", _bal(address(vault)) - idleBefore);\n        console.log(\"adapter net credit decrease:\", netCreditBefore - adapter.marketData(id).netCredit);\n        console.log(\"penalty shares burnt:\", sharesBefore - vault.balanceOf(depositor));\n        console.log(\"adapter leftover balance (dust):\", _bal(address(adapter)));\n        console.log(\"consumed[adapter][0] before:\", consumedBefore);\n        console.log(\"consumed[adapter][0] after:\", midnight.consumed(address(adapter), bytes32(0)));\n        assertEq(midnight.credit(id, depositor), units, \"taker credit\");\n        assertEq(_bal(address(vault)) - idleBefore, units, \"vault got face value\");\n        assertFalse(_flag(\"inForceDeallocate()\"), \"flag cleared\");\n        assertFalse(_flag(\"admitting()\"), \"admitting cleared\");\n        assertLe(_bal(address(adapter)), 1, \"at most 1 wei dust\");\n    }\n\n    /* 2. the self-made tick-0 offer cannot be taken outside the force path */\n\n    function test_02_SelfOfferNotTakeableOutsideForce() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        bytes32 id = IdLib.toId(market);\n        Offer memory offer = _selfOffer(market);\n        uint256 units = 1000 * oneToken;\n        console.log(\"price of the self-made offer per unit (WAD):\", TickLib.tickToPrice(0));\n        deal(address(underlyingToken), attacker, units);\n        vm.startPrank(attacker);\n        ERC20Mock(address(underlyingToken)).approve(address(midnight), type(uint256).max);\n        (bool ok, bytes memory ret) = address(midnight)\n            .call(abi.encodeCall(IMidnight.take, (offer, hex\"\", units, attacker, address(0), address(0), hex\"\")));\n        console.log(\"take with empty ratifierData succeeded (0 = reverted):\", ok ? 1 : 0);\n        assertFalse(ok);\n        (ok, ret) = address(midnight)\n            .call(\n                abi.encodeCall(\n                    IMidnight.take,\n                    (offer, abi.encode(address(attacker), hex\"\"), units, attacker, address(0), address(0), hex\"\")\n                )\n            );\n        console.log(\"take naming attacker as sub-ratifier succeeded (0 = reverted):\", ok ? 1 : 0);\n        console.logBytes4(_sel(ret));\n        assertFalse(ok);\n        (ok, ret) = address(midnight)\n            .call(\n                abi.encodeCall(\n                    IMidnight.take,\n                    (\n                        offer,\n                        abi.encode(address(priceSubRatifier), abi.encode(bytes32(0), uint256(0), new bytes32[](0), address(0))),\n                        units,\n                        attacker,\n                        address(0),\n                        address(0),\n                        hex\"\"\n                    )\n                )\n            );\n        console.log(\"take naming the real sub-ratifier succeeded (0 = reverted):\", ok ? 1 : 0);\n        console.logBytes4(_sel(ret));\n        assertFalse(ok);\n        vm.stopPrank();\n        assertEq(midnight.credit(id, attacker), 0);\n        assertFalse(_flag(\"inForceDeallocate()\"));\n    }\n\n    /* 3. zero-asset force call on a sibling-maturity market the adapter does not hold */\n\n    function test_03_ZeroAssetsOnUnheldSiblingMaturity() public {\n        testMakerBuy();\n        Market memory held = _market(7 days);\n        Market memory sibling = _market(30 days);\n        bytes32 adapterId = keccak256(abi.encode(\"this\", address(adapter)));\n        vm.prank(depositor);\n        vault.transfer(attacker, 1);\n        _prepareForce(attacker, oneToken);\n        vm.prank(attacker);\n        midnight.touchMarket(sibling);\n        uint256 allocBefore = vault.allocation(adapterId);\n        uint256 lenBefore = adapter.marketIdsLength();\n        uint256 netBefore = adapter.marketData(IdLib.toId(held)).netCredit;\n\n        vm.prank(attacker);\n        vault.forceDeallocate(address(adapter), abi.encode(sibling, attacker), 0, attacker);\n\n        console.log(\"allocation(adapterId) before:\", allocBefore);\n        console.log(\"allocation(adapterId) after :\", vault.allocation(adapterId));\n        console.log(\"marketIdsLength before/after:\", lenBefore, adapter.marketIdsLength());\n        assertEq(vault.allocation(adapterId), allocBefore);\n        assertEq(adapter.marketIdsLength(), lenBefore);\n        assertEq(adapter.marketData(IdLib.toId(held)).netCredit, netBefore);\n        assertFalse(_flag(\"inForceDeallocate()\"));\n\n        vm.prank(attacker);\n        (bool ok, bytes memory ret) = address(vault)\n            .call(abi.encodeCall(IVaultV2.forceDeallocate, (address(adapter), abi.encode(sibling, attacker), 1, attacker)));\n        console.log(\"1 wei force call on unheld market succeeded (0 = reverted):\", ok ? 1 : 0);\n        assertFalse(ok);\n        assertEq(_sel(ret), IMidnight.MakerCreditOrDebtIncreased.selector);\n    }\n\n    /* 4. refuted: the force path does not move Midnight's consumed[adapter][bytes32(0)] (tick 0 has price 0) */\n\n    function test_04_GroupZeroConsumedUntouched() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        uint256 units = 1000 * oneToken;\n        Offer memory offer = _makerSellOffer(market, units, bytes32(0));\n        bytes memory ratifierData = _ratify(offer);\n\n        _prepareForce(depositor, 2 * units);\n        vm.prank(depositor);\n        vault.forceDeallocate(address(adapter), abi.encode(market, depositor), units, depositor);\n        uint256 c = midnight.consumed(address(adapter), bytes32(0));\n        console.log(\"consumed[adapter][0] after a 1000 token force call:\", c);\n        assertEq(c, 0);\n\n        deal(address(underlyingToken), lender, units);\n        vm.startPrank(lender);\n        ERC20Mock(address(underlyingToken)).approve(address(midnight), type(uint256).max);\n        midnight.take(offer, ratifierData, units, lender, address(0), address(0), hex\"\");\n        vm.stopPrank();\n        console.log(\"allocator's group-0 offer of\", units, \"units filled in full; consumed now:\",\n            midnight.consumed(address(adapter), bytes32(0)));\n    }\n\n    /* 5. refuted: cancelling group 0 with setConsumed(max) does not block forceDeallocate */\n\n    function test_05_SetConsumedMaxDoesNotBlockForce() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        bytes32 id = IdLib.toId(market);\n        uint256 units = 1000 * oneToken;\n        _prepareForce(depositor, 2 * units);\n        vm.prank(sentinel);\n        adapter.setConsumed(bytes32(0), type(uint128).max);\n        console.log(\"consumed[adapter][0]:\", midnight.consumed(address(adapter), bytes32(0)));\n        vm.prank(depositor);\n        vault.forceDeallocate(address(adapter), abi.encode(market, depositor), units, depositor);\n        console.log(\"units bought by taker after the cancel:\", midnight.credit(id, depositor));\n        assertEq(midnight.credit(id, depositor), units);\n    }\n\n    /* 6. ratifier authorization and signature submission */\n\n    function _sig(uint256 pk, bytes32 root, bool status, uint128 nonce, uint256 deadline)\n        internal\n        view\n        returns (uint8 v, bytes32 r, bytes32 s)\n    {\n        bytes32 hashStruct = keccak256(\n            abi.encode(HashLib.priceRatifierV1OfferTreeTypeHash(1), address(adapter), root, status, nonce, deadline)\n        );\n        bytes32 digest = keccak256(bytes.concat(\"\\x19\\x01\", priceSubRatifier.DOMAIN_SEPARATOR(), hashStruct));\n        (v, r, s) = vm.sign(pk, digest);\n    }\n\n    function test_06_RatifierAuthorizationAndSig() public {\n        bytes32 root = keccak256(\"root\");\n        address delegate = makeAddr(\"delegate\");\n        bytes4 unauthorized = IMidnightAdapterPriceRatifierV1.Unauthorized.selector;\n\n        vm.prank(attacker);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n\n        // The adapter is itself an allocator of its vault and is self-authorized on Midnight.\n        assertTrue(vault.isAllocator(address(adapter)));\n        assertTrue(midnight.isAuthorized(address(adapter), address(adapter)));\n        vm.prank(attacker);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, address(adapter));\n\n        vm.prank(sentinel);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, sentinel);\n\n        // A shareholder who authorized the adapter for an in-kind exit gains nothing on the ratifier.\n        vm.prank(attacker);\n        midnight.setIsAuthorized(address(adapter), true, attacker);\n        vm.prank(attacker);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, attacker);\n\n        vm.prank(allocator);\n        midnight.setIsAuthorized(delegate, true, allocator);\n        vm.prank(delegate);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        assertTrue(priceSubRatifier.isRootRatified(address(adapter), root));\n        vm.prank(sentinel);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, false, sentinel);\n        assertFalse(priceSubRatifier.isRootRatified(address(adapter), root));\n\n        (address signer, uint256 pk) = makeAddrAndKey(\"signerAllocator\");\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (signer, true)));\n        bytes32 root2 = keccak256(\"root2\");\n        uint256 deadline = block.timestamp + 1 days;\n        (uint8 v, bytes32 r, bytes32 s) = _sig(pk, root2, true, 0, deadline);\n\n        // TRST-R-6: another allocator, a sentinel and a stranger can no longer submit the signature.\n        vm.prank(allocator);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 1, true, 0, deadline, v, r, s);\n        vm.prank(sentinel);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 1, true, 0, deadline, v, r, s);\n        vm.prank(attacker);\n        vm.expectRevert(unauthorized);\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 1, true, 0, deadline, v, r, s);\n        // Another height or maker recovers another signer.\n        vm.prank(signer);\n        vm.expectRevert();\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 2, true, 0, deadline, v, r, s);\n\n        vm.prank(signer);\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 1, true, 0, deadline, v, r, s);\n        assertTrue(priceSubRatifier.isRootRatified(address(adapter), root2));\n        console.log(\"rootNonce after signed ratification:\", priceSubRatifier.rootNonce(address(adapter), root2));\n\n        // Direct revocation leaves the nonce where it was (TRST-R-5, known), but the used signature cannot re-ratify.\n        vm.prank(sentinel);\n        priceSubRatifier.setIsRootRatified(address(adapter), root2, false, sentinel);\n        console.log(\"rootNonce after direct revocation:\", priceSubRatifier.rootNonce(address(adapter), root2));\n        vm.prank(signer);\n        vm.expectRevert(IMidnightAdapterPriceRatifierV1.RatifiedStatusChanged.selector);\n        priceSubRatifier.setIsRootRatifiedWithSig(address(adapter), root2, 1, true, 0, deadline, v, r, s);\n        assertFalse(priceSubRatifier.isRootRatified(address(adapter), root2));\n    }\n\n    /* 7. factory salt and provenance */\n\n    function test_07_FactorySaltAndProvenance() public {\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(adapter.factory());\n        uint256[] memory d = new uint256[](1);\n        d[0] = 7 days;\n        bytes32 preSalt = keccak256(\"victim-salt\");\n        vm.prank(attacker);\n        address a1 = factory.createMidnightAdapter(address(vault), d, address(0), preSalt);\n        vm.prank(curator);\n        address a2 = factory.createMidnightAdapter(address(vault), d, address(0), preSalt);\n        console.log(\"front-runner's adapter:\", a1);\n        console.log(\"victim's adapter      :\", a2);\n        assertTrue(a1 != a2);\n        assertTrue(factory.isCreated(a1) && factory.isCreated(a2));\n        vm.prank(curator);\n        vm.expectRevert();\n        factory.createMidnightAdapter(address(vault), d, address(0), preSalt);\n\n        FakeVault fake = new FakeVault(address(underlyingToken));\n        vm.prank(attacker);\n        address a3 = factory.createMidnightAdapter(address(fake), d, address(0), preSalt);\n        console.log(\"adapter of a contract that is no VaultV2, isCreated (1 = yes):\", factory.isCreated(a3) ? 1 : 0);\n        assertTrue(factory.isCreated(a3));\n    }\n\n    /* 8. per-deployment durations, packing, cap id preimage */\n\n    function test_08_DurationsEdges() public {\n        IMidnightAdapterFactory factory = IMidnightAdapterFactory(adapter.factory());\n        uint256[] memory d8 = new uint256[](8);\n        for (uint256 i; i < 8; i++) {\n            d8[i] = i + 1;\n        }\n        d8[6] = type(uint32).max - 1;\n        d8[7] = type(uint32).max;\n        IMidnightAdapter a = IMidnightAdapter(factory.createMidnightAdapter(address(vault), d8, address(0), \"d8\"));\n        uint256[] memory got = a.durations();\n        assertEq(got.length, 8);\n        for (uint256 i; i < 8; i++) {\n            assertEq(got[i], d8[i]);\n        }\n        console.log(\"durations()[7] round trip:\", got[7]);\n\n        uint256[] memory bad = new uint256[](9);\n        for (uint256 i; i < 9; i++) {\n            bad[i] = i + 1;\n        }\n        vm.expectRevert();\n        factory.createMidnightAdapter(address(vault), bad, address(0), \"d9\");\n        bad = new uint256[](1);\n        vm.expectRevert();\n        factory.createMidnightAdapter(address(vault), bad, address(0), \"zero\");\n        bad[0] = uint256(type(uint32).max) + 1;\n        vm.expectRevert();\n        factory.createMidnightAdapter(address(vault), bad, address(0), \"high\");\n        bad = new uint256[](2);\n        bad[0] = 5;\n        bad[1] = 5;\n        vm.expectRevert();\n        factory.createMidnightAdapter(address(vault), bad, address(0), \"equal\");\n        IMidnightAdapter e =\n            IMidnightAdapter(factory.createMidnightAdapter(address(vault), new uint256[](0), address(0), \"empty\"));\n        assertEq(e.durations().length, 0);\n\n        bytes32 newId = keccak256(abi.encode(\"this/duration\", address(adapter), uint256(7 days)));\n        bytes32 oldId = keccak256(abi.encode(\"duration\", address(adapter), uint256(7 days)));\n        console.log(\"absoluteCap of this/duration id:\", vault.absoluteCap(newId));\n        console.log(\"absoluteCap of the audited duration id:\", vault.absoluteCap(oldId));\n        assertGt(vault.absoluteCap(newId), 0);\n        assertEq(vault.absoluteCap(oldId), 0);\n\n        testMakerBuy();\n        (bool ok, bytes memory ret) =\n            address(adapter).staticcall(abi.encodeWithSignature(\"durationAllocations(uint256)\", uint256(1)));\n        require(ok, \"durationAllocations\");\n        uint256[] memory allocations = abi.decode(ret, (uint256[]));\n        bytes32 id = IdLib.toId(_market(7 days));\n        console.log(\"durationAllocations(1)[0]:\", allocations[0]);\n        console.log(\"stored net credit        :\", adapter.marketData(id).netCredit);\n        assertEq(allocations[0], adapter.marketData(id).netCredit);\n        vm.warp(block.timestamp + 1);\n        (, ret) = address(adapter).staticcall(abi.encodeWithSignature(\"durationAllocations(uint256)\", uint256(1)));\n        console.log(\"durationAllocations(1)[0] one second later:\", abi.decode(ret, (uint256[]))[0]);\n    }\n\n    /* 9. isRatified binds offer.market.midnight, not the chain id */\n\n    function test_09_IsRatifiedBinding() public {\n        testMakerBuy();\n        Market memory market = _market(7 days);\n        Offer memory offer = _makerSellOffer(market, 1000 * oneToken, keccak256(\"g\"));\n        bytes memory ratifierData = _ratify(offer);\n        bytes32 ok = IRatifier(address(adapter)).isRatified(offer, ratifierData, lender);\n        assertEq(ok, keccak256(\"morpho.midnight.callbackSuccess\"));\n\n        offer.market.midnight = address(0xBEEF);\n        ratifierData = _ratify(offer);\n        vm.expectRevert(IMidnightAdapterBase.NotMidnight.selector);\n        IRatifier(address(adapter)).isRatified(offer, ratifierData, lender);\n\n        offer.market.midnight = address(midnight);\n        offer.market.chainId = block.chainid + 1;\n        ratifierData = _ratify(offer);\n        ok = IRatifier(address(adapter)).isRatified(offer, ratifierData, lender);\n        console.log(\"isRatified for a root-ratified offer of another chain id returns success (1 = yes):\",\n            ok == keccak256(\"morpho.midnight.callbackSuccess\") ? 1 : 0);\n        // Midnight itself refuses that market.\n        deal(address(underlyingToken), lender, 1000 * oneToken);\n        vm.startPrank(lender);\n        ERC20Mock(address(underlyingToken)).approve(address(midnight), type(uint256).max);\n        vm.expectRevert();\n        midnight.take(offer, ratifierData, 1000 * oneToken, lender, address(0), address(0), hex\"\");\n        vm.stopPrank();\n    }\n}\n"
 }
}