# Audit report

> RE-CHECK the wave-1 fixes in src/Parameters.sol, src/ParametersBase.sol, src/ParametersRules.sol, src/GovernedByKind.sol, src/managers/RateManager.sol, script/deploy/, and REVIEW THE DESIGN of the beta as run: README trust model, script/DeployConfig.sol BetaConfig, src/Parameters*.sol, at the pinned commit, for a capped mainnet beta.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum. Positions are NFT ids; borrowers set their own rate and redemptions take from the lowest rates first; liquidation is mark then bite, with a standing bid from Backstop sleeves; the peg pool is a Uniswap v4 pool with our own hook; prices come from Chainlink and swarm-attested feeds. README.md gives scope, invariants, trust model and known issues: read it first. This repository's first commit (2875ffb) was audited in wave 1; the second commit is the whole delta since (README 'What changed').
>
> BUILD AND TEST (required; Foundry, solc 0.8.26 via_ir per foundry.toml). Never build or test the whole project with solc: it needs about 49 GB. Run only this panel's tests: `forge test --match-path 'test/unit/{AuditW1{BatchItems,OtherImdLines,PostLowerDepth,RateStep,ResumeTypes},Core,PanelParams,CapAndSlots}.t.sol'` (measured: about 3.7 GB peak, 5 minutes). With Foundry 1.9+, `forge test --use solar --no-match-path 'test/fork/*'` builds everything and runs all 1,267 tests in seconds under 1 GB (confirm a proof with solc). Write each proof as test/unit/Proof<Name>.t.sol, add it to the glob, run it, paste it with its output, then delete it: leave the tree unchanged.
>
> Wave 1's findings and proofs are public: GET https://api.imd.fun/jobs/<id>/submissions for jobs 59d97f98 (ledger, liquidation), 584aadc2 (treasury, backstop), bd0ce553 (oracles, depth), cd9184ac (governance), 561e7d5b (peg), 3d73817d (seats), 17e4edf1 (deploy), 4384ebcc (full system). For questions 1-2, re-run each original proof for these files against this commit and say whether it still fails, and why.
>
> Questions 3-5: For each: rank the options given (and any better one you find), try to refute ours with numbers or a test, and say what you would build, with its cost. Constraints: beta on 2026-12-07, code freeze about 2026-11-20 (only small contract changes before it); the Treasury holds almost no USDC; a swarm-attested answer costs 0.5 IMD and the IMD price leg may be at most 1 hour old. Report concrete defects as findings in the usual form.
>
> Answer each numbered question:
> 1. Governance: a malformed BATCH item is refused at propose; lowerOtherImdLines is refused while the depth line binds; postLowerDepth never raises from 0 without ImdDepth; RateManager keeps its step reference after a target of 0; SET_KEEPER, SET_BRIDGE and adding to a full sleeve are refused at propose. What still passes propose and fails at apply?
> 2. M6: a resumed deploy stage compares every kept piece (types, feeds, risk, backstop pieces) with the config. Can a resume still adopt something it should not?
> 3. OPERATIONS. Every action the protocol needs someone to take (depth samples and the daily poke, relaying attestations, ticks, marks and liquidations, seat pokes and auctions, starting collateral auctions, buffer and LP rules, Backstop conversions): what missing it costs after 1 hour, 1 day, 1 week; lazily inside user transactions, an on-chain tip, or a chore; who pays for oracle answers (whoever needs the update, or an on-chain asker).
> 4. ROOM TO GROW. Size margins (ParametersRules 82 bytes left, Allocator about 2.6 KB, Ledger about 2.2 KB), one pending proposal per kind, adding types, chains and modules without a redeploy. Where does v2 run out first, and what should change before mainnet?
> 5. GOVERNANCE AS THE LAST KEY. A 2-of-3 Safe holds every raise, the freezer and the only mint path for a bridge. The worst a compromised or absent Safe does within the timelocks, and the cheapest hardening.
>
> Not findings: README.md 'Known issues and accepted risks' (say so if you find one worse than written); src/bridge, src/dex, src/earn/LoopVault.sol, src/stocks (after the beta) unless a question names them; test/ and mocks; gas only.
>
> For every finding: severity by impact; file, line and the lines copied; the call sequence; a concrete failing state with expected against actual; whether it is reachable with script/DeployConfig.sol BetaConfig; the smallest fix; and a Foundry test that fails on this commit, RUN as BUILD says and pasted in full with its output (the judge reruns it). Answer every numbered question, including those where nothing is wrong.

| | |
|---|---|
| Repository | https://github.com/fa11up/imdusd-v2-audit.git |
| Commit | `5de80a6d895e020e1a4e790fd00b7248b34733da` |
| Job | `62b92eb1-7472-440c-ad76-2e55e66a1f65` |
| Judged | 2026-11-13 03:43 UTC |
| Findings | 3 low · 3 info |

Four agents audited the code as it is at `5de80a6`, each in one area (math, permissions, economics, control flow),
and a judge reproduced, merged and ranked what they found, then read the code once more itself. Nothing in the repository was changed or deployed.

## Findings

### 1. Low: Q1: ADD_DEPTH_SAMPLER (listed sampler, listed pool, 7th), SET_DEPTH_LEG (codeless leg/price) and self-conflicting BATCH items still pass propose and always fail at apply, holding the kind's slot and l

`src/ParametersRules.sol:75`

```
        } else if (kind == ADD_DEPTH_SAMPLER) {
            (, address sampler) = abi.decode(payload, (uint8, address));
            if (address(imdDepth) == address(0) || sampler.code.length == 0) revert OutOfBounds();
        } else if (kind == SET_DEPTH_LEG) {
            (, address leg, address price) = abi.decode(payload, (uint8, address, address));
            if (address(imdDepth) == address(0) || (leg == address(0)) != (price == address(0))) revert OutOfBounds();
```

Wave 1's rule for Parameters is 'refuse at propose what the apply would fail on'. The wave-1 fixes listed in question 1 hold (re-run: a malformed BATCH item, SET_KEEPER/SET_BRIDGE when already set, and a full sleeve are refused at propose; lowerOtherImdLines is refused while depth binds; postLowerDepth cannot raise from 0 without ImdDepth; RateManager keeps its step reference after target 0; the AuditW1* suites pass). Three classes remain. (1) ADD_DEPTH_SAMPLER: _validate (line 75-77) checks only that ImdDepth exists and the sampler has code. ImdDepth.addSampler (src/feeds/ImdDepth.sol:82-88) also refuses a sampler already listed, a second sampler on an already listed (manager, poolId) and a 7th sampler (MAX_SAMPLERS = 6). (2) SET_DEPTH_LEG: _validate (line 78-80) checks only the both-or-neither-zero pairing; ImdDepth.setLeg (ImdDepth.sol:103-104) also requires code on both addresses. (3) BATCH: each item is validated against the state BEFORE the batch (line 132-135), while _apply re-validates item i after items 0..i-1 applied, so items that conflict with each other pass propose: two ADD_ILK of the same new type (IlkExists at apply), two SET_BRIDGE or two SET_KEEPER (ImdUSD AlreadySet), two ADD_SLEEVE_ILK each adding a new token into a sleeve holding 5 (SLEEVE_MAX_TOKENS 6) or a new type into one listing 11, or two ADD_SLEEVE_ILK for different types sharing a token. Each such proposal is accepted, waits 48h, then every applyPending reverts; GovernedByKind keeps the slot and its lock bits until cancel (an expired proposal also keeps them), and a correct re-proposal of that kind reverts ProposalPending. Impact: governance liveness only under the Safe's own payloads (a lost 48h cycle on the depth-gated sIMD line or the depth leg; inside a BATCH one bad item fails the whole batch at apply). No funds or parameters move. Reachable with BetaConfig: yes (ImdDepth with 3 samplers is set at genesis; a 4th exit pool and the swarm depth leg are exactly what the Safe expects to add after genesis; re-adding a sampler for an already measured pool with new band settings without removeDepthSampler first is a realistic operator mistake). RETIRE_SLEEVE_TOKEN's 3-word payload is already in Known issues. Smallest fix: in _validate, for ADD_DEPTH_SAMPLER read IDepthPool(sampler).manager()/poolId() and compare with imdDepth.samplers() (revert OutOfBounds on a match or when samplers().length >= 6), or add a view ImdDepth.canAdd(address) mirroring addSampler and call it (one external call in Rules); for SET_DEPTH_LEG require leg.code.length != 0 && price.code.length != 0 when non-zero; for BATCH refuse two items of a once-only kind (SET_BRIDGE, SET_KEEPER, ADD_ILK of one ilk) and count new sleeve tokens/types across the batch. Cost: ParametersRules has 82 bytes of EIP-170 room (measured 24,494 B), so these checks need the size work in the info finding first (or the ImdDepth view, which keeps Rules' cost to one call).

**Reproduction**

Reproduced on this commit. Setup: Parameters (governor g) sealed with a depth-gated type and ImdDepth listing sampler S0 (manager M, poolId P). (a) g.propose(abi.encode(uint8(24), S0)) -> accepted (expected: revert OutOfBounds); warp 48h; applyPending(24) -> reverts ImdDepth.BadSampler(); pendingOf(24).eta stays non-zero and bit 24 of locked stays set. (b) same with S1 having code and S1.manager()==M, S1.poolId()==P -> accepted; applyPending(24) reverts BadSampler(). (c) g.propose(abi.encode(uint8(25), address(0xBEEF), feedWithCode)) -> accepted; applyPending(25) reverts BadSampler(). (d) g.propose(abi.encode(BATCH, [ADD_ILK(WSTETH,cfg,risk), ADD_ILK(WSTETH,cfg,risk)])) -> accepted; after 48h applyPending(BATCH kind) reverts IlkExists(). Run: forge test --match-path 'test/scratch/*.t.sol' (solc 0.8.26 via_ir): Proof_7d974e3c7655 -> [FAIL: BadSampler()] test_addListedSamplerRefusedAtPropose, [FAIL: IlkExists()] test_batchDuplicateAddIlkRefusedAtPropose; Proof_f4b0e56b2b28 -> [FAIL: BadSampler()] x3 (already listed, same pool, codeless leg). 0 passed; 5 failed.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "forge-std/Test.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";
import {ImdDepth} from "src/feeds/ImdDepth.sol";
import {IFeed} from "src/interfaces/IFeed.sol";

contract PaStub {}

contract PaJoin {
    address public token;
    address public ledger;

    constructor(address t, address l) {
        (token, ledger) = (t, l);
    }
}

/// A stand-in exit-pool sampler: ImdDepth only reads manager() and poolId() when listing.
contract PaSampler {
    address public manager;
    bytes32 public poolId;

    constructor(address m, bytes32 id) {
        (manager, poolId) = (m, id);
    }
}

/// Wave 2 says propose refuses what apply would fail on. These still pass propose, wait 48h and always revert at
/// apply, holding their slot (and every kind they lock) until the Safe cancels.
contract ProofProposeApply is Test {
    Parameters params;
    ImdDepth depth;
    address gov = makeAddr("gov");
    address ledger;
    address sampler;
    bytes32 constant ETH = "ETH";
    bytes32 constant SIMD = "SIMD";

    function setUp() public {
        params = new Parameters(gov, address(this));
        ledger = address(new PaStub());
        params.wire(ledger, address(new PaStub()));
        _add(ETH, 1_000_000e18);
        _add(SIMD, 0);
        params.setGenesisDepthRule(SIMD, 1e18, 0, 0, 0);
        depth = new ImdDepth(address(params));
        sampler = address(new PaSampler(address(0xBEEF), bytes32(uint256(1))));
        address[] memory list = new address[](1);
        list[0] = sampler;
        params.setGenesisImdDepth(address(depth), list);
        params.seal();
    }

    function _risk(uint128 line) internal pure returns (ParametersBase.Risk memory) {
        return ParametersBase.Risk({
            mat: 1.5e18, chop: 0.1e18, cut: 0.1e18, chip: 0.01e18, rateFloor: 0.005e18, yieldFee: 0, skew: 0.02e18,
            pegFloor: 0, line: line, dust: 100e18, redeemFloor: 0.005e18, redeemDivisor: 4, redeemCap: 0
        });
    }

    function _cfg() internal returns (ParametersBase.Config memory c) {
        c.token = address(new PaStub());
        c.join = address(new PaJoin(c.token, ledger));
        c.median = IFeed(address(new PaStub()));
        c.spot = c.median;
        c.redeemable = true;
    }

    function _add(bytes32 ilk, uint128 line) internal {
        params.addGenesisIlk(ilk, _cfg(), _risk(line));
    }

    /// ADD_DEPTH_SAMPLER of a sampler ImdDepth already lists: _validate checks only that it has code.
    function test_addListedSamplerRefusedAtPropose() public {
        bytes memory p = abi.encode(params.ADD_DEPTH_SAMPLER(), sampler);
        vm.prank(gov);
        try params.propose(p) {
            // Queued: it must at least apply after the delay.
            vm.warp(block.timestamp + 48 hours);
            params.applyPending(params.ADD_DEPTH_SAMPLER()); // actual: reverts BadSampler (already listed)
        } catch {}
    }

    /// A BATCH adding the same new type twice: each item is validated against the state before the batch.
    function test_batchDuplicateAddIlkRefusedAtPropose() public {
        bytes[] memory items = new bytes[](2);
        bytes memory add = abi.encode(params.ADD_ILK(), bytes32("WSTETH"), _cfg(), _risk(1_000e18));
        (items[0], items[1]) = (add, add);
        bytes memory p = abi.encode(params.BATCH(), items);
        vm.prank(gov);
        try params.propose(p) {
            vm.warp(block.timestamp + 48 hours);
            params.applyPending(params.BATCH()); // actual: reverts IlkExists on the second item
        } catch {}
    }
}
```

### 2. Low: Q1: lowerOtherImdLines is refused only while the depth line binds at the call; lowered while depth is slack, the instant act raises the enforced sIMD line without the 48h timelock as soon as depth fal

`src/Parameters.sol:214`

```
    function lowerOtherImdLines(uint256 lines) external onlyGovernor {
        if (depthIlk == bytes32(0) || lines >= otherImdLines) revert OutOfBounds();
        if (depthLine() < _risk[depthIlk].line) revert OutOfBounds();
```

The wave-1 fix states the instant lower is refused because it 'would RAISE the enforced line without the timelock; SET_OTHER_IMD (48h) does that'. The guard (line 216) reads depthLine() at the moment of the call. depthIMD() is ImdDepth's 7-day low and changes every hour (keeper gaps, the depth griefing in Known issues). Lowering otherImdLines while depthLine() >= the stored line removes the other-chain term from every FUTURE depthLine(); when depth later falls, risk(SIMD).line = min(stored, depthLine()) is higher than it would have been with the old term. This is the wave-1 raise again, delayed until depth binds, and reachable with BetaConfig: otherImdLines counts the Robinhood IMD line (3,000 at chop 20%, a 3,600 term), so lowering it to 0 is up to 3,000 imdUSD more enforced sIMD line without the timelock. The Safe is trusted and the raise is bounded by the stored line, so severity is low; the point is that the fix does not deliver the property it claims. Smallest fix: remove lowerOtherImdLines (an instant act that can only ever widen room is not a risk-reducing act) and leave the change to SET_OTHER_IMD (48h); or require the stored sIMD line to be lowered by at least the removed term in the same call, so the enforced line can never increase.

**Reproduction**

Reproduced on this commit. State: SIMD stored line 10,000e18, chop 0.2, redeemCap 0, k = 1, otherImdLines 3,000e18 at chop 0.2, measured depth 15,600e18 -> depthLine = (15,600 - 3,600)/1.2 = 10,000 (not binding). Governor: lowerOtherImdLines(0) -> accepted. One hour later depth reads 12,000e18. Expected (term still counted, change being timelocked): risk(SIMD).line = (12,000 - 3,600)/1.2 = 7,000e18. Actual: 12,000/1.2 = 10,000e18. Run: forge test --match-path test/scratch/Proof_1262e517d5de.t.sol -> [FAIL: instant act raised the enforced sIMD line: 10000000000000000000000 > 7000000000000000000000] test_lowerOtherImdLinesDoesNotRaiseLineAfterDepthFalls(). 0 passed; 1 failed.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "forge-std/Test.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";
import {IFeed} from "src/interfaces/IFeed.sol";

contract OlStub {}

contract OlJoin {
    address public token;
    address public ledger;

    constructor(address t, address l) {
        (token, ledger) = (t, l);
    }
}

/// The measured depth, moved by the test (it moves hourly on chain: DepthSampler + ImdDepth.poke).
contract OlDepth {
    address public params;
    uint256 public depth;

    constructor(address p) {
        params = p;
    }

    function set(uint256 d) external {
        depth = d;
    }

    function addSampler(address) external {}
}

/// Wave 2 refuses lowerOtherImdLines only while the depth line binds NOW. Lowered one block before it binds, the instant
/// act still raises the enforced sIMD line as soon as depth falls: the same raise without the 48h timelock.
contract ProofOtherImdLater is Test {
    Parameters params;
    OlDepth depth;
    address gov = makeAddr("gov");
    bytes32 constant SIMD = "SIMD";

    function setUp() public {
        params = new Parameters(gov, address(this));
        address ledger = address(new OlStub());
        params.wire(ledger, address(new OlStub()));
        address t = address(new OlStub());
        ParametersBase.Config memory c;
        c.token = t;
        c.join = address(new OlJoin(t, ledger));
        c.median = IFeed(address(new OlStub()));
        c.spot = c.median;
        c.redeemable = true;
        ParametersBase.Risk memory r = ParametersBase.Risk({
            mat: 1.7e18, chop: 0.2e18, cut: 0.04e18, chip: 0, rateFloor: 0.005e18, yieldFee: 0, skew: 0.02e18,
            pegFloor: 0, line: 10_000e18, dust: 100e18, redeemFloor: 0.005e18, redeemDivisor: 2, redeemCap: 0
        });
        params.addGenesisIlk(SIMD, c, r);
        // BetaConfig's other-chain term: the Robinhood IMD line 3,000 at chop 20%.
        params.setGenesisDepthRule(SIMD, 1e18, 0, 3_000e18, 0.2e18);
        depth = new OlDepth(address(params));
        params.setGenesisImdDepth(address(depth), new address[](0));
        params.seal();
        depth.set(15_600e18); // depthLine = (15,600 - 3,600) / 1.2 = 10,000 = the stored line: not binding
    }

    function test_lowerOtherImdLinesDoesNotRaiseLineAfterDepthFalls() public {
        assertEq(params.risk(SIMD).line, 10_000e18);
        vm.prank(gov);
        try params.lowerOtherImdLines(0) {} catch {} // accepted: the depth line does not bind at this moment
        // One hour later the measured depth falls 23% (a keeper gap or a cheap push, README 'Depth griefing').
        depth.set(12_000e18);
        // With the other chain's 3,000 still counted: (12,000 - 3,600) / 1.2 = 7,000. After the instant act: 10,000.
        assertLe(params.risk(SIMD).line, 7_000e18, "instant act raised the enforced sIMD line");
    }
}
```

### 3. Low: Q2 (M6): a resumed stage-4 deploy never compares ImdDepth's listed samplers with the config; a changed sampler list redeploys and records samplers that are never listed, and the run seals with ImdDept

`script/deploy/StageGenesis.sol:299`

```
        if (address(d.params.imdDepth()) != address(d.imdDepth)) {
            g = gasleft();
            d.params.setGenesisImdDepth(address(d.imdDepth), list);
            _rec("params.setGenesisImdDepth", g, CALL_DATA + 32 * n);
        }
```

Yes, a resume can still adopt something it should not: the measured-depth pieces. _stageDepth keeps a recorded ImdDepth if its params() matches, compares each recorded DepthSampler with its spec (_samplerIs, which stops with Mismatch('DepthSampler') on a difference: verified), but (a) line 276 `if (d.samplers.length != n) d.samplers = new DepthSampler[](n);` discards the whole recorded array whenever the config's pool count differs from the record (a 4th exit pool added before a resume, or a record that lost an entry), so every sampler is deployed afresh and recorded; and (b) setGenesisImdDepth (lines 299-303), the only genesis call that lists samplers, runs only while Parameters does not yet point at the recorded ImdDepth. Nothing compares d.imdDepth.samplers() with `list`. Together: the resumed run records n fresh samplers, ImdDepth keeps the first run's listing (a pool the operator dropped as suspect keeps counting toward depth, so the sIMD line is sized higher than the config intends; an added pool is never measured; a swapped sampler, cleared in the record per the DeployBase header, is recorded but not listed), no Mismatch fires, and the stage goes on to seal(). The deployment record used for verification and for the hourly sampling keeper then names samplers the depth rule never reads; if the keeper samples the recorded addresses, the listed ones read 0 after about 6 hours and the sIMD line is held at 0 for about 8 days. After the seal the repair is removeDepthSampler (instant) plus one ADD_DEPTH_SAMPLER (48h) per pool, one pending at a time. Every other kept piece (types, feeds, risk, sleeves, Allocator, backstop wiring, a changed sampler at the same index) now stops with Mismatch; the PEG-type gap is in Known issues. The same adopt-what-is-there pattern applies to extra sleeve listings and edgeIlk flags left by an earlier config (compared only for the ilks THIS config names) and to setGenesisCap/Target/Group, which no stage checks. Reachable with BetaConfig (depth.enabled, 3 samplers) on any resume whose record and config disagree on the sampler list. Severity low: only a resumed stage reaches it and governance can repair in 48h per pool. Smallest fix (script only, about 8 lines, no contract change): do not reset d.samplers when the length differs (reuse recorded entries by index), and when address(d.params.imdDepth()) == address(d.imdDepth) require keccak256(abi.encode(d.imdDepth.samplers())) == keccak256(abi.encode(list)), else revert Mismatch('ImdDepth lists other samplers').

**Reproduction**

Reproduced on this commit with a harness exposing StageGenesis._stageDepth (real ImdDepth and DepthSampler, stub PoolManager). Run 1 with cfg.depth.samplers = [pool P1] on an empty record: ImdDepth deployed, sampler A deployed and listed, params.imdDepth() == ImdDepth; the run stops before the seal. Config gains pool P2; stage 4 is resumed on the same record. Expected: ImdDepth.samplers() == d.samplers (two entries), or the run stops with Mismatch. Actual: two new samplers are deployed and recorded, setGenesisImdDepth is skipped, ImdDepth.samplers() == [A], no revert. Run: forge test --match-path test/scratch/Proof_c481e43ca23f.t.sol -> [FAIL: ImdDepth does not list the config's samplers: 1 != 2] test_resumedDepthStepListsTheSamplersItKeeps() (gas: 7644175). 0 passed; 1 failed.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "forge-std/Test.sol";
import {DeployTypes} from "script/DeployConfig.sol";
import {StageGenesis} from "script/deploy/StageGenesis.sol";
import {Parameters} from "src/Parameters.sol";
import {ImdDepth} from "src/feeds/ImdDepth.sol";
import {IFeed} from "src/interfaces/IFeed.sol";

/// A pool manager whose every pool reads as initialised at price 1 (StateLibrary.getSlot0 reads extsload).
contract RsCode {
    function extsload(bytes32) external pure returns (bytes32) {
        return bytes32(uint256(1 << 96));
    }
}

contract RsToken {
    function decimals() external pure returns (uint8) {
        return 18;
    }
}

/// Stage 4's depth step exactly as the launch runs it, on a deployment record `d`.
contract RsStage is StageGenesis {
    function depthStep(DeployTypes.Config memory cfg, Deployed memory d) external returns (Deployed memory) {
        _stageDepth(cfg, d);
        return d;
    }
}

/// A resumed stage 4 that rebuilds a sampler (the recorded one is from another config) never lists the new one:
/// Parameters already points at the recorded ImdDepth, so `setGenesisImdDepth` is skipped and ImdDepth keeps measuring
/// the depth of the OLD samplers, which nothing compares with the config.
contract ProofResumeSamplers is Test {
    RsStage h;
    address manager;
    address tokenA;
    address tokenB;

    function setUp() public {
        h = new RsStage();
        manager = address(new RsCode());
        (tokenA, tokenB) = (address(new RsToken()), address(new RsToken()));
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
    }

    function _spec(DeployTypes.SamplerSpec memory sp, uint24 fee, int24 spacing) internal view {
        (sp.currency0, sp.currency1, sp.fee, sp.tickSpacing, sp.hooks) = (tokenA, tokenB, fee, spacing, address(0));
        sp.poolId = keccak256(abi.encode(tokenA, tokenB, fee, spacing, address(0)));
        (sp.feed0, sp.feed1) = (DeployTypes.NO_FEED, DeployTypes.NO_FEED);
        (sp.bandBps, sp.maxDeviationTicks, sp.maxSteps, sp.soldIsToken0) = (1_500, 200, 64, true);
    }

    /// `n` exit pools: the first is the same pool and spec in every config.
    function _cfg(uint256 n) internal view returns (DeployTypes.Config memory cfg) {
        cfg.poolManager = manager;
        cfg.depth.enabled = true;
        cfg.depth.samplers = new DeployTypes.SamplerSpec[](n);
        _spec(cfg.depth.samplers[0], 10_000, 200);
        if (n > 1) _spec(cfg.depth.samplers[1], 3_000, 60);
    }

    function test_resumedDepthStepListsTheSamplersItKeeps() public {
        RsStage.Deployed memory d;
        d.params = new Parameters(makeAddr("gov"), address(h));
        d.feeds = new IFeed[](0);
        // Run 1 lists one exit pool's sampler A in ImdDepth (the run then stops later in stage 4, before the seal).
        d = h.depthStep(_cfg(1), d);
        address a = address(d.samplers[0]);
        assertEq(d.imdDepth.samplers()[0], a);
        // The config gains a second exit pool and stage 4 is resumed on the same record.
        try h.depthStep(_cfg(2), d) returns (RsStage.Deployed memory d2) {
            address[] memory listed = d2.imdDepth.samplers();
            // expected: ImdDepth measures the two samplers the record now holds (or the resume stops: Mismatch).
            // actual: both were rebuilt, neither is listed, and ImdDepth still measures A alone.
            assertEq(listed.length, 2, "ImdDepth does not list the config's samplers");
            assertEq(listed[0], address(d2.samplers[0]));
            assertEq(listed[1], address(d2.samplers[1]));
        } catch {
            // refused (Mismatch): also correct
        }
    }
}
```

### 4. Info: Q4 room to grow: ParametersRules has 82 bytes left (24,494 B runtime), Parameters' creation code is 1,417 B under EIP-3860, Allocator has 1,878 B (not ~2.6 KB), Ledger 2,178 B; the immutable rules mod

`src/ParametersRules.sol:10`

```
    uint256 internal constant SLEEVE_MAX_TOKENS = 6; // Backstop.MAX_TOKENS
    uint256 internal constant SLEEVE_MAX_ILKS = 12; // Backstop.MAX_ILKS
```

Measured on this commit's solc 0.8.26 via_ir artifacts (bytecode_hash none, the panel build): ParametersRules runtime 24,494 B (82 B to EIP-170's 24,576), Parameters runtime 22,404 B (2,172 left) but creation code 47,735 B (1,417 B under the 49,152 B EIP-3860 init-code limit, because `rules = new ParametersRules(governor_)` embeds Rules' creation code in Parameters' constructor), Ledger 22,398 B (2,178 left), Allocator 22,698 B (1,878 left, against the brief's ~2.6 KB), Backstop 19,942 B, Liquidator 12,112 B. Rules inherits ParametersBase and GovernedByKind, so propose/cancel/applyPending and every base event and error are compiled into Rules as dead code, and every byte added to the shared base is paid in both contracts. `rules` is immutable in Parameters and Parameters is immutable in Ledger, Pricer, Treasury, the sleeves and the hook: adding a governed kind (a third sleeve, a chain, a module), tightening a validation (the fixes for the propose/apply finding cost roughly 60-150 B), adding a per-step raise bound (Known issues) or a veto role all need a new Parameters and a full redeploy. One pending proposal per kind is softened by BATCH (MAX_BATCH items, locking every kind it touches) but a stuck proposal (previous finding) blocks its kind for 48h plus a cancel. Order in which v2 runs out: (1) Backstop MAX_TOKENS at genesis (next finding), (2) ParametersRules code size, (3) Parameters init code, (4) one slot per kind. What should change before the 2026-11-20 freeze (small): let ParametersRules take the governor as a constructor argument and inherit only a storage/constants part of ParametersBase, not GovernedByKind (frees several KB in Rules and in Parameters' init code); write the sampler/leg checks as an ImdDepth view. After the beta: a SET_RULES kind under a longer timelock (7 days) so validations can be tightened without a redeploy.

**Reproduction**

Build the panel with foundry.toml's settings (forge test on the panel glob or test/scratch compiles Parameters) and read out/ParametersRules.sol/ParametersRules.json deployedBytecode.object: 24,494 B; out/Parameters.sol/Parameters.json bytecode.object: 47,735 B; out/Allocator.sol/Allocator.json deployedBytecode: 22,698 B; out/Ledger.sol/Ledger.json: 22,398 B. Adding about 90 B of validation to ParametersRules._validate fails the build with 'contract code size exceeds 24576 bytes'.

### 5. Info: Q4 room to grow: BetaConfig fills the blue sleeve to Backstop.MAX_TOKENS (6) at genesis and the sleeves are set once in Parameters, so no new blue collateral token can ever get the standing bid withou

`script/DeployConfig.sol:518`

```
        b.ilks[0] = DeployTypes.SleeveIlk("ETH", false, 0, 50e18);
        b.ilks[1] = DeployTypes.SleeveIlk("WSTETH", false, 0, 40e18);
        b.ilks[2] = DeployTypes.SleeveIlk("CBBTC", false, 0, 2e8);
        b.ilks[3] = DeployTypes.SleeveIlk("WBTC", false, 0, 2e8);
        b.ilks[4] = DeployTypes.SleeveIlk("S-USDS", false, 0, 200_000e18);
        b.ilks[5] = DeployTypes.SleeveIlk("S-USDC-STEAKHOUSE", false, 0, 200_000e18);
```

backstopSpec lists six distinct blue tokens at genesis: WETH, wstETH, cbBTC, WBTC, sUSDS and steakUSDC (src/backstop/Backstop.sol:66 MAX_TOKENS = 6; ParametersRules.sol:113 refuses ADD_SLEEVE_ILK for a NEW token once tokenCount() >= SLEEVE_MAX_TOKENS). Parameters.blueBackstop/edgeBackstop are written once by setGenesisBackstops (src/Parameters.sol:142-149) before the seal and there is no governed kind to add or replace a sleeve (and 82 B of room to add one). So from day one the first new blue type on a new token (another LST, tBTC, another staked stable) can only be listed without a standing bid; its liquidations go to callers only. A token freed by RETIRE_SLEEVE_TOKEN still counts. Of everything in v2 this runs out first, before code size or proposal slots. Smallest change before the freeze: raise Backstop.MAX_TOKENS (and SLEEVE_MAX_TOKENS) to 8-10, or leave one slot free at genesis by listing only one of the two BTC wrappers in the sleeve. Longer term: a timelocked kind that names a further sleeve address.

**Reproduction**

Deploy with BetaConfig: blue.tokenCount() == 6. ADD_ILK a new type X on a new token (48h), then propose(abi.encode(ADD_SLEEVE_ILK, X, false, 0, saleMax, slope)) -> reverts OutOfBounds at propose (ParametersRules.sol:113), while the ADD_SLEEVE_ILK for a type on an already listed token (e.g. a second wstETH type) is accepted.

### 6. Info: Answers to questions 3 and 5 (operations; governance as the last key): no defect beyond the findings above, design assessment and cheapest hardening

`README.md:154`

```
## Trust model

- **Governor:** a 2-of-3 Safe, immutable in each contract. It acts only through the 48-hour timelocks of `Parameters`,
  `Treasury` and `Allocator`, except instant actions: the risk-reducing ones (lowering a line, a cap, a keeper cap, a
  depth ceiling, a bucket; disabling a sleeve listing; freezing the Allocator), unfreezing the Allocator, and
  `Allocator.returnToTreasury` (funds held there back to the Treasury, no bucket). It cannot move user collateral or
  mint imdUSD directly. It can name one bridge minter, once, through the 48-hour timelock (`SET_BRIDGE`): that minter
  can mint without limit and burn from any holder. The beta leaves the slot empty.
```

Q3 OPERATIONS. Cost of each missing action (BetaConfig): DEPTH samples + hourly ImdDepth.poke: 1h nothing (an hour keeps its lowest, a missed hour is not counted); about 6h missed inside a 26h window reads 0 depth and the 7-day low holds new sIMD borrowing at 0 for about 8 days (Known issues; 1 day and 1 week the same, repayment and liquidation untouched). RELAYING ATTESTATIONS (sIMD legs, NHI, seat median/spot, depth leg): 1h the per-epoch cap widens 2x, 1 day the feed is stale so borrowing on those types stops and borrowing up to the line may use the last low; 1 week the same plus edge marks stop counting after 7 days. TICKS/MARKS/LIQUIDATIONS: 1h in a calm market nothing; in a 20%+ move an hour of no liquidator is bad debt on blue types above chop; the standing bid makes a bite self-executing once marked, so the mark is the chore that matters; 1 day/1 week: sleeve losses, the unbacked-supply brake, every bucket held. SEAT POKES/AUCTIONS and COLLATERAL AUCTIONS: a day's delay sells at a staler decayed price; a week leaves healed-by-price auctions open (Known issues). BUFFER/LP RULES and BACKSTOP CONVERSIONS: rule-driven and permissionless, bounded by daily buckets; a week unrun means the buffer and LP drift from target and matured deposits wait (anyone may call realize). Where to put each: lazily inside user transactions for what is cheap and state-only (ImdDepth.poke folded into the depth-gated borrow path and Backstop.realize on the first touch, both already permissionless); an on-chain tip for marks/liquidations (chop already pays; add a small fixed tip for the mark so the first mover is paid even when the bite goes to the standing bid); a funded chore ONLY for depth sampling, because the operator must sample through private relays to avoid the +L/sample/-L inflation (Known issues), which no public tip can enforce. Oracle answers: at 0.5 IMD per answer and a 1h max age for the IMD leg, an on-chain asker costs 24 answers a day per feed (12 IMD/day, about 4,400 IMD/yr per feed) from a Treasury that holds almost no USDC and no IMD budget; whoever-needs-pays (relay with the borrow) keeps liveness tied to demand and costs the protocol nothing, so keep it, and fund a chore only for the depth leg if the Safe enables it. Q5 GOVERNANCE AS THE LAST KEY. Worst a COMPROMISED 2-of-3 Safe does: instantly, lower every line, cap and keeper cap to the floor (new borrowing and plain withdrawals from indebted positions stop until SET_CAP 48h), freeze the Allocator, disable sleeve listings (standing bid off), returnToTreasury, and the lowerOtherImdLines raise in finding 2; within 48h, SET_BRIDGE names a minter that mints without limit and burns from any holder (the single catastrophic power, and the beta keeps the kind live with the slot empty), SET_KEEPER, raises of lines/mat/depth with no per-step bound (Known issues), ADD_ILK of a worthless token with a high line (two 48h steps). An ABSENT Safe: nothing can be raised, cancelled or unfrozen; a stuck proposal holds its kind; the protocol runs on frozen parameters and fail-closed oracles, which is survivable for the beta. Cheapest hardening, in order of cost: (1) monitoring: alert on every Proposed event and on any instant lower, with a 48h human review; cost zero contract bytes. (2) Do not ship SET_BRIDGE live in the beta: refuse it in _validate (about 20 B) or have ImdUSD cap the bridge minter by a daily mint bucket like keeperCap. (3) A cancel-only guardian key in GovernedByKind (one address, cancel(kind) allowed to it) so a second party can veto a 48h proposal without being able to propose; about 100 B in the base, which today lands in both Parameters and Rules, so it needs the Rules refactor in the size finding first. (4) A 7-day timelock for SET_BRIDGE/SET_KEEPER/ADD_ILK (a per-kind delay table). Option ranking: (2)+(1) before the freeze, (3) with the size refactor, (4) after the beta.

**Reproduction**

Design assessment, not a defect: figures from README Known issues (6h sampler gap -> 8 days at 0; 2x cap after 1h stale), src/GovernedByKind.sol (cancel is governor-only; TIMELOCK 48h; a slot persists through expiry), src/Parameters.sol instant lowers (lowerCap, lowerLine, lowerDepthLine, lowerOtherImdLines, disable sleeve listing), ParametersRules SET_BRIDGE branch (line 45-49; refused only when already set), and the task's 0.5 IMD per answer with a 1h max age.

---

Judge's submission `e493c2e6727a615468e54fbe3c56067cc6bfdf0a3bffe66115eebe8ed68a2a8f`, accepted on the IdentityMD network. Acceptance means the report met the job's checks;
it is not a guarantee that the code has no other defects.
