{
 "angle": "Stateless fuzz tests of the Midnight adapter components in isolation: PackedDurationsLib, the onBuy amortization/netRate formula, the onSell shortfall spread, the rate ratifier's price bound, the two signature paths (setIsRootRatifiedWithSig, setIsWhitelistedWithSig), and CREATE2 address derivation in the three factories.",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": true,
 "summary": "All 12 fuzz properties hold at 10,000 runs each. None of them found a counterexample against the code, so there is no High or Medium finding from this angle. Three early failures were bugs in the test harness: an overflow in my input generator, and the documented uint64 rate-cast revert on 'extremely high rates' (MidnightAdapter.sol:509, already covered by TrustSec R-2). I fixed the harness; the contract was not at fault. Manual review of the signature paths gave one candidate, rated Low with a Foundry PoC against real Midnight and a real VaultV2: on the WhitelistEnterSubGate, a direct de-whitelist does not invalidate a whitelister's outstanding signature, so a revoked account can whitelist itself again. This is the enter-gate counterpart of TrustSec R-5, which only covered the ratifiers. A judge may reasonably treat it as Informational, because whitelisters are trusted and the signer can cancel with a counter-signature.",
 "candidates": [
  {
   "id": "FUZZ-1",
   "title": "WhitelistEnterSubGate: a direct setIsWhitelisted revocation does not invalidate outstanding setIsWhitelistedWithSig signatures, and anyone can submit them, so a revoked account can whitelist itself again until the signature's deadline",
   "severity": "Low",
   "impact": "Medium",
   "likelihood": "Low",
   "severityReasoning": "Cantina matrix: Medium impact x Low likelihood = Low. Impact: the gate's core function (keeping a revoked account from increasing credit or debt in gated markets) is defeated for that account. In the PoC, the revoked borrower then borrows 1e18 of vault assets through the adapter's offer. The loan is still collateralized, so no loss of funds is shown. That puts impact at Medium at most, and arguably Low, which would make this Informational. Likelihood: it needs a whitelister to have issued a signature that is still unused and unexpired, then a revocation through the direct setter rather than a counter-signature. Whitelisters are a trusted gate role, and Cantina caps issues that depend on admin actions at Low.",
   "files": [
    {
     "path": "src/adapters/midnight/gates/WhitelistEnterSubGate.sol",
     "lines": "52-56 (setIsWhitelisted writes status without touching nonces), 59-87 (setIsWhitelistedWithSig: permissionless submitter, nonce per (side, whitelister, account), applies when nonce == stored nonce)"
    }
   ],
   "description": "Root cause: setIsWhitelistedWithSig keeps nonces[creditSide][whitelister][account] and applies a signature when nonce == previousNonce (WhitelistEnterSubGate.sol:76-80). The direct setter setIsWhitelisted (lines 52-56) changes isWhitelisted without bumping any nonce. Neither path has a cancel or invalidate-nonce function. The NatSpec at line 58 says signatures are meant to be batched with the take by a third party, so they are handed out and anyone can submit them. Attack steps (reproduced in the PoC): (1) onboarding whitelister W signs SetIsWhitelisted(debt side, account, true, nonce 0, deadline now+30d) and gives it to the account or its bundler. (2) Before it is used, compliance (another whitelister, or W) revokes the account with setIsWhitelisted(false, account, false). The PoC asserts that debtIncreaseAllowed is false, that nonces(false, W, account) is still 0, and that the account's take of the adapter's buy offer reverts. (3) The account submits W's signature itself, and debtIncreaseAllowed(account) becomes true again. (4) The account sells credit to the adapter's buy offer in the IKRCompatibleEnterGate-gated market and borrows 1e18 of vault assets (logged: debt 1e18, vault assets lent 1e18, adapter net credit 1e18). Who loses: the gate operator's access control and, through it, depositors of a vault that relies on the gate (via enterGateFactory) to keep unapproved borrowers or lenders out. A signature that was already used cannot be replayed after a revocation, because a stale nonce with a changed status reverts WhitelistedStatusChanged. The only way to cancel an unused signature is for the signer to sign and submit a counter-signature with the same nonce (testCancellationRequiresCounterSignature), or for the roleSetter to remove W as whitelister, which stops all of W's signatures.",
   "poc": {
    "path": "test/poc/WhitelistSigSurvivesRevocation.t.sol",
    "source": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport \"../MidnightAdapterTest.sol\";\nimport {\n    SET_IS_WHITELISTED_TYPEHASH,\n    EIP712_DOMAIN_TYPEHASH as WL_DOMAIN_TYPEHASH\n} from \"../../src/adapters/midnight/gates/interfaces/IWhitelistEnterSubGate.sol\";\n\n/// @notice A whitelister's outstanding setIsWhitelistedWithSig signature is not invalidated by a direct\n/// setIsWhitelisted(false) revocation. Anyone (here: the revoked borrower) can submit it afterwards and\n/// re-whitelist themselves, then borrow from the vault through the adapter in the gated market.\ncontract WhitelistSigSurvivesRevocationTest is MidnightAdapterTest {\n    function testPoCWhitelistSigSurvivesDirectRevocation() public {\n        (IKRCompatibleEnterGateFactory gateFactory, IWhitelistEnterSubGate gate) = setUpEnterGateRealVault(true);\n        address wrapper = createIKRCompatibleEnterGate(gateFactory, gate);\n\n        // Onboarding whitelister with a key (debt side). roleSetter is address(this).\n        (address wl, uint256 wlKey) = makeAddrAndKey(\"onboardingWhitelister\");\n        gate.setIsWhitelister(false, wl, true);\n\n        // 1. Onboarding whitelister signs a debt-side whitelisting of `taker`, valid 30 days, and hands it out.\n        uint256 deadline = block.timestamp + 30 days;\n        bytes32 structHash = keccak256(abi.encode(SET_IS_WHITELISTED_TYPEHASH, false, taker, true, uint256(0), deadline));\n        bytes32 domain = keccak256(abi.encode(WL_DOMAIN_TYPEHASH, block.chainid, address(gate)));\n        (uint8 v, bytes32 r, bytes32 s) = vm.sign(wlKey, keccak256(bytes.concat(\"\\x19\\x01\", domain, structHash)));\n\n        // 2. Before it is used, compliance (another whitelister, address(this)) revokes `taker` with the direct setter.\n        gate.setIsWhitelisted(false, taker, false);\n        assertFalse(gate.debtIncreaseAllowed(taker), \"revoked\");\n        assertEq(gate.nonces(false, wl, taker), 0, \"direct setter did not touch the signature nonce\");\n\n        // The revoked borrower cannot borrow from the adapter's offer.\n        Offer memory offer = makeEnterGateBuyOffer(wrapper, true);\n        vm.expectRevert();\n        this.takeWithAccrual(offer, \"\", taker, address(0));\n\n        // 3. The borrower submits the still-valid signature themselves (anyone may submit) and is whitelisted again.\n        vm.prank(taker);\n        gate.setIsWhitelistedWithSig(false, taker, true, 0, deadline, v, r, s);\n        assertTrue(gate.debtIncreaseAllowed(taker), \"revocation undone\");\n\n        // 4. The borrower now borrows vault funds through the adapter in the gated market.\n        uint256 vaultIdleBefore = loanToken.balanceOf(address(realVault));\n        take(offer);\n        bytes32 marketId = _marketId(offer.market);\n        uint256 debt = midnight.debt(marketId, taker);\n        uint256 lent = vaultIdleBefore - loanToken.balanceOf(address(realVault));\n        emit log_named_uint(\"revoked borrower debt (units)\", debt);\n        emit log_named_uint(\"vault assets lent to revoked borrower\", lent);\n        emit log_named_uint(\"adapter net credit\", adapter.marketData(marketId).netCredit);\n        assertEq(debt, 1e18);\n        assertEq(lent, 1e18);\n    }\n\n    /// The only cancellation path: the signer burns the nonce by signing and submitting a counter-signature.\n    function testCancellationRequiresCounterSignature() public {\n        (, IWhitelistEnterSubGate gate) = setUpEnterGateRealVault(true);\n        (address wl, uint256 wlKey) = makeAddrAndKey(\"onboardingWhitelister\");\n        gate.setIsWhitelister(false, wl, true);\n        uint256 deadline = block.timestamp + 30 days;\n        bytes32 domain = keccak256(abi.encode(WL_DOMAIN_TYPEHASH, block.chainid, address(gate)));\n        (uint8 v, bytes32 r, bytes32 s) = vm.sign(\n            wlKey,\n            keccak256(\n                bytes.concat(\n                    \"\\x19\\x01\",\n                    domain,\n                    keccak256(abi.encode(SET_IS_WHITELISTED_TYPEHASH, false, taker, true, uint256(0), deadline))\n                )\n            )\n        );\n        (uint8 v2, bytes32 r2, bytes32 s2) = vm.sign(\n            wlKey,\n            keccak256(\n                bytes.concat(\n                    \"\\x19\\x01\",\n                    domain,\n                    keccak256(abi.encode(SET_IS_WHITELISTED_TYPEHASH, false, taker, false, uint256(0), deadline))\n                )\n            )\n        );\n        gate.setIsWhitelistedWithSig(false, taker, false, 0, deadline, v2, r2, s2);\n        vm.expectRevert(IWhitelistEnterSubGate.WhitelistedStatusChanged.selector);\n        gate.setIsWhitelistedWithSig(false, taker, true, 0, deadline, v, r, s);\n        assertFalse(gate.debtIncreaseAllowed(taker));\n    }\n}\n",
    "command": "forge test --match-path test/poc/WhitelistSigSurvivesRevocation.t.sol --match-test \"PoC|Cancellation\" -vv",
    "output": "Compiling 1 files with Solc 0.8.37\nSolc 0.8.37 finished in 63.61s\nCompiler run successful!\n\nRan 2 tests for test/poc/WhitelistSigSurvivesRevocation.t.sol:WhitelistSigSurvivesRevocationTest\n[PASS] testCancellationRequiresCounterSignature() (gas: 26734823)\n[PASS] testPoCWhitelistSigSurvivesDirectRevocation() (gas: 29008084)\nLogs:\n  revoked borrower debt (units): 1000000000000000000\n  vault assets lent to revoked borrower: 1000000000000000000\n  adapter net credit: 1000000000000000000\n\nSuite result: ok. 2 passed; 0 failed; 0 skipped; finished in 38.95ms (21.31ms CPU time)\n\nRan 1 test suite in 50.22ms (38.95ms CPU time): 2 tests passed, 0 failed, 0 skipped (2 total tests)"
   },
   "fix": "Make the direct setter invalidate outstanding signatures, or add explicit cancellation. Options: (a) keep a per-account epoch (e.g. statusVersion[creditSide][account]) that is included in the signed struct and incremented by every setIsWhitelisted / setIsWhitelistedWithSig, so any status change voids older signatures; (b) add invalidateNonce(creditSide, account, newNonce) for whitelisters; (c) document that revoking an account with outstanding signatures needs a counter-signature with the same nonce (or removing the signing whitelister), and recommend short deadlines.",
   "priorAuditCheck": "Not in the Cantina draft (19 issues, none on signatures or nonces). TrustSec R-5 raises the same pattern for MidnightAdapterPriceRatifierV1/RateRatifierV1 setIsRootRatified ('A signature for setIsRootRatifiedWithSig() that was created before a root was unratified with setIsRootRatified() therefore remains valid and can ratify the root again'), but neither report mentions WhitelistEnterSubGate or setIsWhitelistedWithSig. Here the issue is worse than R-5, because submission is permissionless: the revoked account itself can submit. In the ratifiers, the submitter must be the signer or authorized by the signer. A judge could still treat it as a duplicate in spirit of R-5.",
   "outOfScopeCheck": "WhitelistEnterSubGate.sol is in the listed scope. Neither the NatSpec nor the README states this behaviour as an accepted risk: the gate NatSpec only says the chainid change invalidates signatures (line 17). TrustSec CR-1 notes that depositors must trust the gate's controller, which partly overlaps: the issue relies on how trusted whitelisters revoke accounts. It is not malicious behaviour by a trusted role, because the revoking whitelister acts in good faith and is undone by the revoked account."
  }
 ],
 "lowInfo": [
  {
   "title": "setIsRootRatifiedWithSig cannot be cancelled except by a counter-signature, and setIsRootRatified does not bump rootNonce",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:33-48",
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:52-91",
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:37-52"
   ],
   "detail": "Same pattern as FUZZ-1, but the submitter must be the signer or authorized by the signer on Midnight, so only trusted parties can use it. This is already TrustSec R-5 / R-6 and is listed only for completeness. Fuzzing (testFuzzRatifierSigReplayAndWrongSigner, 10,000 runs) confirms that wrong signers, replay of a used signature, use on another maker, a nonce above the current one and an expired deadline all revert or are no-ops."
  },
  {
   "title": "EIP-712 domains omit name and version",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/gates/interfaces/IWhitelistEnterSubGate.sol:10-11",
    "src/adapters/midnight/gates/WhitelistEnterSubGate.sol:92-94",
    "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:94-97"
   ],
   "detail": "The domain is EIP712Domain(uint256 chainId,address verifyingContract). Replay across contracts and chains is still prevented, because verifyingContract and chainId are bound, and struct typehashes differ (fuzzed: a signature for one maker or side is rejected for another). Wallets will show no app name, which makes phishing a whitelister into signing harder to spot. No security impact was found."
  },
  {
   "title": "PackedDurationsLib.pack silently corrupts neighbouring slots for values above 32 bits; get(index >= 8) returns 0",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/libraries/PackedDurationsLib.sol:6-30",
    "src/adapters/midnight/MidnightAdapter.sol:161-169"
   ],
   "detail": "testFuzzPackOverflowCorrupts shows that a value above uint32 bleeds into the next slot. testFuzzGetOutOfRange shows that get returns 0 for any index of 8 or more. Both are documented library assumptions, and the adapter constructor enforces <= 8 strictly increasing, non-zero, <= uint32 durations. testFuzzAdapterConstructorDurations deploys real adapters through MidnightAdapterFactory at 10,000 runs and confirms that invalid arrays revert and valid ones round-trip through durations(). No reachable misuse was found."
  },
  {
   "title": "onBuy netRate rounding accrues interest early; the bound holds",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:22",
    "src/adapters/midnight/MidnightAdapter.sol:544-547"
   ],
   "detail": "Fuzzing a verbatim copy of the formula (testFuzzBuyAmortization, testFuzzBuyRateMonotonicInAssets, 10,000 runs each) shows: amortizedValue <= newNetCredit; the stored value newNetCredit/(1+netRate*ttm) >= amortizedValue (rounds against depositors waiting for interest, i.e. accrues early, as documented); and the excess is <= newNetCredit*ttm/WAD + 1 wei. The rate is non-increasing in paid assets, and book value is non-decreasing in time and equals net credit at maturity (testFuzzValueMonotonicInTime). This is documented and already covered by Cantina 3.2.8 / 3.6.6 and TrustSec R-14. The toUint64 cast reverts on extreme implied rates, which is documented at line 509 and covered by TrustSec R-2."
  },
  {
   "title": "onSell shortfall spread covers the whole shortfall and over-reduces interest only by rounding",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:646-686"
   ],
   "detail": "testFuzzShortfallSpread (10,000 runs, 1-5 markets, including matured ones with ttm = 0) mirrors the loop verbatim. Rates never increase, no market's value exceeds its net credit, the realized reduction is >= the shortfall (the early break is safe), and the over-reduction is <= sum(netCredit_i*ttm_i/WAD + 2), as documented at line 146. One unfuzzed edge: shortfall.mulDivUp(netCredit - amortizedValue, totalInterest) overflows when the product exceeds 2^256 (netCredit on the order of 2^128, about 3.4e20 tokens at 18 decimals). This is unrealistic, and the effect would only be a reverted sale."
  },
  {
   "title": "Rate ratifier price bound is exact at the boundary",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/ratifiers/MidnightAdapterRateRatifierV1.sol:105-108"
   ],
   "detail": "testFuzzRateRatifierBound calls the real MidnightAdapterRateRatifierV1.isRatified with a ratified single-leaf root, over every tick (0..MAX_TICK), rates up to 1000% APR and ttm from 0 to 30 years, including past maturity (ttm floors at 0). Buy offers are accepted iff price*(WAD+rate*ttm) <= WAD^2, and sell offers iff >= WAD^2. The mulDivDown/mulDivUp rounding introduces no off-by-one either way. rate*ttm overflow can only revert (rate comes from the allocator-ratified leaf)."
  },
  {
   "title": "Factory CREATE2 derivation, isCreated and duplicates behave as specified",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapterFactory.sol:28-41",
    "src/adapters/midnight/gates/IKRCompatibleEnterGateFactory.sol:12-21",
    "src/adapters/midnight/gates/WhitelistEnterSubGateFactory.sol:12-28"
   ],
   "detail": "testFuzzFactoryAddresses (10,000 runs) shows that for all three factories the deployed address equals computeCreate2Address(keccak256(abi.encode(preSalt, msg.sender)), keccak256(artifact initcode ++ args), factory), and that isCreated is set. The same sender and preSalt with the same args reverts, while another sender with the same preSalt gets a different address, so front-running cannot block a deployment. One note: the salt does not commit to the constructor args, but the initcode hash does, so the same (preSalt, sender) with different args gives a different address. This is not an issue."
  }
 ],
 "covered": [
  "Built the repo at bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with Foundry 1.8.3 (submodules recursive). Ran the existing suites with FOUNDRY_FUZZ_RUNS=16: MidnightAdapterTest 314/314, MidnightAdapterRatifiersV1Test 36/36 + 38/38 + 1/1, MidnightAdapterIntegrationTest 7/8. The one failure is testWrapperGateForceDeallocateAfterRevocation with 'vm.getCode: multiple matching artifacts found'. The build cache holds three WhitelistEnterSubGate artifacts (default, 466-osaka, 833-osaka), and my scratch fuzz file, which imports WhitelistEnterSubGate together with the 833-osaka adapter factory, probably adds one of them. I did not confirm whether a clean clone without my files passes (UNVERIFIED).",
  "Fuzz suite test/poc/ComponentsFuzz.t.sol (source in fuzzSuite below): 12 properties, 10,000 runs each, all passing (output below). Uses the real Midnight (deployCode artifact), real ratifiers, the real WhitelistEnterSubGate and the three real factories. The parent vault for the ratifier and factory tests is the repo's VaultV2Mock. The buy and sell formulas are verbatim copies in a pure library, because they are internal to onBuy/onSell.",
  "Read both prior audit drafts in full (via a reader sub-agent): Cantina 2026-10-12 draft (19 issues) and TrustSec 2026-10-12 draft (5 Low plus R-1..R-15). Both audited commit 6476e9d9, earlier than the pinned commit.",
  "Manual review of the signature paths: wrong signer, replay, nonce ordering, cross-maker, cross-side and deadline (fuzzed), and cancellation semantics (gave FUZZ-1)."
 ],
 "notCovered": [
  "Stateful or invariant fuzzing across sequences of buys, sells, withdrawals and losses on the real adapter (this angle is stateless only; other items cover it).",
  "Fuzzing onBuy/onSell end to end through Midnight with random ticks, fees and loss factors. The formulas were fuzzed as verbatim mirrors, not through the live contract.",
  "The independent re-run of the PoC from a clean clone (step 4) was not done by me; it belongs to another item.",
  "Price ratifier merkle proof edge cases (multi-level trees, leafIndex range) were not fuzzed beyond single-leaf roots."
 ],
 "fuzzSuite": {
  "path": "test/poc/ComponentsFuzz.t.sol",
  "command": "FOUNDRY_FUZZ_RUNS=10000 forge test --match-path test/poc/ComponentsFuzz.t.sol",
  "output": "Ran 12 tests for test/poc/ComponentsFuzz.t.sol:ComponentsFuzzTest\n[PASS] testFuzzAdapterConstructorDurations(uint256[9],uint8) (runs: 10000, \u03bc: 2743744, ~: 4470764)\n[PASS] testFuzzBuyAmortization(uint256,uint256,uint256,uint64,uint256) (runs: 10000, \u03bc: 7786, ~: 7753)\n[PASS] testFuzzBuyRateMonotonicInAssets(uint256,uint256,uint256,uint256,uint64,uint256) (runs: 10000, \u03bc: 7846, ~: 7863)\n[PASS] testFuzzFactoryAddresses(bytes32,address,address) (runs: 10000, \u03bc: 1072885740, ~: 1072885622)\n[PASS] testFuzzGetOutOfRange(bytes32,uint256) (runs: 10000, \u03bc: 6039, ~: 6018)\n[PASS] testFuzzPackOverflowCorrupts(uint256) (runs: 10000, \u03bc: 12120, ~: 12151)\n[PASS] testFuzzPackRoundTrip(uint32[8],uint8) (runs: 10000, \u03bc: 40701, ~: 40600)\n[PASS] testFuzzRateRatifierBound(uint256,uint256,uint256,bool) (runs: 10000, \u03bc: 1529048, ~: 1530617)\n[PASS] testFuzzRatifierSigReplayAndWrongSigner(bytes32,uint256,bool,bool) (runs: 10000, \u03bc: 1661681, ~: 1605699)\n[PASS] testFuzzShortfallSpread(uint128[5],uint64[5],uint32[5],uint8,uint256) (runs: 10000, \u03bc: 26547, ~: 25722)\n[PASS] testFuzzValueMonotonicInTime(uint128,uint64,uint40,uint40,uint40) (runs: 10000, \u03bc: 1652, ~: 1659)\n[PASS] testFuzzWhitelistSigReplayAndWrongSigner(address,uint256,bool,bool) (runs: 10000, \u03bc: 281483, ~: 272221)\nSuite result: ok. 12 passed; 0 failed; 0 skipped; finished in 8.90s (32.16s CPU time)\n\nRan 1 test suite in 8.90s (8.90s CPU time): 12 tests passed, 0 failed, 0 skipped (12 total tests)\n",
  "source": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport \"../../lib/forge-std/src/Test.sol\";\nimport {PackedDurationsLib} from \"../../src/adapters/midnight/libraries/PackedDurationsLib.sol\";\nimport {MathLib} from \"../../src/libraries/MathLib.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {IMidnight, Offer, Market} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {TickLib, MAX_TICK} from \"../../lib/midnight/src/libraries/TickLib.sol\";\nimport {HashLib} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {\n    IMidnightAdapterPriceRatifierV1,\n    EIP712_DOMAIN_TYPEHASH\n} from \"../../src/adapters/midnight/ratifiers/interfaces/IMidnightAdapterPriceRatifierV1.sol\";\nimport {IMidnightAdapterBase} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {WhitelistEnterSubGate} from \"../../src/adapters/midnight/gates/WhitelistEnterSubGate.sol\";\nimport {WhitelistEnterSubGateFactory} from \"../../src/adapters/midnight/gates/WhitelistEnterSubGateFactory.sol\";\nimport {IKRCompatibleEnterGateFactory} from \"../../src/adapters/midnight/gates/IKRCompatibleEnterGateFactory.sol\";\nimport {SET_IS_WHITELISTED_TYPEHASH} from \"../../src/adapters/midnight/gates/interfaces/IWhitelistEnterSubGate.sol\";\nimport {MidnightAdapterFactory} from \"../../src/adapters/midnight/MidnightAdapterFactory.sol\";\nimport {VaultV2Mock} from \"../mocks/VaultV2Mock.sol\";\nimport {ERC20Mock} from \"../mocks/ERC20Mock.sol\";\n\ncontract PackedHarness {\n    function pack(uint256[] memory d) external pure returns (bytes32) {\n        return PackedDurationsLib.pack(d);\n    }\n\n    function unpack(bytes32 p, uint256 l) external pure returns (uint256[] memory) {\n        return PackedDurationsLib.unpack(p, l);\n    }\n\n    function get(bytes32 p, uint256 i) external pure returns (uint256) {\n        return PackedDurationsLib.get(p, i);\n    }\n}\n\n/// @dev Mirrors of the exact formulas of MidnightAdapter.onBuy / onSell / realAssets (src unmodified, copied verbatim).\nlibrary AdapterMath {\n    using MathLib for uint256;\n\n    function buyRate(uint256 newNetCredit, uint256 boughtNetCredit, uint256 buyerAssets, uint64 oldNetRate, uint256 ttm)\n        internal\n        pure\n        returns (uint256 amortizedValue, uint64 netRate)\n    {\n        amortizedValue = (newNetCredit - boughtNetCredit).mulDivDown(WAD, WAD + oldNetRate * ttm) + buyerAssets;\n        netRate = MathLib.toUint64((newNetCredit - amortizedValue).mulDivDown(WAD, amortizedValue * ttm));\n    }\n\n    /// Same computation without the cast, to filter the documented \"Can revert on extremely high rates\" case.\n    function rawBuyRate(uint256 newNetCredit, uint256 boughtNetCredit, uint256 buyerAssets, uint64 oldNetRate, uint256 ttm)\n        internal\n        pure\n        returns (uint256)\n    {\n        uint256 amortizedValue = (newNetCredit - boughtNetCredit).mulDivDown(WAD, WAD + oldNetRate * ttm) + buyerAssets;\n        return (newNetCredit - amortizedValue).mulDivDown(WAD, amortizedValue * ttm);\n    }\n\n    function value(uint256 netCredit, uint256 netRate, uint256 ttm) internal pure returns (uint256) {\n        return netCredit * WAD / (WAD + netRate * ttm);\n    }\n}\n\ncontract ComponentsFuzzTest is Test {\n    using MathLib for uint256;\n\n    PackedHarness h;\n    IMidnight midnight;\n    VaultV2Mock vault;\n    address allocator;\n    uint256 allocatorKey;\n    address maker;\n\n    function setUp() public {\n        vm.setEvmVersion(\"osaka\");\n        h = new PackedHarness();\n        midnight = IMidnight(deployCode(\"Midnight.sol:Midnight\"));\n        (allocator, allocatorKey) = makeAddrAndKey(\"allocator\");\n        maker = makeAddr(\"adapter\");\n        vault = new VaultV2Mock(address(new ERC20Mock(18)), address(this), address(this), allocator, address(0));\n        vm.mockCall(maker, abi.encodeCall(IMidnightAdapterBase.parentVault, ()), abi.encode(address(vault)));\n        vm.mockCall(maker, abi.encodeCall(IMidnightAdapterBase.midnight, ()), abi.encode(address(midnight)));\n    }\n\n    /* PackedDurationsLib */\n\n    function testFuzzPackRoundTrip(uint32[8] memory raw, uint8 len) public view {\n        uint256 l = bound(len, 0, 8);\n        uint256[] memory d = new uint256[](l);\n        for (uint256 i; i < l; i++) d[i] = raw[i];\n        bytes32 p = h.pack(d);\n        uint256[] memory u = h.unpack(p, l);\n        for (uint256 i; i < l; i++) {\n            assertEq(u[i], d[i]);\n            assertEq(h.get(p, i), d[i]);\n        }\n        // Unused slots are zero, and out-of-range indices read zero (shift >= 256).\n        for (uint256 i = l; i < 8; i++) assertEq(h.get(p, i), 0);\n    }\n\n    function testFuzzGetOutOfRange(bytes32 p, uint256 idx) public view {\n        idx = bound(idx, 8, type(uint256).max / 64);\n        assertEq(h.get(p, idx), 0);\n    }\n\n    /// Out-of-range input (> 32 bits) corrupts higher slots: documented assumption, enforced by the constructor.\n    function testFuzzPackOverflowCorrupts(uint256 big) public view {\n        big = bound(big, uint256(type(uint32).max) + 1, type(uint64).max);\n        uint256[] memory d = new uint256[](2);\n        d[0] = big;\n        d[1] = 0;\n        assertNotEq(h.unpack(h.pack(d), 2)[1], 0);\n    }\n\n    function testFuzzAdapterConstructorDurations(uint256[9] memory raw, uint8 len) public {\n        uint256 l = bound(len, 0, 9);\n        uint256[] memory d = new uint256[](l);\n        bool valid = l <= 8;\n        uint256 prev;\n        for (uint256 i; i < l; i++) {\n            // Mostly valid increasing values, sometimes arbitrary.\n            d[i] = raw[i] % 4 == 0 ? raw[i] % (uint256(type(uint32).max) * 2) : (prev % 2 ** 40) + 1 + (raw[i] % 1e6);\n            if (!(d[i] > prev) || d[i] > type(uint32).max) valid = false;\n            prev = d[i];\n        }\n        MidnightAdapterFactory f = new MidnightAdapterFactory(address(midnight));\n        if (!valid) {\n            vm.expectRevert();\n            f.createMidnightAdapter(address(vault), d, address(0), bytes32(0));\n        } else {\n            address a = f.createMidnightAdapter(address(vault), d, address(0), bytes32(0));\n            uint256[] memory got = IAdapterDurations(a).durations();\n            assertEq(got.length, l);\n            for (uint256 i; i < l; i++) assertEq(got[i], d[i]);\n        }\n    }\n\n    /* onBuy amortization */\n\n    function _buyInputs(uint256 oldNc, uint256 bought, uint256 assets, uint64 oldRate, uint256 ttm)\n        internal\n        pure\n        returns (uint256, uint256, uint256, uint64, uint256)\n    {\n        oldNc = bound(oldNc, 0, 1e30);\n        bought = bound(bought, 1, 1e30);\n        assets = bound(assets, 1, bought); // boughtNetCredit >= buyerAssets enforced by onBuy\n        ttm = bound(ttm, 1, type(uint32).max);\n        // stored rates are those an earlier buy could produce: bound to <= 100%/year-ish * 1000\n        oldRate = uint64(bound(oldRate, 0, 1e18 / uint256(365 days) * 1000));\n        return (oldNc, bought, assets, oldRate, ttm);\n    }\n\n    /// After a buy, the stored value never exceeds net credit, is at least the pre-buy value + paid assets\n    /// (rate rounded down => interest accrued early, documented), and the early accrual is bounded.\n    function testFuzzBuyAmortization(uint256 oldNc, uint256 bought, uint256 assets, uint64 oldRate, uint256 ttm)\n        public\n        view\n    {\n        (oldNc, bought, assets, oldRate, ttm) = _buyInputs(oldNc, bought, assets, oldRate, ttm);\n        uint256 newNc = oldNc + bought;\n        vm.assume(AdapterMath.rawBuyRate(newNc, bought, assets, oldRate, ttm) <= type(uint64).max);\n        (uint256 av, uint64 r) = AdapterMath.buyRate(newNc, bought, assets, oldRate, ttm);\n        uint256 v = AdapterMath.value(newNc, r, ttm);\n        assertLe(av, newNc, \"AV > net credit\");\n        assertLe(v, newNc, \"value > net credit\");\n        assertGe(v, av, \"value < amortized target\");\n        // Rate rounding error <1 wei/s => value excess <= newNc * ttm / WAD + 1 (documented early accrual).\n        assertLe(v - av, newNc * ttm / WAD + 1, \"early accrual above bound\");\n    }\n\n    /// Paying more for the same credit can only lower the stored rate.\n    function testFuzzBuyRateMonotonicInAssets(\n        uint256 oldNc,\n        uint256 bought,\n        uint256 a1,\n        uint256 a2,\n        uint64 oldRate,\n        uint256 ttm\n    ) public pure {\n        (oldNc, bought, a1, oldRate, ttm) = _buyInputs(oldNc, bought, a1, oldRate, ttm);\n        a2 = bound(a2, a1, bought);\n        vm.assume(AdapterMath.rawBuyRate(oldNc + bought, bought, a1, oldRate, ttm) <= type(uint64).max);\n        (, uint64 r1) = AdapterMath.buyRate(oldNc + bought, bought, a1, oldRate, ttm);\n        (, uint64 r2) = AdapterMath.buyRate(oldNc + bought, bought, a2, oldRate, ttm);\n        assertGe(r1, r2);\n    }\n\n    /// Book value of a stored position is non-decreasing in time and reaches net credit at maturity.\n    function testFuzzValueMonotonicInTime(uint128 nc, uint64 rate, uint40 maturity, uint40 t1, uint40 t2) public pure {\n        t1 = uint40(bound(t1, 0, type(uint40).max - 1));\n        t2 = uint40(bound(t2, t1, type(uint40).max));\n        uint256 v1 = AdapterMath.value(nc, rate, MathLib.zeroFloorSub(maturity, t1));\n        uint256 v2 = AdapterMath.value(nc, rate, MathLib.zeroFloorSub(maturity, t2));\n        assertLe(v1, v2);\n        assertEq(AdapterMath.value(nc, rate, MathLib.zeroFloorSub(maturity, maturity)), nc);\n    }\n\n    /* onSell shortfall spread (verbatim mirror of the loop) */\n\n    function _spread(uint256[] memory nc, uint64[] memory rate, uint256[] memory ttm, uint256 shortfall)\n        internal\n        pure\n        returns (uint256 totalInterest, uint256 realized, uint256 sumIncrease, uint64[] memory newRates)\n    {\n        uint256 n = nc.length;\n        uint256[] memory av = new uint256[](n);\n        newRates = new uint64[](n);\n        for (uint256 i; i < n; i++) {\n            av[i] = nc[i].mulDivDown(WAD, WAD + rate[i] * ttm[i]);\n            totalInterest += nc[i] - av[i];\n            newRates[i] = rate[i];\n        }\n        if (shortfall > totalInterest) return (totalInterest, 0, 0, newRates);\n        for (uint256 i; i < n; i++) {\n            if (nc[i] == av[i]) continue;\n            uint256 target = av[i] + shortfall.mulDivUp(nc[i] - av[i], totalInterest);\n            uint64 r = MathLib.toUint64((nc[i] - target).mulDivDown(WAD, target * ttm[i]));\n            newRates[i] = r;\n            realized += nc[i].mulDivDown(WAD, WAD + r * ttm[i]) - av[i];\n            if (realized >= shortfall) break;\n        }\n        for (uint256 i; i < n; i++) {\n            sumIncrease += nc[i].mulDivDown(WAD, WAD + newRates[i] * ttm[i]) - av[i];\n        }\n    }\n\n    function testFuzzShortfallSpread(\n        uint128[5] memory ncRaw,\n        uint64[5] memory rateRaw,\n        uint32[5] memory ttmRaw,\n        uint8 len,\n        uint256 shortfall\n    ) public pure {\n        uint256 n = bound(len, 1, 5);\n        uint256[] memory nc = new uint256[](n);\n        uint64[] memory rate = new uint64[](n);\n        uint256[] memory ttm = new uint256[](n);\n        for (uint256 i; i < n; i++) {\n            nc[i] = bound(ncRaw[i], 1, 1e30);\n            rate[i] = uint64(bound(rateRaw[i], 0, 1e18 / uint256(365 days) * 10));\n            ttm[i] = ttmRaw[i]; // 0 = matured\n        }\n        uint256 total;\n        for (uint256 i; i < n; i++) total += nc[i] - nc[i].mulDivDown(WAD, WAD + rate[i] * ttm[i]);\n        vm.assume(total > 0);\n        shortfall = bound(shortfall, 1, total);\n        (, uint256 realized, uint256 sumIncrease, uint64[] memory newRates) = _spread(nc, rate, ttm, shortfall);\n        // Whole shortfall is covered, rates only decrease, no value ever exceeds face value.\n        assertGe(realized, shortfall, \"realized < shortfall\");\n        assertEq(sumIncrease, realized, \"sum mismatch\");\n        uint256 extraBound;\n        for (uint256 i; i < n; i++) {\n            assertLe(newRates[i], rate[i], \"rate increased\");\n            assertLe(nc[i].mulDivDown(WAD, WAD + newRates[i] * ttm[i]), nc[i]);\n            extraBound += nc[i] * ttm[i] / WAD + 2;\n        }\n        // Over-reduction of interest is limited to rounding (documented at MidnightAdapter.sol:146 / :684).\n        assertLe(realized - shortfall, extraBound, \"over-realization beyond rounding\");\n    }\n\n    /* Rate ratifier boundary */\n\n    function testFuzzRateRatifierBound(uint256 tick, uint256 rate, uint256 ttm, bool buy) public {\n        tick = bound(tick, 0, MAX_TICK);\n        rate = bound(rate, 0, 1e18 / uint256(365 days) * 1000);\n        ttm = bound(ttm, 0, 30 * 365 days);\n        IMidnightAdapterPriceRatifierV1 rr = IMidnightAdapterPriceRatifierV1(deployCode(\"MidnightAdapterRateRatifierV1.sol:MidnightAdapterRateRatifierV1\"));\n        Offer memory offer;\n        offer.maker = maker;\n        offer.buy = buy;\n        offer.tick = tick;\n        offer.market.chainId = block.chainid;\n        offer.market.maturity = block.timestamp + ttm;\n        bytes32 root = HashLib.hashRateRatifierV1Offer(offer, rate, address(0));\n        vm.prank(allocator);\n        rr.setIsRootRatified(maker, root, true, allocator);\n        uint256 price = TickLib.tickToPrice(tick);\n        uint256 d = WAD + rate * ttm;\n        // Exact rational bound: buy accepted iff price*(1+r t) <= 1 ; sell iff price*(1+r t) >= 1.\n        bool expected = buy ? price * d <= WAD * WAD : price * d >= WAD * WAD;\n        bytes memory data = abi.encode(root, uint256(0), new bytes32[](0), rate, address(0));\n        try rr.isRatified(offer, data, address(this)) returns (bytes32) {\n            assertTrue(expected, \"accepted out of bound\");\n        } catch {\n            assertFalse(expected, \"rejected in bound\");\n        }\n    }\n\n    /* Ratifier signature path */\n\n    function _ratSig(address ratifier, address _maker, bytes32 root, bool status, uint128 nonce, uint256 deadline, uint256 key, bool rate)\n        internal\n        view\n        returns (uint8 v, bytes32 r, bytes32 s)\n    {\n        bytes32 th = rate ? HashLib.rateRatifierV1OfferTreeTypeHash(0) : HashLib.priceRatifierV1OfferTreeTypeHash(0);\n        bytes32 sh = keccak256(abi.encode(th, _maker, root, status, nonce, deadline));\n        bytes32 dom = keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, block.chainid, ratifier));\n        (v, r, s) = vm.sign(key, keccak256(bytes.concat(\"\\x19\\x01\", dom, sh)));\n    }\n\n    function testFuzzRatifierSigReplayAndWrongSigner(bytes32 root, uint256 otherKey, bool rateKind, bool status)\n        public\n    {\n        otherKey = bound(otherKey, 1, 115792089237316195423570985008687907852837564279074904382605163141518161494336);\n        vm.assume(otherKey != allocatorKey);\n        IMidnightAdapterPriceRatifierV1 rat = rateKind\n            ? IMidnightAdapterPriceRatifierV1(deployCode(\"MidnightAdapterRateRatifierV1.sol:MidnightAdapterRateRatifierV1\"))\n            : IMidnightAdapterPriceRatifierV1(deployCode(\"MidnightAdapterPriceRatifierV1.sol:MidnightAdapterPriceRatifierV1\"));\n        uint256 dl = block.timestamp + 1;\n        // Wrong signer (not an allocator) is rejected even when the caller is the allocator.\n        (uint8 v, bytes32 r, bytes32 s) = _ratSig(address(rat), maker, root, status, 0, dl, otherKey, rateKind);\n        vm.prank(allocator);\n        vm.expectRevert();\n        rat.setIsRootRatifiedWithSig(maker, root, 0, status, 0, dl, v, r, s);\n        // Valid signature applies once; replay is a no-op, nonce > current reverts.\n        (v, r, s) = _ratSig(address(rat), maker, root, status, 0, dl, allocatorKey, rateKind);\n        vm.prank(allocator);\n        rat.setIsRootRatifiedWithSig(maker, root, 0, status, 0, dl, v, r, s);\n        assertEq(rat.isRootRatified(maker, root), status);\n        assertEq(rat.rootNonce(maker, root), 1);\n        vm.prank(allocator);\n        rat.setIsRootRatifiedWithSig(maker, root, 0, status, 0, dl, v, r, s);\n        assertEq(rat.rootNonce(maker, root), 1);\n        // Same signature used for another maker / another ratifier recovers another signer => rejected.\n        address maker2 = makeAddr(\"adapter2\");\n        vm.mockCall(maker2, abi.encodeCall(IMidnightAdapterBase.parentVault, ()), abi.encode(address(vault)));\n        vm.mockCall(maker2, abi.encodeCall(IMidnightAdapterBase.midnight, ()), abi.encode(address(midnight)));\n        vm.prank(allocator);\n        vm.expectRevert();\n        rat.setIsRootRatifiedWithSig(maker2, root, 0, status, 0, dl, v, r, s);\n        // Expired deadline rejected.\n        vm.warp(dl + 1);\n        vm.prank(allocator);\n        vm.expectRevert();\n        rat.setIsRootRatifiedWithSig(maker, root, 0, status, 1, dl, v, r, s);\n    }\n\n    /* Whitelist signature path */\n\n    function _wlSig(address gate, bool side, address account, bool st, uint256 nonce, uint256 dl, uint256 key)\n        internal\n        view\n        returns (uint8 v, bytes32 r, bytes32 s)\n    {\n        bytes32 sh = keccak256(abi.encode(SET_IS_WHITELISTED_TYPEHASH, side, account, st, nonce, dl));\n        bytes32 dom = keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, block.chainid, gate));\n        (v, r, s) = vm.sign(key, keccak256(bytes.concat(\"\\x19\\x01\", dom, sh)));\n    }\n\n    function testFuzzWhitelistSigReplayAndWrongSigner(address account, uint256 otherKey, bool side, bool st) public {\n        otherKey = bound(otherKey, 1, 115792089237316195423570985008687907852837564279074904382605163141518161494336);\n        (address wl, uint256 wlKey) = makeAddrAndKey(\"whitelister\");\n        vm.assume(otherKey != wlKey);\n        WhitelistEnterSubGate g = new WhitelistEnterSubGate(address(this), address(this), false, false);\n        g.setIsWhitelister(side, wl, true);\n        uint256 dl = block.timestamp + 1;\n        (uint8 v, bytes32 r, bytes32 s) = _wlSig(address(g), side, account, st, 0, dl, otherKey);\n        vm.expectRevert();\n        g.setIsWhitelistedWithSig(side, account, st, 0, dl, v, r, s);\n        (v, r, s) = _wlSig(address(g), side, account, st, 0, dl, wlKey);\n        // Wrong side: signature does not verify for the other side.\n        vm.expectRevert();\n        g.setIsWhitelistedWithSig(!side, account, st, 0, dl, v, r, s);\n        g.setIsWhitelistedWithSig(side, account, st, 0, dl, v, r, s);\n        assertEq(g.isWhitelisted(side, account), st);\n        assertEq(g.nonces(side, wl, account), 1);\n        g.setIsWhitelistedWithSig(side, account, st, 0, dl, v, r, s); // replay is a no-op\n        assertEq(g.nonces(side, wl, account), 1);\n        (v, r, s) = _wlSig(address(g), side, account, st, 5, dl, wlKey);\n        vm.expectRevert();\n        g.setIsWhitelistedWithSig(side, account, st, 5, dl, v, r, s);\n    }\n\n    /* Factories */\n\n    function testFuzzFactoryAddresses(bytes32 preSalt, address sender, address sender2) public {\n        vm.assume(sender != sender2 && sender != address(0) && sender2 != address(0));\n        bytes32 salt = keccak256(abi.encode(preSalt, sender));\n\n        WhitelistEnterSubGateFactory wf = new WhitelistEnterSubGateFactory();\n        vm.prank(sender);\n        address sg = wf.createWhitelistEnterSubGate(address(1), address(2), true, false, preSalt);\n        bytes memory init = abi.encodePacked(\n            vm.getCode(\"WhitelistEnterSubGate.sol:WhitelistEnterSubGate\"), abi.encode(address(1), address(2), true, false)\n        );\n        assertEq(sg, vm.computeCreate2Address(salt, keccak256(init), address(wf)));\n        assertTrue(wf.isCreated(sg));\n        vm.prank(sender);\n        vm.expectRevert();\n        wf.createWhitelistEnterSubGate(address(1), address(2), true, false, preSalt);\n        vm.prank(sender2);\n        address sg2 = wf.createWhitelistEnterSubGate(address(1), address(2), true, false, preSalt);\n        assertNotEq(sg, sg2);\n\n        IKRCompatibleEnterGateFactory gf = new IKRCompatibleEnterGateFactory();\n        vm.prank(sender);\n        address gate = gf.createIKRCompatibleEnterGate(sg, true, preSalt);\n        init = abi.encodePacked(vm.getCode(\"IKRCompatibleEnterGate.sol:IKRCompatibleEnterGate\"), abi.encode(sg, true));\n        assertEq(gate, vm.computeCreate2Address(salt, keccak256(init), address(gf)));\n        assertTrue(gf.isCreated(gate));\n        assertFalse(gf.isCreated(sg));\n\n        MidnightAdapterFactory mf = new MidnightAdapterFactory(address(midnight));\n        uint256[] memory d = new uint256[](1);\n        d[0] = 1 days;\n        vm.prank(sender);\n        address ad = mf.createMidnightAdapter(address(vault), d, address(gf), preSalt);\n        init = abi.encodePacked(\n            vm.getCode(\"MidnightAdapter.sol:MidnightAdapter\"),\n            abi.encode(address(vault), address(midnight), d, address(gf))\n        );\n        assertEq(ad, vm.computeCreate2Address(salt, keccak256(init), address(mf)));\n        assertTrue(mf.isCreated(ad));\n        vm.prank(sender);\n        vm.expectRevert();\n        mf.createMidnightAdapter(address(vault), d, address(gf), preSalt);\n    }\n}\n\ninterface IAdapterDurations {\n    function durations() external view returns (uint256[] memory);\n}\n"
 }
}