{
 "lead": "gate configuration and roles in WhitelistEnterSubGate, IKRCompatibleEnterGate and their factories (credit/debt sides and creditSide flag, role setter and whitelister lifecycle, open sides, multicall, setIsWhitelistedWithSig replay across side/account/gate/chain, IKRCompatibleEnterGate.roleSetter and addAdmitterFactory, adapter first entry, non-whitelisted accounts entering gated markets)",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No Medium or higher candidate survives. Every path I tested where an untrusted account tries to get a non-whitelisted account into a gated market outside in-kind redemption (IKR) is blocked. The one confirmed behaviour worth reporting is that an IKR admission is not limited by how many shares the taker holds (Low/Informational, see lowInfo[0]). It is an amplification of the IKR design the README describes, not an exploit, and it costs the attacker money.",
 "lowInfo": [
  {
   "title": "IKR admission is not bounded by the taker's vault position: a holder of 1 wei of shares can take an arbitrarily large credit position in a whitelisted (gated) market",
   "class": "Low",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:427",
    "src/adapters/midnight/MidnightAdapter.sol:430",
    "src/adapters/midnight/MidnightAdapter.sol:462",
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:38",
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:40",
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:55",
    "src/VaultV2.sol:790",
    "src/adapters/midnight/README.md:162"
   ],
   "detail": "deallocate's forceDeallocate branch only checks IVaultV2(parentVault).balanceOf(taker) > 0 (MidnightAdapter.sol:430) before it admits the taker in the market's IKRCompatibleEnterGate (MidnightAdapter.sol:462). It then sells `assets` units of the adapter's credit to the taker. VaultV2.forceDeallocate (VaultV2.sol:790) takes the penalty from `onBehalf`, which can be a different account from the taker. So the taker only needs 1 wei of shares, and the credit it gets is limited only by the adapter's credit in that market. In testDustShareholderEntersGatedMarketWithLargeCredit, a taker that deposited 1 wei (1 share, worth 1 wei) and is not on the credit whitelist (isWhitelisted(true, attacker) == false) cannot buy directly: midnight.take reverts with BuyerGatedFromIncreasingCredit. Through forceDeallocate it ends with 50000000000000000000000 credit (50,000 tokens) in the gated market. A second account it controls paid the 2% penalty (1000000000000000000000 shares). Impact: a credit-side whitelist (for example a KYC list for lenders) does not keep out any account able to get 1 wei of the parent vault's shares, at any size. Limits: the buyer pays face value plus the settlement fee plus the penalty, which is above the amortized value, so this costs the attacker money and does not harm the vault or other depositors. The README documents the admission itself (README.md:162). The undocumented part is that its size is not proportional to the shares. The vault's receive-shares gate, if the curator sets one, closes this. Suggested fix, or a NatSpec/README note: in forceDeallocate, require that the taker's share value covers `assets` (e.g. previewRedeem(balanceOf(taker)) >= assets), or require taker == onBehalf. Alternatively, document that market whitelists offer no protection against vault shareholders of any size."
  },
  {
   "title": "An admit-disabled gate is rejected even when its credit side is open, although IKR could not be blocked there",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:566",
    "src/adapters/midnight/MidnightAdapter.sol:569",
    "src/adapters/midnight/gates/WhitelistEnterSubGate.sol:96"
   ],
   "detail": "onBuy's first-entry check requires admitEnabled() && admitterFactory(factory) for any gate created by enterGateFactory. A gate whose sub-gate has CREDIT_OPEN = true lets anyone receive credit, so IKR can never be blocked there, yet the adapter still rejects it with IncorrectEnterGate (testOpenCreditGateWithoutAdmitIsRejected: depositor canIncreaseCredit = true, buy reverts). This is conservative and documented ('With admitEnabled = false, adapters with enterGateFactory set cannot enter markets that use this gate'). It is only an operational limitation."
  },
  {
   "title": "IKRCompatibleEnterGate.roleSetter() is the sub-gate's credit-side role setter, so the debt-side role setter has no say over admitter factories",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:27",
    "src/adapters/midnight/gates/IKRCompatibleEnterGate.sol:32"
   ],
   "detail": "roleSetter() returns IEnterSubGate(subGate).roleSetter(true). testRoleSetterLifecycleAndSides shows that the debt role setter gets Unauthorized on addAdmitterFactory, that handing over the credit role setter moves gate.roleSetter() with it and locks out the old one, and that setRoleSetter(true, address(0)) freezes factory registration for good. Admission only affects credit, so binding it to the credit side is consistent. The NatSpec says only 'roleSetter', so naming the side explicitly would help integrators. Factories that are already registered cannot be removed; this is documented."
  },
  {
   "title": "setIsWhitelistedWithSig accepts the malleable (high-s) twin of a used signature as an idempotent replay",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/gates/WhitelistEnterSubGate.sol:73",
    "src/adapters/midnight/gates/WhitelistEnterSubGate.sol:74"
   ],
   "detail": "ecrecover accepts s > n/2. After a signature is used (nonce 0 -> 1), its (v^1, r, n-s) twin passes: the stale-nonce branch requires isWhitelisted == newIsWhitelisted, and emits another SetIsWhitelistedWithSig event without changing state. No state impact; the code comment already accepts it ('malleability is ok thanks to the nonce'). Off-chain indexers that count events should deduplicate. A known, already-held issue covers re-admission after direct removal; I did not re-report it."
  }
 ],
 "covered": {
  "pocFile": "test/poc/GatesConfigPoC.t.sol (in a clean clone at the pinned commit; inherits test/integration/MidnightAdapterIntegrationTest.sol with real Midnight and VaultV2)",
  "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol test/poc/GatesConfigPoC.t.sol && forge test --match-path test/poc/GatesConfigPoC.t.sol -vv",
  "pocRun": "17 passed, 0 failed (9 new tests + 8 inherited integration tests)",
  "existingSuitesRun": "forge test --match-path 'test/*{Gate,Whitelist,IKR}*.sol': 145 passed, 0 failed across 9 suites (incl. WhitelistEnterSubGateTest 42, IKRCompatibleEnterGateTest 24, IKRCompatibleEnterGateFactoryTest 4, WhitelistEnterSubGateFactoryTest 6, WhitelistGatesIntegrationTest 2, GateExampleTest 5)",
  "dismissed": [
   "Admission leak / reuse: Midnight.take makes no external call between the gate check and onBuy, onBuy clears the admission before token transfers, and Midnight calls onBuy even on zero-unit takes. After forceDeallocate with 0 assets and with 100 tokens, canIncreaseCredit(attacker) is false later in the same transaction, and a direct take in a second market sharing the gate reverts BuyerGatedFromIncreasingCredit (testAdmissionNotReusableSameTx, attacker m2 credit = 0).",
   "Direct admit: admit from an EOA with the real factory, or with an unregistered fake factory whose isCreated always returns true, reverts Unauthorized. addAdmitterFactory by a non-role-setter reverts. unadmit is permissionless but can only clear state. Admission never grants debt (canIncreaseDebt false).",
   "Rogue adapter from the registered factory: an adapter deployed permissionlessly from the registered factory can only reach admit through deallocate, which requires msg.sender == parentVault (NotAuthorized), and it holds no credit, so a reduceOnly sale of non-zero units is impossible.",
   "Signature replay: cross-side, cross-account, cross-subgate (same whitelister), cross-chain (vm.chainId) and flipped-value replays all revert InvalidSigner. A revoked whitelister's signature reverts. Credit and debt nonces are separate. The typehash constants match the documented type strings.",
   "Side mix-up: the gate routes canIncreaseCredit to creditIncreaseAllowed and canIncreaseDebt to debtIncreaseAllowed. Credit and debt role setters and whitelisters cannot cross sides (NotRoleSetter / NotWhitelister). CREDIT_OPEN does not open debt.",
   "Multicall: it delegatecalls itself and keeps msg.sender, so an outsider batch reverts NotRoleSetter; a role-setter batch works as intended. It is non-payable, so there is no msg.value reuse.",
   "Adapter first entry: an adapter that is not credit-whitelisted cannot buy (BuyerGatedFromIncreasingCredit). A gate from the factory that does not list the adapter's factory, or that has admitEnabled = false, is rejected with IncorrectEnterGate. The adapter never takes debt in forceDeallocate (reduceOnly sale), so canIncreaseDebt is never needed for IKR.",
   "Factories: salts are derived from msg.sender, so there is no front-running or squatting of another deployer's address. Anyone can create a gate around an arbitrary sub-gate and it will be isCreated, but such a gate affects only markets that choose it, and adapters still require admitterFactory(factory) plus an allocator's buy."
  ],
  "priorAuditCheck": "I decoded the text of audits/2026-10-12-midnight-adapter-cantina-draft.pdf and audits/2026-10-12-midnight-adapter-trustsec-draft.pdf and searched it for gate, whitelist, admit, signature and nonce. Neither draft reports the share-size-independent admission. The TrustSec forceDeallocate items concern front-running of exit offers and penalty accounting. Some glyphs in both PDFs did not decode, so a partial overlap cannot be fully excluded."
 },
 "notCovered": [
  "Fuzz/invariant tests for the gates were not written (only targeted unit and integration PoCs).",
  "Sub-gates other than WhitelistEnterSubGate (arbitrary sub-gate contracts) were reasoned about but not tested beyond the factory-created-gate case.",
  "Vault receive-shares/send-shares gates combined with IKR were not tested (they would close lowInfo[0]).",
  "Settlement-fee-bearing IKR (fee > 0) was not re-run in the PoC; the existing integration test testWrapperGateForceDeallocateAfterRevocation covers it and passes.",
  "Parts of both audit PDFs did not fully decode (see priorAuditCheck)."
 ],
 "poc": {
  "path": "test/poc/GatesConfigPoC.t.sol",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {\n    SET_IS_WHITELISTED_TYPEHASH,\n    EIP712_DOMAIN_TYPEHASH\n} from \"../../src/adapters/midnight/gates/interfaces/IWhitelistEnterSubGate.sol\";\nimport {console} from \"../../lib/forge-std/src/Test.sol\";\n\ncontract FakeAdapterFactory {\n    function isCreated(address) external pure returns (bool) {\n        return true;\n    }\n}\n\n/// @dev PoC / dismissal tests for the gate-configuration lead (WhitelistEnterSubGate, IKRCompatibleEnterGate, factories).\ncontract GatesConfigPoC is MidnightAdapterIntegrationTest {\n    IMidnightAdapter internal gAdapter;\n    IMidnightAdapterFactory internal gFactory;\n    IWhitelistEnterSubGate internal sub;\n    IIKRCompatibleEnterGateFactory internal gateFactory;\n    IIKRCompatibleEnterGate internal gate;\n    Market internal gMarket;\n\n    address internal attacker = makeAddr(\"attacker\");\n    address internal attackerPenaltyPayer = makeAddr(\"attackerPenaltyPayer\");\n    address internal creditRoleSetter = makeAddr(\"creditRoleSetter\");\n    address internal debtRoleSetter = makeAddr(\"debtRoleSetter\");\n    uint256 internal wlKey = 0xA11CE;\n    address internal wl;\n\n    function _gatedSetup(bool creditOpen, bool admitEnabled) internal {\n        wl = vm.addr(wlKey);\n        gateFactory = IIKRCompatibleEnterGateFactory(\n            deployCode(\"IKRCompatibleEnterGateFactory.sol:IKRCompatibleEnterGateFactory\")\n        );\n        gFactory = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight)))\n        );\n        uint256[] memory durations = new uint256[](1);\n        durations[0] = 7 days;\n        gAdapter = IMidnightAdapter(\n            gFactory.createMidnightAdapter(address(vault), durations, address(gateFactory), bytes32(0))\n        );\n        IWhitelistEnterSubGateFactory subFactory =\n            IWhitelistEnterSubGateFactory(deployCode(\"WhitelistEnterSubGateFactory.sol:WhitelistEnterSubGateFactory\"));\n        sub = IWhitelistEnterSubGate(\n            subFactory.createWhitelistEnterSubGate(creditRoleSetter, debtRoleSetter, creditOpen, false, bytes32(0))\n        );\n        gMarket = _market(7 days);\n        gate = IIKRCompatibleEnterGate(gateFactory.createIKRCompatibleEnterGate(address(sub), admitEnabled, bytes32(0)));\n        gMarket.enterGate = address(gate);\n\n        vm.startPrank(creditRoleSetter);\n        sub.setIsWhitelister(true, wl, true);\n        gate.addAdmitterFactory(address(gFactory));\n        vm.stopPrank();\n        vm.prank(debtRoleSetter);\n        sub.setIsWhitelister(false, wl, true);\n        vm.startPrank(wl);\n        sub.setIsWhitelisted(true, address(gAdapter), true);\n        sub.setIsWhitelisted(false, borrower, true);\n        vm.stopPrank();\n\n        _submitAndSet(address(gAdapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (90 days)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(gAdapter))));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(gAdapter), true)));\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setForceDeallocatePenalty, (address(gAdapter), 0.02e18)));\n        _increaseCaps(abi.encode(\"this\", address(gAdapter)));\n        _increaseCaps(abi.encode(\"this/duration\", address(gAdapter), 7 days));\n        _increaseCaps(\n            abi.encode(\n                \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n                gMarket.collateralParams,\n                gMarket.rcfThreshold,\n                gMarket.liquidatorGate,\n                gMarket.enterGate\n            )\n        );\n    }\n\n    function _borrowerSellOffer(Market memory market, uint256 units, bytes32 tag)\n        internal\n        returns (Offer memory offer, bytes memory ratifierData)\n    {\n        offer = Offer({\n            market: market,\n            buy: false,\n            maker: borrower,\n            start: block.timestamp,\n            expiry: market.maturity,\n            tick: TICK,\n            group: keccak256(abi.encode(tag, IdLib.toId(market), units)),\n            callback: address(0),\n            callbackData: \"\",\n            receiverIfMakerIsSeller: borrower,\n            ratifier: address(setterRatifier),\n            reduceOnly: false,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n        uint256 collateral = units * 2e18 / oneToken;\n        deal(address(collateralToken), borrower, collateral);\n        bytes32 root = HashLib.hashOffer(offer);\n        ratifierData = abi.encode(root, uint256(0), new bytes32[](0));\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), collateral);\n        midnight.supplyCollateral(market, 0, collateral, borrower);\n        midnight.setIsAuthorized(address(setterRatifier), true, borrower);\n        setterRatifier.setIsRootRatified(borrower, root, true);\n        vm.stopPrank();\n    }\n\n    /// @dev Gated adapter buys `units` credit in gMarket from the whitelisted borrower.\n    function _adapterBuys(uint256 units) internal {\n        (Offer memory offer, bytes memory rd) = _borrowerSellOffer(gMarket, units, \"adapter buy\");\n        vm.prank(allocator);\n        gAdapter.take(offer, rd, units, abi.encode(address(0), \"\"));\n    }\n\n    /// @dev Attacker gets the smallest possible vault position; a second attacker account covers the 2% penalty.\n    function _attackerDustShares(uint256 penaltyBudget) internal {\n        deal(address(underlyingToken), attacker, 1);\n        vm.startPrank(attacker);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), 1);\n        vault.deposit(1, attacker);\n        vm.stopPrank();\n        deal(address(underlyingToken), attackerPenaltyPayer, penaltyBudget);\n        vm.startPrank(attackerPenaltyPayer);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(vault), penaltyBudget);\n        vault.deposit(penaltyBudget, attackerPenaltyPayer);\n        vault.approve(attacker, type(uint256).max);\n        vm.stopPrank();\n    }\n\n    function _forceDeallocate(address taker, uint256 assets, address onBehalf) internal {\n        deal(address(underlyingToken), taker, assets);\n        vm.startPrank(taker);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(gAdapter), assets);\n        midnight.setIsAuthorized(address(gAdapter), true, taker);\n        vault.forceDeallocate(address(gAdapter), abi.encode(gMarket, taker), assets, onBehalf);\n        vm.stopPrank();\n    }\n\n    /* 1. IKR admission size is not tied to the taker's share balance. */\n\n    function testDustShareholderEntersGatedMarketWithLargeCredit() public {\n        _gatedSetup(false, true);\n        uint256 bought = initialAssets * WAD / TickLib.tickToPrice(TICK);\n        _adapterBuys(bought);\n        bytes32 id = IdLib.toId(gMarket);\n\n        uint256 assets = 50_000 * oneToken;\n        _attackerDustShares(assets * 3 / 100);\n\n        // Direct entry is gated.\n        (Offer memory o2, bytes memory rd2) = _borrowerSellOffer(gMarket, 10 * oneToken, \"direct\");\n        deal(address(underlyingToken), attacker, 10 * oneToken);\n        vm.startPrank(attacker);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        vm.expectRevert(IMidnight.BuyerGatedFromIncreasingCredit.selector);\n        midnight.take(o2, rd2, 10 * oneToken, attacker, address(0), address(0), \"\");\n        vm.stopPrank();\n\n        uint256 takerShares = vault.balanceOf(attacker);\n        uint256 takerSharesValue = vault.previewRedeem(takerShares);\n        uint256 payerSharesBefore = vault.balanceOf(attackerPenaltyPayer);\n        _forceDeallocate(attacker, assets, attackerPenaltyPayer);\n\n        console.log(\"attacker isWhitelisted(credit)\", sub.isWhitelisted(true, attacker));\n        console.log(\"attacker vault shares (taker)\", takerShares);\n        console.log(\"value of attacker shares (assets wei)\", takerSharesValue);\n        console.log(\"attacker Midnight credit in gated market\", uint256(midnight.credit(id, attacker)));\n        console.log(\"penalty shares burnt from 2nd account\", payerSharesBefore - vault.balanceOf(attackerPenaltyPayer));\n        console.log(\"credit / share-value ratio\", uint256(midnight.credit(id, attacker)) / (takerSharesValue + 1));\n        assertFalse(sub.isWhitelisted(true, attacker));\n        assertEq(uint256(midnight.credit(id, attacker)), assets);\n        assertLe(takerSharesValue, 1);\n        // Admission does not survive the forceDeallocate, even later in the same transaction.\n        assertFalse(gate.canIncreaseCredit(attacker));\n    }\n\n    /* 2. Admission cannot be reused inside the same transaction, and cannot be obtained without a registered adapter. */\n\n    function testAdmissionNotReusableSameTx() public {\n        _gatedSetup(false, true);\n        _adapterBuys(initialAssets * WAD / TickLib.tickToPrice(TICK));\n        _attackerDustShares(1000 * oneToken);\n        // Second market sharing the same gate.\n        Market memory m2 = gMarket;\n        m2.maturity = gMarket.maturity + 1 days;\n        (Offer memory o2, bytes memory rd2) = _borrowerSellOffer(m2, 100 * oneToken, \"m2\");\n\n        // forceDeallocate of 0 assets still admits then clears in onBuy (Midnight calls onBuy on zero-unit takes).\n        _forceDeallocate(attacker, 0, attackerPenaltyPayer);\n        assertFalse(gate.canIncreaseCredit(attacker), \"zero-asset IKR leaked admission\");\n        _forceDeallocate(attacker, 100 * oneToken, attackerPenaltyPayer);\n        assertFalse(gate.canIncreaseCredit(attacker), \"IKR leaked admission\");\n\n        deal(address(underlyingToken), attacker, 100 * oneToken);\n        vm.startPrank(attacker);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        vm.expectRevert(IMidnight.BuyerGatedFromIncreasingCredit.selector);\n        midnight.take(o2, rd2, 100 * oneToken, attacker, address(0), address(0), \"\");\n        vm.stopPrank();\n        console.log(\"m2 credit of attacker after IKR in m1 (same tx)\", uint256(midnight.credit(IdLib.toId(m2), attacker)));\n\n        // Direct admit attempts.\n        vm.startPrank(attacker);\n        vm.expectRevert(IIKRCompatibleEnterGate.Unauthorized.selector);\n        gate.admit(attacker, address(gFactory));\n        address fake = address(new FakeAdapterFactory());\n        vm.expectRevert(IIKRCompatibleEnterGate.Unauthorized.selector);\n        gate.admit(attacker, fake);\n        vm.expectRevert(IIKRCompatibleEnterGate.Unauthorized.selector);\n        gate.addAdmitterFactory(fake);\n        // Anyone may call unadmit; it only clears.\n        gate.unadmit();\n        vm.stopPrank();\n        // Admission never grants debt.\n        assertFalse(gate.canIncreaseDebt(attacker));\n    }\n\n    /// @dev An attacker-owned adapter from the registered factory (own vault) cannot admit anyone usefully: it has no credit.\n    function testAttackerOwnedRegisteredAdapterCannotAdmitWithCredit() public {\n        _gatedSetup(false, true);\n        uint256[] memory durations = new uint256[](1);\n        durations[0] = 7 days;\n        // The attacker's adapter is isCreated() by the registered factory but points at a vault it controls; here\n        // we reuse `vault` (which never added it) to show that only the parent vault can trigger admit.\n        address rogue = gFactory.createMidnightAdapter(address(vault), durations, address(gateFactory), keccak256(\"x\"));\n        assertTrue(gFactory.isCreated(rogue));\n        vm.prank(attacker);\n        vm.expectRevert(bytes4(keccak256(\"NotAuthorized()\")));\n        IMidnightAdapter(rogue).deallocate(abi.encode(gMarket, attacker), 1, IVaultV2.forceDeallocate.selector, attacker);\n    }\n\n    /* 3. setIsWhitelistedWithSig domain separation: side, account, gate, chain. */\n\n    function _sig(address subGate, bool side, address account, bool v_, uint256 nonce, uint256 deadline)\n        internal\n        view\n        returns (uint8 v, bytes32 r, bytes32 s)\n    {\n        bytes32 h = keccak256(abi.encode(SET_IS_WHITELISTED_TYPEHASH, side, account, v_, nonce, deadline));\n        bytes32 digest =\n            keccak256(bytes.concat(\"\\x19\\x01\", IWhitelistEnterSubGate(subGate).DOMAIN_SEPARATOR(), h));\n        (v, r, s) = vm.sign(wlKey, digest);\n    }\n\n    function testSignatureReplayAcrossSideAccountGateChain() public {\n        _gatedSetup(false, true);\n        assertEq(\n            SET_IS_WHITELISTED_TYPEHASH,\n            keccak256(\"SetIsWhitelisted(bool creditSide,address account,bool newIsWhitelisted,uint256 nonce,uint256 deadline)\")\n        );\n        assertEq(EIP712_DOMAIN_TYPEHASH, keccak256(\"EIP712Domain(uint256 chainId,address verifyingContract)\"));\n        // A second subgate where wl is whitelister on both sides.\n        IWhitelistEnterSubGateFactory f2 =\n            IWhitelistEnterSubGateFactory(deployCode(\"WhitelistEnterSubGateFactory.sol:WhitelistEnterSubGateFactory\"));\n        IWhitelistEnterSubGate sub2 =\n            IWhitelistEnterSubGate(f2.createWhitelistEnterSubGate(creditRoleSetter, debtRoleSetter, false, false, 0));\n        vm.prank(creditRoleSetter);\n        sub2.setIsWhitelister(true, wl, true);\n        vm.prank(debtRoleSetter);\n        sub2.setIsWhitelister(false, wl, true);\n\n        uint256 dl = block.timestamp + 1 days;\n        (uint8 v, bytes32 r, bytes32 s) = _sig(address(sub), true, attacker, true, 0, dl);\n        // Other side.\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub.setIsWhitelistedWithSig(false, attacker, true, 0, dl, v, r, s);\n        // Other account.\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub.setIsWhitelistedWithSig(true, lender, true, 0, dl, v, r, s);\n        // Other subgate with the same whitelister.\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub2.setIsWhitelistedWithSig(true, attacker, true, 0, dl, v, r, s);\n        // Flipped value.\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub.setIsWhitelistedWithSig(true, attacker, false, 0, dl, v, r, s);\n        // Malleable (high-s) twin recovers the same signer: accepted only as an idempotent stale-nonce replay.\n        sub.setIsWhitelistedWithSig(true, attacker, true, 0, dl, v, r, s);\n        bytes32 sHigh = bytes32(uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141) - uint256(s));\n        uint8 vFlip = v == 27 ? 28 : 27;\n        sub.setIsWhitelistedWithSig(true, attacker, true, 0, dl, vFlip, r, sHigh);\n        assertEq(sub.nonces(true, wl, attacker), 1);\n        assertTrue(sub.isWhitelisted(true, attacker));\n        assertFalse(sub.isWhitelisted(false, attacker));\n        assertFalse(sub2.isWhitelisted(true, attacker));\n        // Debt side signature works only on debt side and does not touch credit nonces.\n        (v, r, s) = _sig(address(sub), false, attacker, true, 0, dl);\n        sub.setIsWhitelistedWithSig(false, attacker, true, 0, dl, v, r, s);\n        assertEq(sub.nonces(true, wl, attacker), 1);\n        assertEq(sub.nonces(false, wl, attacker), 1);\n        // Revoked whitelister's signature is dead.\n        (v, r, s) = _sig(address(sub), true, lender, true, 0, dl);\n        vm.prank(creditRoleSetter);\n        sub.setIsWhitelister(true, wl, false);\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub.setIsWhitelistedWithSig(true, lender, true, 0, dl, v, r, s);\n        // Other chain id (last, since vm.chainId is not restored reliably under the optimizer).\n        (v, r, s) = _sig(address(sub), true, depositor, true, 0, dl);\n        vm.chainId(block.chainid + 1);\n        vm.prank(creditRoleSetter);\n        sub.setIsWhitelister(true, wl, true);\n        vm.expectRevert(IWhitelistEnterSubGate.InvalidSigner.selector);\n        sub.setIsWhitelistedWithSig(true, depositor, true, 0, dl, v, r, s);\n        console.log(\"cross side/account/gate/chain/value replays rejected: 6 of 6\");\n    }\n\n    /* 4. Role setter lifecycle, credit/debt separation, multicall, open sides. */\n\n    function testRoleSetterLifecycleAndSides() public {\n        _gatedSetup(false, true);\n        // The gate's roleSetter is the credit-side role setter only.\n        assertEq(gate.roleSetter(), creditRoleSetter);\n        vm.prank(debtRoleSetter);\n        vm.expectRevert(IIKRCompatibleEnterGate.Unauthorized.selector);\n        gate.addAdmitterFactory(address(0xBEEF));\n        // Debt role setter cannot touch credit whitelisters and vice versa.\n        vm.prank(debtRoleSetter);\n        vm.expectRevert(IWhitelistEnterSubGate.NotRoleSetter.selector);\n        sub.setIsWhitelister(true, attacker, true);\n        vm.prank(creditRoleSetter);\n        vm.expectRevert(IWhitelistEnterSubGate.NotRoleSetter.selector);\n        sub.setIsWhitelister(false, attacker, true);\n        // Credit whitelister cannot write the debt list.\n        address cw = makeAddr(\"creditOnlyWl\");\n        vm.prank(creditRoleSetter);\n        sub.setIsWhitelister(true, cw, true);\n        vm.prank(cw);\n        vm.expectRevert(IWhitelistEnterSubGate.NotWhitelister.selector);\n        sub.setIsWhitelisted(false, attacker, true);\n        // Multicall by an outsider cannot escalate (delegatecall keeps msg.sender).\n        bytes[] memory calls = new bytes[](2);\n        calls[0] = abi.encodeCall(IWhitelistEnterSubGate.setIsWhitelister, (true, attacker, true));\n        calls[1] = abi.encodeCall(IWhitelistEnterSubGate.setIsWhitelisted, (true, attacker, true));\n        vm.prank(attacker);\n        vm.expectRevert(IWhitelistEnterSubGate.NotRoleSetter.selector);\n        sub.multicall(calls);\n        // Role setter batches: grant itself whitelister and whitelist in one call.\n        calls[0] = abi.encodeCall(IWhitelistEnterSubGate.setIsWhitelister, (true, creditRoleSetter, true));\n        calls[1] = abi.encodeCall(IWhitelistEnterSubGate.setIsWhitelisted, (true, lender, true));\n        vm.prank(creditRoleSetter);\n        sub.multicall(calls);\n        assertTrue(sub.isWhitelisted(true, lender));\n        // Handing over the credit role setter moves gate.roleSetter() too; old one is locked out.\n        address newRs = makeAddr(\"newRs\");\n        vm.prank(creditRoleSetter);\n        sub.setRoleSetter(true, newRs);\n        assertEq(gate.roleSetter(), newRs);\n        vm.prank(creditRoleSetter);\n        vm.expectRevert(IIKRCompatibleEnterGate.Unauthorized.selector);\n        gate.addAdmitterFactory(address(0xBEEF));\n        // Renouncing (address(0)) freezes the side, whitelisters keep working.\n        vm.prank(newRs);\n        sub.setRoleSetter(true, address(0));\n        vm.prank(cw);\n        sub.setIsWhitelisted(true, attacker, true);\n        assertTrue(gate.canIncreaseCredit(attacker));\n        assertFalse(gate.canIncreaseDebt(attacker));\n    }\n\n    function testCreditOpenSideDoesNotOpenDebt() public {\n        _gatedSetup(true, true);\n        assertTrue(gate.canIncreaseCredit(attacker));\n        assertFalse(gate.canIncreaseDebt(attacker));\n        assertTrue(gate.canIncreaseDebt(borrower));\n    }\n\n    /* 5. Adapter first entry. */\n\n    function testFirstEntryRequiresAdapterWhitelistedOnCredit() public {\n        _gatedSetup(false, true);\n        vm.prank(wl);\n        sub.setIsWhitelisted(true, address(gAdapter), false);\n        (Offer memory offer, bytes memory rd) = _borrowerSellOffer(gMarket, 1000 * oneToken, \"first\");\n        vm.prank(allocator);\n        vm.expectRevert(IMidnight.BuyerGatedFromIncreasingCredit.selector);\n        gAdapter.take(offer, rd, 1000 * oneToken, abi.encode(address(0), \"\"));\n    }\n\n    /// @dev Credit side fully open (anyone can receive credit, so IKR cannot be blocked) but admitEnabled = false:\n    ///      an adapter with enterGateFactory set still refuses the market.\n    function testOpenCreditGateWithoutAdmitIsRejected() public {\n        _gatedSetup(true, false);\n        (Offer memory offer, bytes memory rd) = _borrowerSellOffer(gMarket, 1000 * oneToken, \"open\");\n        assertTrue(gate.canIncreaseCredit(depositor));\n        vm.prank(allocator);\n        vm.expectRevert(IMidnightAdapterBase.IncorrectEnterGate.selector);\n        gAdapter.take(offer, rd, 1000 * oneToken, abi.encode(address(0), \"\"));\n        console.log(\"open-credit gate with admitEnabled=false rejected; depositor canIncreaseCredit\", gate.canIncreaseCredit(depositor));\n    }\n\n    /// @dev A gate whose admitter factory is not the adapter's factory is rejected at first entry.\n    function testUnregisteredFactoryRejectedAtFirstEntry() public {\n        _gatedSetup(false, true);\n        IIKRCompatibleEnterGate g2 =\n            IIKRCompatibleEnterGate(gateFactory.createIKRCompatibleEnterGate(address(sub), true, keccak256(\"g2\")));\n        Market memory m = gMarket;\n        m.enterGate = address(g2);\n        _increaseCaps(\n            abi.encode(\n                \"collateralParams/rcfThreshold/liquidatorGate/enterGate\",\n                m.collateralParams,\n                m.rcfThreshold,\n                m.liquidatorGate,\n                m.enterGate\n            )\n        );\n        (Offer memory offer, bytes memory rd) = _borrowerSellOffer(m, 1000 * oneToken, \"g2\");\n        vm.prank(allocator);\n        vm.expectRevert(IMidnightAdapterBase.IncorrectEnterGate.selector);\n        gAdapter.take(offer, rd, 1000 * oneToken, abi.encode(address(0), \"\"));\n    }\n}\n",
  "command": "forge build src lib/midnight/src/Midnight.sol lib/midnight/src/ratifiers/SetterRatifier.sol test/poc/GatesConfigPoC.t.sol && forge test --match-path test/poc/GatesConfigPoC.t.sol -vv",
  "output": "Ran 17 tests for test/poc/GatesConfigPoC.t.sol:GatesConfigPoC\n[PASS] testAdmissionNotReusableSameTx() (gas: 18425826)\nLogs:\n  m2 credit of attacker after IKR in m1 (same tx) 0\n\n[PASS] testAttackerOwnedRegisteredAdapterCannotAdmitWithCredit() (gas: 18931929)\n[PASS] testCreditOpenSideDoesNotOpenDebt() (gas: 14423191)\n[PASS] testDustShareholderEntersGatedMarketWithLargeCredit() (gas: 17690750)\nLogs:\n  attacker isWhitelisted(credit) false\n  attacker vault shares (taker) 1\n  value of attacker shares (assets wei) 1\n  attacker Midnight credit in gated market 50000000000000000000000\n  penalty shares burnt from 2nd account 1000000000000000000000\n  credit / share-value ratio 25000000000000000000000\n\n[PASS] testFirstEntryRequiresAdapterWhitelistedOnCredit() (gas: 15224196)\n[PASS] testForceDeallocate() (gas: 1751919)\n[PASS] testForceSell() (gas: 1653927)\n[PASS] testMakerBuy() (gas: 1130870)\n[PASS] testMakerSell() (gas: 1922671)\n[PASS] testOpenCreditGateWithoutAdmitIsRejected() (gas: 15396046)\nLogs:\n  open-credit gate with admitEnabled=false rejected; depositor canIncreaseCredit true\n\n[PASS] testRepayWithdrawRedeem() (gas: 1781983)\n[PASS] testRoleSetterLifecycleAndSides() (gas: 14875030)\n[PASS] testSignatureReplayAcrossSideAccountGateChain() (gas: 17096311)\nLogs:\n  cross side/account/gate/chain/value replays rejected: 6 of 6\n\n[PASS] testTakerBuy() (gas: 1167582)\n[PASS] testTakerSell() (gas: 1960240)\n[PASS] testUnregisteredFactoryRejectedAtFirstEntry() (gas: 15992971)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17209800)\nSuite result: ok. 17 passed; 0 failed; 0 skipped; finished in 43.81ms (92.58ms CPU time)\n\nRan 1 test suite in 53.82ms (43.81ms CPU time): 17 tests passed, 0 failed, 0 skipped (17 total tests)"
 }
}