# Audit report

> RE-CHECK the wave-2 fixes in src/Parameters.sol, src/ParametersRules.sol, src/feeds/ImdDepth.sol, script/deploy/ (StageGenesis, StageFeeds, DeployBase), and REVIEW the beta as deployed and run: script/DeployConfig.sol BetaConfig, the size margins, the keeper's recurring gas, 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; prices come from Chainlink and swarm-attested feeds. README.md gives scope, invariants, trust model and known issues: read it first. Commit 1 (2875ffb) was audited in wave 1, commit 2 (5de80a6) in wave 2; this third commit is the whole delta since (README 'What changed since the second public audit').
>
> 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/{AuditW2{ProposeAtApply,LowerOtherImd,ResumeSamplers},AuditW1{BatchItems,OtherImdLines},DepthRule,PanelParams,CapAndSlots}.t.sol'`. With Foundry 1.9+, `forge test --use solar --no-match-path 'test/fork/*'` builds everything and runs all 1,297 tests in seconds under 1 GB (confirm a proof and a gas figure 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 2's findings and proofs are public: GET https://api.imd.fun/jobs/<id>/submissions for jobs 5fcd4063 (money), 5a8d427d (prices), 62b92eb1 (running); each fix has a test named AuditW2*. For questions 1-3, re-run each original proof for these files against this commit and say whether it still fails, and why.
>
> Questions 4-5: For each: measure, do not estimate (forge test --gas-report or gasleft() in a test), rank the options given and any better one, and say what you would build, with its cost. A change that saves gas but weakens a check, a bound or a README invariant is a finding, not a saving. Constraints: beta on 2026-12-07; Glamsterdam (EIP-8037/8038, not final) would price a new storage slot 110,020 gas and an update 12,100. Report concrete defects as findings in the usual form.
>
> Answer each numbered question:
> 1. A BATCH is dry-run at propose (Parameters.checkBatch / dryRun, a self-call that always reverts) and refused when an item fails only because of an earlier one. Can the dry run change state, be re-entered, be made to pass while the apply fails (or the reverse), or price a legitimate batch out of a block? Is an item waiting on state still accepted?
> 2. ADD_DEPTH_SAMPLER asks ImdDepth.canAdd at propose, SET_DEPTH_LEG needs code on both, lowerOtherImdLines is removed, a resumed stage 4 stops when ImdDepth lists other samplers. What still passes propose and fails at apply, or what can a resume still adopt?
> 3. The new PROVEN_POOL feed kind is deployed empty and verified by Check/DeployBase. Can a deploy or a resume adopt a wrong ProvenPoolPrice (manager, pool, base side, max age), and does anything at genesis read it before its first proof?
> 4. SIZE AND ROOM. Measured under solc: Parameters init code 762 bytes under EIP-3860, ParametersRules 165 bytes, Ledger 1,778, Allocator 1,767. Per-contract optimizer runs failed because the deploy scripts compile every contract in one job (Ledger went over EIP-170). What should change before mainnet: deploying hot contracts from separately compiled artifacts, splitting ParametersRules off GovernedByKind, or else?
> 5. GAS OVERALL. Name the three largest gas items of the protocol's own recurring bill (keeper) and of a borrower's first month, each with the change that removes most of it, measured. Include what Glamsterdam pricing does to each.
>
> 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.
>
> 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 | `c64eceed2610694debaedf2be9bd28b8593778c5` |
| Job | `b19b5e0c-704e-4104-a012-f4a8bfc22b72` |
| Judged | 2026-11-14 18:29 UTC |
| Findings | 4 low · 1 info |

Four agents audited the code as it is at `c64ecee`, 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: BATCH dry run stops at the first item that waits on state: a later item broken by an earlier one still passes propose and can never apply

`src/Parameters.sol:419`

```
        if (_dry(items, n - 1, n)) revert BadConfig();
```

Merged from three specialists (permissions, flow, economics), all reproduced. README ('BATCH proposals are dry-run at propose'): an item that fails only because of an earlier item in the same batch is refused at propose. Parameters.checkBatch (lines 414-420) dry-runs the whole batch, then walks prefixes [0,n) to the FIRST failing one and asks only whether item n-1 fails alone. When that item legitimately waits on state (BetaConfig: the sIMD line raise before the measured depth exists, line 0 and depth 0 until day 7; also a RETIRE before its feed stops), checkBatch returns and no item after it is ever dry-run in order. So BATCH [SET_RISK(SIMD, line up), ADD_ILK X, ADD_ILK X] (or [ADD_ILK X, SET_RISK SIMD, ADD_ILK X]) passes propose, exactly the wave-2 case (two ADD_ILK of one type, two SET_KEEPER, two sleeve listings) hidden behind a waiting item. Call sequence: governor propose(BATCH) -> _validate -> ParametersRules.validateKind(BATCH) -> IBatchCheck(this).checkBatch -> _dry(0,3) false (DepthRuleFails at item 0) -> _dry(0,1) false -> _dry(0,1) alone false -> return (accepted). The batch locks BATCH, SET_RISK and ADD_ILK for 48 h plus the slot's life, and applyPending(BATCH) reverts whatever the depth: with depth present the apply-time re-validation runs checkBatch again, now reaches item 2 and reverts BadConfig; with no depth it reverts DepthRuleFails. The Safe must cancel and re-propose (another 48 h). Impact: governance liveness only, no funds (same class as the wave-2 low). Reachable with BetaConfig: the day-7 batch carries the sIMD line item that waits on depth by design, MAX_BATCH is 8. Smallest fix: one in-order pass that, when item i fails, dry-runs item i alone against the pre-batch state: passes alone -> revert BadConfig; fails alone -> mark it waiting, skip it, and continue applying the remaining items on the accumulated state (have dryRun take a skip mask and revert with the index of the first failure). Every item is then checked against the items before it, and the check is linear, which also fixes the quadratic-gas finding on line 418.

**Reproduction**

State: Parameters sealed, SIMD registered with line 0, setGenesisDepthRule(SIMD, 1e18, 0, 0, 0), ImdDepth stand-in reading depth 0 (the beta before day 7). Input: governor propose(abi.encode(BATCH, [ADD_ILK WSTETH, SET_RISK(SIMD, line 1,000e18), ADD_ILK WSTETH])). Expected: revert BadConfig (as AuditW2ProposeAtApply.test_batchDuplicateAddIlkRefusedAtPropose shows for the two ADD_ILK without the waiting item). Actual: propose succeeds; then with depth set to 10,000e18 and 48 h later applyPending(BATCH) reverts BadConfig and the ADD_ILK lock stays set. Run on c64ecee: forge test --match-path 'test/scratch/Proof_59301b228fbd.t.sol' -> [FAIL: a batch whose third item fails only because of its first was accepted at propose] test_itemBrokenByAnEarlierItemBehindAWaitingItemIsRefusedAtPropose() (gas: 5410814). The two other specialists' proofs fail the same way ([FAIL: next call did not revert as expected] test_duplicateAddIlkBehindAWaitingItemIsRefusedAtPropose, test_brokenPairBehindWaitingItemIsNotRefused; [FAIL: BadConfig()] test_acceptedBatchNeverApplies).

**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 PbStub {}

contract PbJoin {
    address public token;
    address public ledger;

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

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

    constructor(address p) {
        params = p;
    }

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

    function addSampler(address) external {}
}

/// Parameters.checkBatch stops at the FIRST item that fails in order and only asks whether THAT item fails alone. An
/// item behind it that fails only because of an earlier item (the wave-2 case: two ADD_ILK of one type) is never dry-run
/// against the items before it. The batch passes propose, locks ADD_ILK and SET_RISK for 48 h, and can never apply:
/// once the waiting item's state arrives (depth), apply reaches the third item and reverts IlkExists.
contract ProofBatchAfterWaitingItemTest is Test {
    Parameters params;
    PbDepth depth;
    address gov = makeAddr("gov");
    address ledger;
    bytes32 constant SIMD = "SIMD";

    function setUp() public {
        params = new Parameters(gov, address(this));
        ledger = address(new PbStub());
        params.wire(ledger, address(new PbStub()));
        params.addGenesisIlk(SIMD, _cfg(), _risk(0));
        params.setGenesisDepthRule(SIMD, 1e18, 0, 0, 0);
        depth = new PbDepth(address(params));
        params.setGenesisImdDepth(address(depth), new address[](0));
        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 PbStub());
        c.join = address(new PbJoin(c.token, ledger));
        c.median = IFeed(address(new PbStub()));
        c.spot = c.median;
        c.redeemable = true;
    }

    function test_itemBrokenByAnEarlierItemBehindAWaitingItemIsRefusedAtPropose() public {
        bytes memory add = abi.encode(params.ADD_ILK(), bytes32("WSTETH"), _cfg(), _risk(1_000e18));
        // Fails alone today (measured depth 0: DepthRuleFails) and is meant to wait for depth, as a single proposal may.
        bytes memory line = abi.encode(params.SET_RISK(), SIMD, _risk(1_000e18));
        bytes[] memory items = new bytes[](3);
        (items[0], items[1], items[2]) = (add, line, add);
        uint8 b = params.BATCH();
        bytes memory batch = abi.encode(b, items);

        vm.prank(gov);
        (bool accepted,) = address(params).call(abi.encodeCall(params.propose, (batch)));
        if (accepted) {
            // The depth arrives, the delay runs: the batch still cannot apply, ever. The SAME dry run, re-run at apply with
            // the depth present, now reaches item 3, finds it passes alone, and refuses the batch (BadConfig).
            depth.set(10_000e18);
            vm.warp(block.timestamp + params.TIMELOCK());
            vm.expectRevert(ParametersBase.BadConfig.selector);
            params.applyPending(b);
            assertTrue(params.locked() & (1 << params.ADD_ILK()) != 0, "ADD_ILK stays locked until the Safe cancels");
        }
        assertFalse(accepted, "a batch whose third item fails only because of its first was accepted at propose");
    }
}
```

### 2. Low: BATCH dry run is quadratic in the batch length: a full batch with one waiting item costs 17.85M gas at propose, over EIP-7825's 16,777,216 transaction cap

`src/Parameters.sol:418`

```
        while (_dry(items, 0, n)) ++n;
```

Merged from two specialists (economics, math), reproduced and extended. checkBatch dry-runs the whole batch, then prefixes [0,1), [0,2), ... up to the first failing one, then that item alone: with the first failure at item k that is 1 + k(k+1)/2 + 1 item applications (45 for k = 8). Each dry run is a reverting self-call, so its SSTOREs (ADD_ILK creates about 13 slots) and cold accesses are paid in full every time and refunded nothing. Measured (solc 0.8.26 via_ir, isolate, gasleft() around propose): 7 ADD_ILK + SET_RISK(SIMD line raise before depth, allowed in a batch by the README) = 17,854,743; the same eight items with none waiting = 6,650,702; with k ADD_ILK + the waiting item last: 1 -> 2,212,901; 2 -> 4,001,549; 3 -> 6,117,481; 4 -> 8,561,012; 5 -> 11,332,384; 6 -> 14,431,965; k+1 ADD_ILK none waiting: 1,833,490 / 2,636,127 / 3,439,173 / 4,242,699 / 5,046,690 / 5,851,301. Sent at exactly 16,777,216 gas the 7+1 propose reverts (no pending batch, the check is not silently skipped: the 63/64 rule leaves too little to store the payload). Mainnet has run EIP-7825 since Fusaka and will on 2026-12-07, so a legitimate batch the design allows cannot be proposed in one transaction, and the item ORDER (waiting item first: ~4.1M; last: 17.9M) decides whether a batch is proposable. applyPending re-validates, so an accepted batch pays the dry run again at apply (8 ADD_ILK: 6,444,921). Under the Glamsterdam figures given (new slot 110,020, update 12,100) each ADD_ILK dry application rises by about 13 x 87,920 = 1.14M, so even 3 ADD_ILK + a waiting item (10 dry applications of ADD_ILK) would add about 11M and exceed the cap. Reachable with BetaConfig (a governance payload, no special state). Impact: governance liveness and cost only. Smallest fix: the linear single-pass check of the previous finding (dryRun reverts with the index of the first failing item and takes a skip mask: two self-calls per waiting item instead of up to n+2 prefix runs), and skipping the dry run at applyPending, where the real apply already fails in order.

**Reproduction**

Setup as the previous finding (SIMD at line 0, depth 0, sealed). Input: propose(abi.encode(BATCH, [ADD_ILK t1..t7 (seven fresh types, line 1,000e18 each), SET_RISK(SIMD, line 1,000e18)])). Expected: fits in a mainnet transaction (<= 16,777,216 gas). Actual: 17,854,743 gas. Run on c64ecee: forge test --match-path 'test/scratch/Proof_1b1425d8e050.t.sol' -vv -> [FAIL: a legitimate full batch cannot be proposed in one transaction: 17854743 > 16777216] test_fullBatchWithOneWaitingItemFitsInATransaction() (gas: 20352161), Logs: gas propose (7 ADD_ILK + 1 waiting item): 17854743. Control (scratch GasCapBehaviour.t.sol): propose(7 ADD_ILK + waiting) at 16,777,216 gas ok? false; the k-item series above.

**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 GcStub {}

contract GcJoin {
    address public token;
    address public ledger;

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

contract GcDepth {
    address public params;
    uint256 public depth;

    constructor(address p) {
        params = p;
    }

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

    function addSampler(address) external {}
}

/// Parameters.checkBatch re-runs the prefix 0..n for every n up to the first failing item (n(n+1)/2 item runs), then the
/// item alone. A full batch (MAX_BATCH = 8) of seven ADD_ILK and one item that waits on state (the sIMD line before depth,
/// which the README says a batch may carry) costs more at propose than EIP-7825's transaction gas cap (16,777,216, in force
/// on mainnet since Fusaka): the Safe cannot propose it at all. The same eight items with none waiting cost 6.65M.
contract ProofBatchGasCapTest is Test {
    uint256 constant EIP_7825_TX_GAS_CAP = 16_777_216;

    Parameters params;
    GcDepth depth;
    address gov = makeAddr("gov");
    address ledger;
    bytes32 constant SIMD = "SIMD";

    function setUp() public {
        params = new Parameters(gov, address(this));
        ledger = address(new GcStub());
        params.wire(ledger, address(new GcStub()));
        params.addGenesisIlk(SIMD, _cfg(), _risk(0));
        params.setGenesisDepthRule(SIMD, 1e18, 0, 0, 0);
        depth = new GcDepth(address(params));
        params.setGenesisImdDepth(address(depth), new address[](0));
        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 GcStub());
        c.join = address(new GcJoin(c.token, ledger));
        c.median = IFeed(address(new GcStub()));
        c.spot = c.median;
        c.redeemable = true;
    }

    function test_fullBatchWithOneWaitingItemFitsInATransaction() public {
        bytes[] memory items = new bytes[](8);
        for (uint256 i; i < 7; ++i) {
            items[i] = abi.encode(params.ADD_ILK(), bytes32(uint256(i + 1)), _cfg(), _risk(1_000e18));
        }
        // Passes validation, fails at apply alone until depth arrives (DepthRuleFails): allowed in a batch by design.
        items[7] = abi.encode(params.SET_RISK(), SIMD, _risk(1_000e18));
        bytes memory batch = abi.encode(params.BATCH(), items);
        vm.prank(gov);
        uint256 g = gasleft();
        params.propose(batch);
        uint256 used = g - gasleft();
        emit log_named_uint("gas propose (7 ADD_ILK + 1 waiting item)", used);
        assertLe(used, EIP_7825_TX_GAS_CAP, "a legitimate full batch cannot be proposed in one transaction");
    }
}
```

### 3. Low: Resumed stage 4 re-points Parameters at a different ImdDepth instead of stopping with Mismatch: setGenesisImdDepth has no already-set guard and the depth step never compares params.imdDepth with the r

`script/deploy/StageGenesis.sol:305`

```
        if (address(d.params.imdDepth()) != address(d.imdDepth)) {
            g = gasleft();
            d.params.setGenesisImdDepth(address(d.imdDepth), list);
```

From the permissions specialist (who could not compile it); reproduced here through a StageGenesis harness. DeployBase's resume rule is that a recorded piece with code but other wiring stops the run (Mismatch), as the sleeves do ('Parameters points at other sleeves', StageGenesis.sol:231). The depth step does not: when Parameters already points at ImdDepth A (a first run that stopped later in stage 4, before the seal) and the resumed record carries no ImdDepth, or another one with params() == Parameters, the step deploys/keeps B and, because params.imdDepth() != B, calls setGenesisImdDepth(B, list) again. Parameters.setGenesisImdDepth (src/Parameters.sol:116-123) checks only code and params(), never that the slot is empty, so it overwrites `imdDepth` and lists the config's samplers on B. A, with every hourly low the keeper may already have poked into it, is orphaned with no Mismatch, the 'ImdDepth samplers' comparison of the wave-2 fix is skipped (it sits in the else branch), and the depth rule restarts from 0 for 6 days (ImdDepth.depth() reads 0 until the window has lows), delaying the beta's day-7 sIMD line. Deployer-only and pre-seal, so no funds: an operational defect in the wave-2 resume fix. Not reachable from a clean single-run BetaConfig deploy; reachable on any resume whose Deployed record disagrees with the chain (a lost or edited record, a resume from an older record). Smallest fix: in Parameters.setGenesisImdDepth add `if (address(imdDepth) != address(0)) revert BadConfig();` (as setGenesisBackstops does), and in _stageDepth add `else if (address(d.params.imdDepth()) != address(0)) revert Mismatch("Parameters points at another ImdDepth");` before the setGenesisImdDepth branch.

**Reproduction**

Run 1: _stageDepth(cfg, d) with one sampler spec deploys ImdDepth A and its sampler and calls params.setGenesisImdDepth(A, [sampler]); params.imdDepth() == A. Resume with the same record but d.imdDepth = ImdDepth(address(0)): expected revert Mismatch (Parameters is wired to A); actual: a new ImdDepth B is deployed, setGenesisImdDepth(B, list) succeeds, params.imdDepth() == B, A is orphaned. Root cause check: setGenesisImdDepth(a) then setGenesisImdDepth(b) on a fresh Parameters both succeed. Run on c64ecee: forge test --match-path 'test/scratch/ProofResumeRepointsImdDepth.t.sol' -> [FAIL: next call did not revert as expected] test_resumeWithoutTheRecordedImdDepthStopsInsteadOfRepointingParameters() (gas: 4622087); [FAIL: next call did not revert as expected] test_setGenesisImdDepthCanBeCalledTwice() (gas: 95067).

**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 RpCode {
    function extsload(bytes32) external pure returns (bytes32) {
        return bytes32(uint256(1 << 96));
    }
}

contract RpToken {
    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 RpStage is StageGenesis {
    function depthStep(DeployTypes.Config memory cfg, Deployed memory d) external returns (Deployed memory) {
        _stageDepth(cfg, d);
        return d;
    }
}

/// DeployBase's resume rule: a recorded piece with code but other wiring stops the run (Mismatch) for a person to decide.
/// The depth step breaks it: when Parameters already points at ImdDepth A (run 1) and the resumed record carries no (or
/// another) ImdDepth, `_stageDepth` deploys B and calls `setGenesisImdDepth(B)` again, which has no already-set guard
/// (Parameters.sol:116-123). A is orphaned with every low the keeper poked into it, and the depth rule restarts at 0.
contract ProofResumeRepointsImdDepthTest is Test {
    RpStage h;
    address manager;
    address tokenA;
    address tokenB;

    function setUp() public {
        h = new RpStage();
        manager = address(new RpCode());
        (tokenA, tokenB) = (address(new RpToken()), address(new RpToken()));
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
    }

    function _cfg() internal view returns (DeployTypes.Config memory cfg) {
        cfg.poolManager = manager;
        cfg.depth.enabled = true;
        cfg.depth.samplers = new DeployTypes.SamplerSpec[](1);
        DeployTypes.SamplerSpec memory sp = cfg.depth.samplers[0];
        (sp.currency0, sp.currency1, sp.fee, sp.tickSpacing, sp.hooks) = (tokenA, tokenB, 10_000, 200, address(0));
        sp.poolId = keccak256(abi.encode(tokenA, tokenB, uint24(10_000), int24(200), 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);
    }

    function test_resumeWithoutTheRecordedImdDepthStopsInsteadOfRepointingParameters() public {
        RpStage.Deployed memory d;
        d.params = new Parameters(makeAddr("gov"), address(h));
        d.feeds = new IFeed[](0);
        // Run 1: ImdDepth A deployed, its sampler listed, Parameters wired to A. The run stops later in stage 4.
        d = h.depthStep(_cfg(), d);
        ImdDepth a = d.imdDepth;
        assertEq(address(d.params.imdDepth()), address(a));

        // Resume on a record that lost the ImdDepth entry (the samplers are still recorded).
        RpStage.Deployed memory d2 = d;
        d2.imdDepth = ImdDepth(address(0));
        // Expected (DeployBase's rule, as the sleeves do: "Parameters points at other sleeves"): revert Mismatch.
        vm.expectRevert();
        h.depthStep(_cfg(), d2);
    }

    function test_setGenesisImdDepthCanBeCalledTwice() public {
        Parameters p = new Parameters(makeAddr("gov"), address(this));
        ImdDepth a = new ImdDepth(address(p));
        ImdDepth b = new ImdDepth(address(p));
        p.setGenesisImdDepth(address(a), new address[](0));
        // Expected: a second wiring is refused (BadConfig), as setGenesisBackstops refuses a second call.
        vm.expectRevert();
        p.setGenesisImdDepth(address(b), new address[](0));
    }
}
```

### 4. Low: Deploy resume keeps a ProvenPoolPrice recorded at a LIVE_POOL node: _feedIs's LIVE_POOL branch cannot tell the two feed kinds apart

`script/deploy/DeployBase.sol:178`

```
        if (n.kind == DeployTypes.LIVE_POOL) {
            return address(LivePoolPrice(f).manager()) == n.source && PoolId.unwrap(LivePoolPrice(f).poolId()) == n.poolId
                && LivePoolPrice(f).baseIsToken0() == n.passOneE18;
```

From the math specialist; reproduced here through a StageFeeds harness. StageFeeds keeps a recorded feed when _feedIs says it is the config's node. The LIVE_POOL branch reads manager(), poolId() and baseIsToken0(); the new PROVEN_POOL kind (ProvenPoolPrice, wave 3) exposes the same three getters with the same values for the same pool (BetaConfig: F_IMD_LIVE node 17 and F_IMD_PROVEN node 23 are both pool 0xb07d on the v4 PoolManager with base = token1). So a resumed stage 2 whose record holds a ProvenPoolPrice at a LIVE_POOL node's index (a record misaligned with the config: a node inserted, or the record edited between a stopped run and its resume) adopts it silently instead of stopping with Mismatch("feed"), against the wave-1 rule that a resume compares every kept piece with the config. F_IMD_LIVE is the base of F_IMD_USD_LIVE and of sIMD's liveSpot leg (F_SIMD_LIVE), so the sIMD redemption payout and the two-leg agree check (README invariant 2) would follow a price proven up to 6 hours earlier instead of the pool's price now, until it reads stale. The reverse direction fails closed (a LivePoolPrice at a PROVEN_POOL node is refused: control test passes). Operator-error path, deployer-only, pre-seal: no funds; low. Smallest fix: in the LIVE_POOL branch also require that f has no provenBlock()/maxAge() answer matching ProvenPoolPrice (a staticcall to provenBlock() must fail), or record each feed's kind in the Deployed record and compare it.

**Reproduction**

cfg.feeds = [ {kind: LIVE_POOL, source: M (a contract answering extsload), poolId: P, passOneE18: false} ]; d.feeds = [ ProvenPoolPrice(M, P, false, 6 hours) ]; run _stageFeeds(cfg, d). Expected: Mismatch("feed") or a new LivePoolPrice at d.feeds[0]. Actual: d.feeds[0] stays the ProvenPoolPrice. Run on c64ecee: forge test --match-path 'test/scratch/ProofResumeAdoptsProvenAsLive.t.sol' -> [FAIL: a ProvenPoolPrice must not be kept as a LIVE_POOL node] test_provenPoolPriceRecordedAtALivePoolNodeIsNotKept() (gas: 22206455); [PASS] test_control_livePoolPriceAtAProvenNodeIsRefused().

**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 {StageFeeds} from "script/deploy/StageFeeds.sol";
import {ProvenPoolPrice} from "src/feeds/ProvenPoolPrice.sol";
import {LivePoolPrice} from "src/feeds/LivePoolPrice.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";

contract PaCode {
    function extsload(bytes32) external pure returns (bytes32) {
        return bytes32(uint256(1 << 96));
    }
}

/// Stage 2 exactly as the launch runs it, on a deployment record `d`.
contract PaStage is StageFeeds {
    function feedsStep(DeployTypes.Config memory cfg, Deployed memory d) external returns (Deployed memory) {
        _stageFeeds(cfg, d);
        return d;
    }
}

/// DeployBase._feedIs's LIVE_POOL branch reads manager(), poolId() and baseIsToken0(): a ProvenPoolPrice (wave 3's
/// PROVEN_POOL kind) answers all three with the same values for the same pool, so a resumed stage 2 whose record holds a
/// ProvenPoolPrice at a LIVE_POOL node's index keeps it instead of stopping with Mismatch("feed").
contract ProofResumeAdoptsProvenAsLiveTest is Test {
    bytes32 constant POOL = keccak256("pool");

    function test_provenPoolPriceRecordedAtALivePoolNodeIsNotKept() public {
        PaStage h = new PaStage();
        address manager = address(new PaCode());
        DeployTypes.Config memory cfg;
        cfg.feeds = new DeployTypes.FeedNode[](1);
        cfg.feeds[0].kind = DeployTypes.LIVE_POOL;
        cfg.feeds[0].source = manager;
        cfg.feeds[0].poolId = POOL;
        cfg.feeds[0].passOneE18 = false; // base is token1, as BetaConfig's F_IMD_LIVE

        PaStage.Deployed memory d;
        d.feeds = new IFeed[](1);
        d.feeds[0] = IFeed(address(new ProvenPoolPrice(manager, POOL, false, 6 hours)));

        // Expected: the kept piece is compared with the config and the run stops (Mismatch) or a LivePoolPrice is built.
        // Actual: the ProvenPoolPrice is kept as the LIVE_POOL node.
        PaStage.Deployed memory out = h.feedsStep(cfg, d);
        assertTrue(address(out.feeds[0]) != address(d.feeds[0]), "a ProvenPoolPrice must not be kept as a LIVE_POOL node");
    }

    function test_control_livePoolPriceAtAProvenNodeIsRefused() public {
        PaStage h = new PaStage();
        address manager = address(new PaCode());
        DeployTypes.Config memory cfg;
        cfg.feeds = new DeployTypes.FeedNode[](1);
        cfg.feeds[0].kind = DeployTypes.PROVEN_POOL;
        cfg.feeds[0].source = manager;
        cfg.feeds[0].poolId = POOL;
        cfg.feeds[0].maxAge = 6 hours;
        PaStage.Deployed memory d;
        d.feeds = new IFeed[](1);
        d.feeds[0] = IFeed(address(new LivePoolPrice(IPoolManager(manager), POOL, false)));
        vm.expectRevert();
        h.feedsStep(cfg, d);
    }
}
```

### 5. Info: ParametersRules is 165 bytes under EIP-170 and carries GovernedByKind's whole governance surface, while Parameters' init code embeds its creation code (762 bytes under EIP-3860): no room for the dry-r

`src/ParametersRules.sol:13`

```
contract ParametersRules is ParametersBase {
```

From the flow specialist; verified from the artifacts of this commit's build (solc 0.8.26, via_ir, runs 200). ParametersRules runtime 24,411 bytes (margin 165), 108 external selectors of which only validateKind/applyKind are ever reached (delegatecall-only module), the rest being GovernedByKind's propose/cancel/applyPending/pending/locked and ParametersBase's getters and constants; it also receives the real governor, who can propose on the Rules contract's own storage (harmless: nothing reads it). Parameters runtime 23,156 (margin 1,420) and init code 48,390 (margin 762) because its constructor does `rules = new ParametersRules(governor_)` (src/Parameters.sol:24), so the two limits are coupled: any growth of the Rules runtime shrinks Parameters' init margin one for one. Ledger (runtime margin 1,778; init 44,886, margin 4,266, embedding LedgerSettlement the same way) and Allocator (margin 1,767) are the next tightest. Not a defect in behaviour; recorded because the two low findings above need code in checkBatch/dryRun and in ParametersRules' BATCH branch. Suggested change: deploy ParametersRules (and LedgerSettlement) separately in the deploy script and pass the address to the constructor (DeployBase checks extcodehash and the immutable self/governor as it does for every kept piece), which removes about 24.6 KB from Parameters' init code; and keep GovernedByKind out of the Rules module by splitting ParametersBase into a storage/constants base (no public getters) that both inherit and a governed layer only Parameters inherits.

**Reproduction**

After forge build on c64ecee: out/ParametersRules.sol/ParametersRules.json deployedBytecode 24,411 bytes, 108 methodIdentifiers including propose(bytes), cancel(uint8), applyPending(uint8), pendingOf(uint8), locked(); out/Parameters.sol/Parameters.json bytecode 48,390 bytes (49,152 - 48,390 = 762), out/Ledger.sol/Ledger.json deployedBytecode 22,798 / bytecode 44,886, out/Allocator.sol/Allocator.json deployedBytecode 22,809. Expected for a delegatecall-only module: two selectors and a runtime margin that does not bound Parameters' init code.

---

Judge's submission `b7e6550fa9b91e2895f7f60212f08800c5e6379becb5a2d2cc9927bc797515fb`, 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.
