# Audit report

> AUDIT price design C: src/feeds/SwarmFeed.sol (+ leaves in SwarmFeeds.sol), src/feeds/FeedTraits.sol and the composites (ProductFeed, RateFeed, SeatFeed), src/Pricer.sol, src/feeds/ProvenPoolPrice.sol, and the sIMD feed graph in script/DeployConfig.sol, at the pinned commit.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum (Robinhood Chain 4663 follows). README.md gives scope, invariants, trust model and known issues: read it first. Earlier public waves: GET https://api.imd.fun/jobs/<id>/submissions (wave 1 bd0ce553 oracles, wave 2 5a8d427d prices, wave 3 ff9ebb9d prices).
>
> BUILD AND TEST (required; Foundry, solc 0.8.26 via_ir). Never build the whole project with solc (~49 GB). Run `forge test --match-path 'test/unit/{SwarmFeed,SwarmFeedProperties,PricerTwin,ProvenPoolPrice,AuditW3WayBack}.t.sol'`; with Foundry 1.9+ `forge test --use solar --no-match-path 'test/fork/*'` builds and runs everything 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.
>
> PROPERTIES:
> P1 Within an epoch the stored value stays within the cap of the epoch's anchor; after a silence the first delivery may move it up to 2x the cap and the epoch re-anchors there at the cap, so that epoch moves at most (1+2c)(1+c)-1 (+68%/-52% at c=20%), and two epochs straddling a boundary at most (1+a)^2-1 within one maxAge.
> P2 Once honest attestations persist, the stored value reaches the honest level within ceil(ln(ratio)/ln(1+cap)) epochs whatever was relayed before; no valid attestation is refused for its value.
> P3 Nothing is refused, and no band is set, by any level but the live epoch's anchor (the stored value when it opened): the feed keeps no memory of earlier levels.
> P4 For sIMD, while the proven spot is fresh (proved within 6 h), the price health and liquidation use is never more than skew (5%) below it: a wrong or compromised median alone cannot liquidate a loan more than skew from mat.
> P5 A genuine fall is followed at least at the allowance per epoch by the median and at once by a proof of a newer block, which anyone can provide in the same bundle.
> P6 No new debt at a value nobody attested: a leg held short of its last attestation, through any composite, makes its type not agree.
> P7 In a real fall faster than the allowance (cap 20% per 1 h epoch, mat 1.7-2.0, chop 20%), the debt that goes bad while low = max(median, spot) follows the slower leg is bounded, and the bound is stated.
>
> THREAT MODEL: a compromised attester key controls any signed value and panel figures (a wrong majority counts as one); a pool pusher controls pool 0xb07d at chosen block ends, at fee and arbitrage cost; a block builder controls ordering and inclusion within a block and across consecutive blocks; a relayer controls which valid attestations land and when (relay is permissionless); a prover controls which of the last 256 blocks is proved. Builder and prover are defended against; a pusher or relayer landing honestly attested pushed reads last in an epoch is bounded to one allowance per epoch while it lasts (C1); Chainlink ETH/USD and the sIMD share rate are trusted and common to both sIMD legs, outside the twin; the Safe may add a type with any feeds (ADD_ILK). An attester compromise is bounded by P1 and, for a median pushed down, P4; a median held above a falling spot keeps under-water loans alive (low = max), and a pushed NHI raises mat; the response is the governor's instant lowerLine(ilk, 0) (README).
>
> PATH: SwarmFeed leaves -> ProductFeed / RateFeed (FeedTraits: converged, proven) -> Pricer.quote (agree, low/high, twin rule) -> Ledger health and borrow, Liquidator mark/bite (q.low, priced), Redeemer payout. sIMD's spot = ProvenPoolPrice x ETH/USD x share rate. The twin needs a fresh proof: with the spot stale (> 6 h) low is the median alone. The keeper (github.com/fa11up/imdusd-v2-keeper-audit) re-proves on 1.5% drift, near 6 h, and as soon as the Pricer reports the legs apart; it buys a median only on a fall with a loan at risk. Deploy numbers: cap 2,000 bps, maxAge 1 h, PROVEN_MAX_AGE 6 h, skew 5%, chop 20% (script/DeployConfig.sol); sIMD's mat is NHI's (Pricer._mat: 1.7 at NHI >= 0.85 to 2.0 at <= 0.6), a swarm leaf outside the twin: a clamped NHI stops borrowing, not liquidation.
>
> CLAIMS TO CHECK: confirm or refute each with a test.
> C1 an attack lasting k epochs takes about k epochs to undo, and the last relayer of an epoch moves a leg one allowance per epoch while it lasts, no more;
> C2 the wide band after a silence is one step;
> C3 the twin rule keeps an under-water loan alive only until both legs have caught up (a proof, and a median bought after the fall);
> C4 a FeedTraits read that runs out of gas reverts rather than reporting converged or proven;
> C5 ProductFeed.proven() (proven(a) || proven(b)) is true only when no attester is in its path; DeployBase._feedIs checks only the input addresses;
> C6 the twin rule applies whenever the pair does not agree, including within skew while one leg is clamped.
>
> SOUNDNESS: three public waves broke SwarmFeed's old way back (a feed cannot tell a pushed move from an honest one by its own history); design C clamps instead and adds a twin. Can it hold P1-P7 at all under the whole threat model? Can a proven leg bound liquidation when it can be stale, or when the median is clamped above the market? If not, name the smallest change, or the property that must be given up.
>
> PROOF STANDARD: fuzz or invariant tests over interleavings of honest and attacker attestations, epoch boundaries, silences, many deliveries in one block, consecutive blocks and proofs of chosen blocks. test/unit/SwarmFeedProperties.t.sol is the harness to extend.
>
> Answer each numbered question:
> 1. (P1, P3) Attack the epoch rule: boundary timing, silences, bursts in one block, the one-step wide band. Find any sequence that moves a stored value further than P1 allows.
> 2. (P2) Find a sequence, honest attestations persisting afterwards, in which the honest level is not reached within the bound, or a valid attestation is refused.
> 3. (P4, P5, P7) Attack the twin rule: a stale proof, a pushed block proved at a block end, a spot pushed down within skew, legs from different moments, a compromised median held above a falling spot, a compromised NHI raising mat toward 2.0. How long can each hold, at what cost, and who can end it? In a real one-block fall of 30-60%, how much sIMD debt goes bad before low reaches the market?
> 4. (P6, P4) FeedTraits through the composites and the deploy graph check (DeployBase._feedIs, _provenAtDeploy; the launch stage-2 check, not in this snapshot, only requires FeedTraits.proven(feed) == _provenAtDeploy): can a composite report converged or proven wrongly, or can a deploy, a resume or a later ADD_ILK give the twin rule to a spot with an attester in its path?
> 5. (P1, P5) Measure gas per accepted attestation and per prove against the README's figures; is any path priced out of a block or costlier than the version it replaced?
>
> Not findings: README 'Known issues' as written (a known issue worse than written IS a finding); test/ and mocks; src/dex and src/earn/LoopVault.sol.
>
> Every finding: severity by impact; file, line and the lines copied; the call sequence; the failing state, expected vs actual; reachable with the deploy config or not; the smallest fix; and a test that fails on this commit, RUN as BUILD says and pasted with its output (the judge reruns it). Answer every numbered question, including where nothing is wrong.

| | |
|---|---|
| Repository | https://github.com/fa11up/imdusd-v2-audit.git |
| Commit | `67eadeac1e67db5f562e03eab8432a435debfb79` |
| Job | `0cb1541e-5d63-4866-815a-425703d326e1` |
| Judged | 2026-11-15 06:08 UTC |
| Findings | 2 medium · 4 low |

Four agents audited the code as it is at `67eadea`, 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. Medium: Twin rule: after a genuine fall and an instant proof, low = max(median, spot) follows the CLAMPED median for k epochs; README 'waits for a proof' is worse than written (C3 refuted, P7 bound stated)

`src/Pricer.sol:93`

```
            q.low = q.high = Math.max(m, s); // the twin rule: neither leg alone can set the liquidation price below the other
```

With the legs apart and the proven spot fresh, the Pricer sets low = high = max(median, spot). After a GENUINE fall the proven spot is updated at once (anyone proves a newer block), but the swarm median leaf descends at most one allowance (20%) per 1 h epoch (SwarmFeed._follow), so low is the clamped median, above the market, until the median has walked down: ceil(ln(S/H)/ln(1.25)) epochs. The proof cannot speed this. Measured on the sIMD-shaped graph (median = ProductFeed(clamp leaf, ETH/USD), spot = ProductFeed(proven, ETH/USD), cap 2,000 bps, maxAge 1 h, skew 5%, chop 20%): a one-block fall of 60% proved at once with honest medians once per epoch gives low/market = 2.00, 1.60, 1.28, 1.024, 1.00; low stays above 1.2 x market (a liquidator repaying D receives D(1+chop)/low of collateral worth less than D: no rational liquidation) for 3 epochs and above the market for 4. A 45% fall: 1 epoch above chop; a 30% fall: liquidatable after the first honest median. README 'Known issues' (Liquidation after a real fall waits for a proof) says the loan is kept healthy 'until then' (a newer block is proved); it is kept healthy until the MEDIAN catches up, so the known issue is worse than written and claim C3 is k median purchases over k-1 hours, not 'a proof and a median bought after the fall'. Any relayer may add up to ~2 h: an honest 1,200-block window median still reads the pre-fall level for ~2 h after a one-block fall and may be landed last in the epoch. While this lasts agree = false (no borrowing or withdrawal), so the exposure is bad debt in a continuing fall and the forgone chop, not extraction. P7 bound: for sIMD debt D at average CR c after a total fall f by the time low <= 1.2 x market, bad debt <= D x max(0, 1 - c(1-f)); at the 24,333 line, c = 1.7, f = 60%: ~7.8k imdUSD (32% of debt at mat); each further 20% fall during the 2-4 h lag adds D x c x 0.2 x (1 - f_before). The proven leg therefore cannot bound liquidation DELAY: with low = max it can only stop a wrong median from liquidating (P4), never make a lagging one liquidate. Reachable with the deploy config, no attacker needed. Smallest fix that keeps P4: carry the median's last attested target through the composites (an attested() trait next to converged()) and in the twin branch use low = max(s, min(m, attestedMedian)): a fall both legs attest is followed at once, while a pushed-down attestation still cannot lower low below the proven spot. Otherwise restate the known issue as 'until the median has walked down (k epochs)'.

**Reproduction**

State: sIMD median leaf stored 4e15 (converged), proven spot 4e15, ETH/USD 2000. Market falls 60% in one block to 1.6e15; prove() lands at once (spot = 3.2e18 USD); honest medians of 1.6e15 relayed once per epoch. Expected (C3 / README as written): low at the market after the proof and one median. Actual: low = 6.4e18, 5.12e18, 4.096e18, 3.2768e18, 3.2e18 over five epochs (2.0x, 1.6x, 1.28x, 1.024x, 1.0x the market); above 1.2x market for 3 epochs, above market for 4. Run: forge test --match-path 'test/scratch/ProofTwinLag.t.sol' -vv -> [FAIL: C3 as read: one proof and one median after the fall end the shelter: 4 > 1] test_F5_afterAGenuineFallLowFollowsTheMedianForKEpochs() (gas: 6198378); Logs: epoch 1 q.low / market (1e4): 20000; epoch 2: 16000; epoch 3: 12800; epoch 4: 10240; epoch 5: 10000; epochs with low > 1.2 x market: 3; epochs with low > market: 4.

**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 {Test} from "forge-std/Test.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {SwarmFeed} from "src/feeds/SwarmFeed.sol";
import {SwarmPricePolicy, SwarmNhiPolicy} from "src/feeds/SwarmFeeds.sol";
import {ProductFeed} from "src/feeds/ProductFeed.sol";
import {RateFeed} from "src/feeds/RateFeed.sol";
import {FeedTraits} from "src/feeds/FeedTraits.sol";
import {Pricer} from "src/Pricer.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";

/// @dev Production clamp leaf (PRICE question, 1 h, 2,000 bps) with a test door to `_accept` (as test/unit/PricerTwin.t.sol).
contract DoorLeaf is SwarmPricePolicy {
    constructor() SwarmFeed(address(1), address(0), 1, 3, 1 hours, 2000) {}

    function set(uint256 target) external {
        _accept(target, uint64(block.timestamp));
    }
}

/// @dev Production NHI leaf (1 day, 2,000 bps: DeployConfig NHI_MAX_AGE / SWARM_CAP_BPS) with the same door.
contract DoorNhi is SwarmNhiPolicy {
    constructor() SwarmFeed(address(1), address(0), 1, 3, 1 days, 2000) {}

    function set(uint256 target) external {
        _accept(target, uint64(block.timestamp));
    }
}

contract MockFeed is IFeed {
    uint256 public v;

    constructor(uint256 v_) {
        v = v_;
    }

    function set(uint256 v_) external {
        v = v_;
    }

    function latestValue() external view returns (uint256, uint64) {
        return (v, uint64(block.timestamp));
    }

    function isStale() external pure returns (bool) {
        return false;
    }

    function maxAge() external pure returns (uint256) {
        return 6 hours;
    }
}

/// @dev Stands in for ProvenPoolPrice's value with the trait ProvenPoolPrice reports.
contract MockProven is MockFeed {
    constructor(uint256 v_) MockFeed(v_) {}

    function proven() external pure returns (bool) {
        return true;
    }
}

contract MockVault {
    function convertToAssets(uint256 s) external pure returns (uint256) {
        return s;
    }
}

/// @dev The Pricer's four reads of Parameters, nothing else.
contract MockParams {
    ParametersBase.Config internal cfg;
    ParametersBase.Risk internal rsk;

    function setConfig(ParametersBase.Config memory c) external {
        cfg = c;
    }

    function setRisk(ParametersBase.Risk memory r) external {
        rsk = r;
    }

    function config(bytes32) external view returns (ParametersBase.Config memory) {
        return cfg;
    }

    function storedRisk(bytes32) external view returns (ParametersBase.Risk memory) {
        return rsk;
    }

    function maxLull() external pure returns (uint256) {
        return 0;
    }

    function cap(bytes32) external pure returns (uint256) {
        return 0;
    }
}

/// @dev Stands where the Pricer stands: a top-level FeedTraits reader.
contract Reader {
    function converged(IFeed f) external view returns (bool) {
        return FeedTraits.converged(f);
    }
}

contract ProofF5 is Test {
    function setUp() public {
        vm.chainId(1);
        vm.warp(1_800_000_000);
        vm.roll(26_000_000);
    }

    function _pricer(IFeed median, IFeed spot, IFeed nhi, uint64 skew) internal returns (Pricer p) {
        MockParams mp = new MockParams();
        ParametersBase.Config memory c;
        c.token = address(0xC0FFEE);
        c.median = median;
        c.spot = spot;
        c.nhi = nhi;
        ParametersBase.Risk memory r;
        r.mat = 1.7e18;
        r.chop = 0.2e18;
        r.skew = skew;
        mp.setConfig(c);
        mp.setRisk(r);
        p = new Pricer(Parameters(address(mp)));
    }

    // -----------------------------------------------------------------------------------------------------------------
    // F5 (C3 / P7 quantified). sIMD graph: median = ProductFeed(clamp leaf, ETH), spot = ProductFeed(proven, ETH). A genuine
    // one-block fall of 60% is proved at once; honest medians land once per epoch. With low = max(median, spot) the
    // liquidation price stays ABOVE 1.2x the market (chop: no rational liquidation) for 3 further epochs and above the
    // market for 4 (0.8^5 = 0.328 < 0.4), whatever the proof says. C3's "a median bought after the fall" is k purchases over
    // k-1 hours. The assertion states the claim as C3 reads it (one median after the proof); it fails by the lag.
    function test_F5_afterAGenuineFallLowFollowsTheMedianForKEpochs() public {
        DoorLeaf leaf = new DoorLeaf();
        MockFeed eth = new MockFeed(2000e18);
        MockProven proven = new MockProven(4e15);
        leaf.set(4e15);
        ProductFeed median = new ProductFeed(leaf, eth);
        ProductFeed spot = new ProductFeed(proven, eth);
        Pricer p = _pricer(median, spot, IFeed(address(0)), 0.05e18);
        uint256 market = 4e15 * 40 / 100; // -60% in one block
        proven.set(market); // proved at once (anyone can)
        vm.warp(vm.getBlockTimestamp() + 1 hours);
        uint256 epochsAboveChop;
        uint256 epochsAboveMarket;
        for (uint256 i; i < 8; ++i) {
            leaf.set(market); // the honest median of the fallen market, once per epoch
            Pricer.Quote memory q = p.quote("SIMD");
            uint256 mkt = market * 2000e18 / 1e18;
            emit log_named_uint("epoch", i + 1);
            (uint256 lv,) = leaf.latestValue();
            (uint256 an, uint64 op, uint256 bp) = leaf.epoch();
            emit log_named_uint("  leaf stored", lv);
            emit log_named_uint("  leaf anchor", an);
            emit log_named_uint("  leaf openedAt", op);
            emit log_named_uint("  leaf bps", bp);
            emit log_named_uint("  now", vm.getBlockTimestamp());
            emit log_named_uint("  q.low", q.low);
            emit log_named_uint("  q.low / market (1e4)", q.low * 1e4 / mkt);
            if (q.low * 10 > mkt * 12) ++epochsAboveChop;
            if (q.low > mkt) ++epochsAboveMarket;
            else break;
            vm.warp(vm.getBlockTimestamp() + 1 hours);
        }
        emit log_named_uint("epochs with low > 1.2 x market (no rational liquidation)", epochsAboveChop);
        emit log_named_uint("epochs with low > market", epochsAboveMarket);
        assertLe(epochsAboveMarket, 1, "C3 as read: one proof and one median after the fall end the shelter");
    }
}
```

### 2. Medium: NHI leaf (same attester key, outside the twin) sets liquidation mat from an UNCONVERGED stored value: one attestation after a 25 h NHI silence moves mat 1.7 -> 2.0 (3.5x skew); lowerLine(ilk, 0) does

`src/Pricer.sol:77`

```
            q.mat = _mat(nhi);
```

P4 is stated for 'a wrong or compromised median alone', but the threat-model actor is a compromised attester KEY, and the same key signs the NHI leaf, which sits outside the twin rule. q.mat = _mat(nhi) reads the NHI leaf's STORED value whether or not it is converged (a clamped NHI only clears borrowable, line 101), and the Pricer applies it to liquidation health. NHI_MAX_AGE is 1 day and SWARM_CAP_BPS 2,000 (script/DeployConfig.sol): if the daily refresh is an hour late (silence >= maxAge + STALE_GROWTH_PERIOD), the next attestation carries the 2x allowance, so ONE signed value (1 wei) moves the stored NHI 0.98 -> 0.588 <= 0.6 and mat 1.7 -> 2.0 (+17.6%, equivalent to a 15% price cut, 3.5x the 5% skew P4 allows) while both price legs are honest, fresh and agree; priced stays true, lull drops to 0, and every sIMD loan with CR < 2.0 is liquidatable at once at chop 20%. Without a silence one attestation gives 0.784 (mat 1.7792, within skew) and a second day 1.968. The README's stated instant response, lowerLine(ilk, 0), stops new debt only; liquidations continue, and the honest NHI walks back at one allowance per DAY (0.588 -> 0.7056 -> 0.847: 2 days to mat 1.7). Who can end it: nobody within a day; the Safe only by re-pointing the NHI feed (48 h). README 'NHI has no market check ... bounded by its feed's per-epoch cap and lifetime' is true in words; the consequence not written is that one late refresh lets the cap cover the whole 1.7 -> 2.0 range in one step, and that the raise is applied at a value nobody attested (the clamp result) although the Pricer's convergence rule exists to stop actions at such a value. Smallest fix: for liquidation, do not let a non-converged NHI raise mat above what its epoch anchor gives (q.mat = _mat(FeedTraits.converged(c.nhi) ? nhi : max(nhi, anchor)) via SwarmFeed.epoch(); or simply keep q.mat = r.mat while the NHI is not converged, as the convergence rule already does for borrowing), so a converged push still takes k epochs; and/or give the NHI leaf a smaller cap (500 bps = mat +1.2%/step). Reachable with the deploy config (NHI_MAX_AGE 1 day, SWARM_CAP_BPS 2,000); needs the attester key or a wrong majority and a one-hour-late daily refresh. Merges the audit_flow and audit_economics NHI findings and the NHI consequence of the audit_permissions P1 finding.

**Reproduction**

State: production NHI leaf (SwarmNhiPolicy, 1 day, 2,000 bps) stored 0.98e18 (mat 1.7); median and spot honest, equal, agree. Warp 1 day + 1 h + 1 s; one attestation of value 1 lands. Expected (P4 for the compromised key): liquidation mat moves at most skew (q.mat <= 1.785e18), or an unconverged NHI does not set liquidation mat. Actual: stored NHI 0.588e18 (converged() false), q.mat 2.0e18, q.priced true, q.agree true, q.borrowable false. Run: forge test --match-path 'test/scratch/ProofNhiMat.t.sol' -vv -> [FAIL: liquidation mat moved more than skew (5%) on one unconverged NHI attestation: 2000000000000000000 > 1785000000000000000] test_oneNhiAttestationAfterSilenceSetsMat2(); Logs: stored NHI: 588000000000000000, q.mat: 2000000000000000000. Control (no silence, warp 1 day): q.mat 1779200000000000000.

**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 {Test} from "forge-std/Test.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {SwarmFeed} from "src/feeds/SwarmFeed.sol";
import {SwarmNhiPolicy} from "src/feeds/SwarmFeeds.sol";
import {Pricer} from "src/Pricer.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";

contract DoorNhi is SwarmNhiPolicy {
    constructor() SwarmFeed(address(1), address(0), 1, 3, 1 days, 2000) {}
    function set(uint256 t) external { _accept(t, uint64(block.timestamp)); }
}

contract MockFeed is IFeed {
    uint256 public v;
    constructor(uint256 v_) { v = v_; }
    function latestValue() external view returns (uint256, uint64) { return (v, uint64(block.timestamp)); }
    function isStale() external pure returns (bool) { return false; }
    function maxAge() external pure returns (uint256) { return 6 hours; }
}

contract MockParams {
    ParametersBase.Config internal cfg;
    ParametersBase.Risk internal rsk;
    function setConfig(ParametersBase.Config memory c) external { cfg = c; }
    function setRisk(ParametersBase.Risk memory r) external { rsk = r; }
    function config(bytes32) external view returns (ParametersBase.Config memory) { return cfg; }
    function storedRisk(bytes32) external view returns (ParametersBase.Risk memory) { return rsk; }
    function maxLull() external pure returns (uint256) { return 0; }
    function cap(bytes32) external pure returns (uint256) { return 0; }
}

/// One signed NHI value after a 25 h NHI silence (deploy: NHI_MAX_AGE 1 day, cap 2,000 bps) is clamped to 0.98 x 0.6 = 0.588
/// <= 0.6, so q.mat = 2.0 at once while both price legs are honest and agree; the NHI is NOT converged, yet liquidation
/// uses the raised mat (only borrowing reads converged). Without a silence: 0.784 -> mat 1.779.
contract ProofNhiMat is Test {
    function setUp() public { vm.chainId(1); vm.warp(1_800_000_000); vm.roll(26_000_000); }

    function _pricer(IFeed nhi) internal returns (Pricer p) {
        MockFeed m = new MockFeed(100e18);
        MockParams mp = new MockParams();
        ParametersBase.Config memory c;
        c.token = address(0xC0FFEE); c.median = IFeed(address(m)); c.spot = IFeed(address(m)); c.nhi = nhi;
        ParametersBase.Risk memory rk; rk.mat = 1.7e18; rk.chop = 0.2e18; rk.skew = 0.05e18;
        mp.setConfig(c); mp.setRisk(rk);
        p = new Pricer(Parameters(address(mp)));
    }

    function test_oneNhiAttestationAfterSilenceSetsMat2() public {
        DoorNhi nhi = new DoorNhi();
        nhi.set(0.98e18);
        Pricer p = _pricer(IFeed(address(nhi)));
        assertEq(p.quote("SIMD").mat, 1.7e18);
        vm.warp(block.timestamp + 1 days + 1 hours + 1); // the daily refresh an hour late
        nhi.set(1); // one signed value
        (uint256 stored,) = nhi.latestValue();
        emit log_named_uint("stored NHI", stored);
        Pricer.Quote memory q = p.quote("SIMD");
        emit log_named_uint("q.mat", q.mat);
        assertFalse(nhi.converged(), "the NHI is clamped: a value nobody attested");
        assertTrue(q.priced); assertTrue(q.agree); assertFalse(q.borrowable);
        assertLe(q.mat, 1.785e18, "liquidation mat moved more than skew (5%) on one unconverged NHI attestation");
    }
}
```

### 3. Low: P1 sliding-window bound understated: after a silence three deliveries inside one closed maxAge move the stored value (1+2c)(1+c)^2 - 1 = +101.6% / -61.6% at c = 20%, above the documented (1 + allowanc

`src/feeds/SwarmFeed.sol:628`

```
                uint256 first = _clamp(target, anchor, bound);
                (_anchorValue, _attested, _anchorAt, _anchorBound) =
                    (uint128(first), uint128(target), uint40(block.timestamp), uint24(maxDeviationBps));
                return first;
```

The wide band is one step (C2 confirmed), but the wide branch of _follow re-anchors the epoch at the wide step's RESULT `first` with the cap and sets _anchorAt = now. The wide epoch can then move a further cap from `first`, and because the epoch ends at exactly maxAge (`block.timestamp - _anchorAt >= maxAge`, line 620) the next epoch opens at T + maxAge anchored at that far edge and adds one more cap at once. Three deliveries at T, T + maxAge - 1 and T + maxAge, all inside one closed maxAge, move the stored value by (1+2c)(1+c)^2 = 2.016x upward or (1-2c)(1-c)^2 = 0.384x downward at the deploy cap (2,000 bps, maxAge 1 h). The per-epoch statements hold (the wide epoch moves at most (1+2c)(1+c)-1 = +68%/-52%, every other epoch c; the harness's fuzz and invariant runs pass), so this is a defect of the stated bound, not of the rule: the header's 'over a sliding maxAge it can reach (1 + allowance)^2 - 1 once' (1.96x at a = 2c, 1.44x at a = c), the task's P1 'two epochs straddling a boundary at most (1+a)^2-1 within one maxAge', and the README known issue are each exceeded within one maxAge. Reachable with the deploy config by a compromised attester or a wrong majority after any 2 h relay silence (the keeper buys a median only on a fall, so silences are routine). Impact on sIMD: a median pushed to 2x in one hour sets low = high = max(median, spot) = 2x, keeping under-water loans alive and halving the redemption payout, where the stated bound gives 1.96x; on NHI the one-step case is the separate finding above. Smallest fix: either restate P1 and the known issue as (1+2c)(1+c)^2 - 1 over a closed maxAge after a silence ((1+c)^2 - 1 otherwise), or keep the wide epoch anchored at the pre-silence stored value with the 2x allowance for its whole life (bound = 2c around `anchor`, not cap around `first`), which gives 1.4x per wide epoch and 1.68x straddling, or open the epoch after a wide one only maxAge after the wide epoch's LAST delivery (_acceptedAt is already kept). Merges three specialists' reports of the same sequence.

**Reproduction**

Production price leaf (SwarmPricePolicy, cap 2000 bps, maxAge 1 h) stored 1e18. Warp 2 h + 1 s (silence). At T deliver target 100e18 (or 1): stored 1.4e18 (0.6e18). At T + 3599 s deliver again: 1.68e18 (0.48e18). At T + 3600 s deliver again: a new epoch opens at the stored value with the cap, stored = 2.016e18 (0.384e18). Expected under the documented bound: at most 1.96e18 (no lower than 0.36e18 by (1-2c)^2; the per-epoch statement gives 1.68e18 / 0.48e18) within one maxAge. Actual: 2.016e18 / 0.384e18 with all three deliveries inside [T, T + maxAge]. Run: forge test --match-path 'test/scratch/ProofP1Wide.t.sol' -vv -> [FAIL: moved further than (1+2c)(1+c) within one maxAge: 2016000000000000000 > 1680000000000000000] test_upWithinOneMaxAgeExceedsStatedBound(); [FAIL: moved further than (1-2c)(1-c) within one maxAge: 384000000000000000 < 480000000000000000] test_downWithinOneMaxAgeExceedsStatedBound().

### 4. Low: C4 refuted through composites: FeedTraits' out-of-gas guard holds only for a leaf read directly; a ProductFeed/RateFeed over a leaf whose trait read ran out of gas (or reverted at all) is read as 'con

`src/feeds/FeedTraits.sol:40`

```
        if (gasleft() < g / 63) revert TraitUnreadable(f);
```

_flag tells 'function absent' from 'ran out of gas' by how much gas is left after the failed staticcall: an OOG callee leaves ~1/64 of g, so the 1/63 threshold catches a DIRECT leaf (PricerTwin's GasBurner test). But every composite's converged()/proven() is itself a FeedTraits reader. When the LEAF's read runs out of gas, the composite's _flag correctly reverts TraitUnreadable with ~1/64 of ITS gas unspent and hands that back, so the reader above (RateFeed's FeedTraits, or the Pricer's at line 89) sees a failed call with ~2/64 of its gas left, passes the g/63 test and answers the default: converged = true (proven() = false). Any leaf revert WITH data (not only OOG) is likewise taken as 'absent'. The deployed sIMD legs are RateFeed(ProductFeed(leaf, ETH/USD)), so the Pricer always reads the only clampable leaf through two composites, and the guarantee stated in FeedTraits' header, the README and claim C4 ('a FeedTraits read that runs out of gas reverts rather than reporting converged') does not hold on the deploy graph. Impact is bounded, hence low: the leaf's converged() is a two-SLOAD read, so under-gassing it from the top starves the outer Ledger/Pricer frames first, and after the leaf ran out the transaction has only a few hundred gas left, so no state-changing path (borrow, bid) completes at the wrong answer; the wrong answer is observable in eth_call-shaped reads and is a latent fail-open for any future leaf whose trait read can revert (the Safe can ADD_ILK such a leaf). Smallest fix: in _flag, treat a failed call that returned revert DATA as unreadable and re-raise it (`if (!ok && data.length != 0) revert TraitUnreadable(f);` or bubble a TraitUnreadable selector), keeping the gas test for the empty-data (absent / OOG) case. Merges three specialists' reports.

**Reproduction**

BurnLeaf.converged() loops until out of gas; PlainFeed has no converged(). From an external reader (so EIP-150 applies, as in the Pricer): FeedTraits.converged(BurnLeaf) reverts TraitUnreadable (control, passes). FeedTraits.converged(ProductFeed(BurnLeaf, PlainFeed)): expected revert TraitUnreadable, actual returns true. RateFeed(rate, ProductFeed(BurnLeaf, PlainFeed)).converged() returns true directly, and FeedTraits.converged(RateFeed) returns true (the sIMD median's shape). Run: forge test --match-path 'test/scratch/ProofTraitNested.t.sol' -vv -> [PASS] test_directReadReverts(); [FAIL: composite over an unreadable leaf read as converged] test_productOfOutOfGasLeafReadsConverged(); [FAIL: RateFeed.converged() true over an unreadable product] test_rateOverProductReadsConverged().

**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 {Test} from "forge-std/Test.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {ProductFeed} from "src/feeds/ProductFeed.sol";
import {RateFeed} from "src/feeds/RateFeed.sol";
import {FeedTraits} from "src/feeds/FeedTraits.sol";

contract PlainFeed {
    function latestValue() external view returns (uint256, uint64) {
        return (1e18, uint64(block.timestamp));
    }

    function isStale() external pure returns (bool) {
        return false;
    }

    function maxAge() external pure returns (uint256) {
        return 1 hours;
    }
}

/// @dev A leaf whose converged() runs out of whatever gas it is given (the PricerTwin GasBurner).
contract BurnLeaf is PlainFeed {
    function converged() external pure returns (bool) {
        while (true) {}
        return true;
    }
}

contract Rate1 {
    function convertToAssets(uint256 x) external pure returns (uint256) {
        return x;
    }
}

contract Reader {
    function converged(IFeed f) external view returns (bool) {
        return FeedTraits.converged(f);
    }
}

/// C4: "a FeedTraits read that runs out of gas reverts rather than reporting converged". The composite's own FeedTraits
/// read reverts TraitUnreadable as designed, but the reader ABOVE the composite sees a failed call with plenty of gas left
/// (the composite returns its unused 1/64) and answers the default: converged.
contract ProofTraitMasked is Test {
    Reader r;
    BurnLeaf burn;
    PlainFeed plain;

    function setUp() public {
        r = new Reader();
        burn = new BurnLeaf();
        plain = new PlainFeed();
    }

    function test_directReadReverts() public {
        vm.expectRevert(abi.encodeWithSelector(FeedTraits.TraitUnreadable.selector, address(burn)));
        r.converged(IFeed(address(burn)));
    }

    function test_productOfOutOfGasLeafReadsConverged() public {
        ProductFeed p = new ProductFeed(IFeed(address(burn)), IFeed(address(plain)));
        // the composite itself fails closed
        vm.expectRevert();
        p.converged();
        // ...but read through FeedTraits, as the Pricer reads every leg, its revert is taken as "no trait" = converged
        bool c = r.converged(IFeed(address(p)));
        assertFalse(c, "composite over an unreadable leaf read as converged");
    }

    function test_rateOverProductReadsConverged() public {
        ProductFeed p = new ProductFeed(IFeed(address(burn)), IFeed(address(plain)));
        RateFeed rf = new RateFeed(address(new Rate1()), Rate1.convertToAssets.selector, true, IFeed(address(p)), 0);
        // RateFeed.converged() itself already answers true: its FeedTraits read took the product's revert as "absent"
        assertFalse(rf.converged(), "RateFeed.converged() true over an unreadable product");
        bool c = r.converged(IFeed(address(rf)));
        assertFalse(c, "sIMD-shaped Rate(Product(leaf, ETH)) over an unreadable leaf read as converged");
    }
}
```

### 5. Low: C5 refuted in code: ProductFeed.proven() is proven(a) \|\| proven(b), so a product of a proven pool price and a swarm leaf reports proven and gets the Pricer's twin rule with an attester in its path; on

`src/feeds/ProductFeed.sol:42`

```
        return FeedTraits.proven(a) || FeedTraits.proven(b);
```

The Pricer gives a type the twin rule (low = high = max(median, spot) while the legs disagree, src/Pricer.sol:92-93) whenever FeedTraits.proven(c.spot) is true. ProductFeed answers proven if EITHER input is proven and RateFeed forwards it, so ProductFeed(ProvenPoolPrice, SwarmLeaf), and anything built over it, is 'proven' although an attester controls one factor and can hold it clamped. With such a spot a compromised attester or last relayer pushing the swarm factor UP (one allowance per epoch, 2x after a silence) raises low = max(m, s) above the honest median and keeps under-water loans alive through the SPOT leg, which design C meant to make attester-free; pushed down it is bounded by the median. Nothing on chain checks the other input: ParametersRules' ADD_ILK reads no trait; DeployBase._feedIs(PRODUCT) only compares a()/b() with the node table's addresses; _provenAtDeploy (script/deploy/DeployBase.sol:212) returns _provenAtDeploy(a) || _provenAtDeploy(b), the same OR, so the launch stage-2 check FeedTraits.proven(feed) == _provenAtDeploy passes trivially for a config node product(proven, swarm). Not reachable with script/DeployConfig.sol as written (F_IMD_USD_PROVEN = product(F_IMD_PROVEN, F_ETH), a Chainlink leg); reachable through a Safe ADD_ILK (48 h timelock, the Safe is trusted), a later config, or a resume adopting such a product. Defence in depth: the README's 'no attester in the path' is enforced by the script, not the contract. Smallest fix: a product is proven only when its OTHER input has no attester in its path, detectable on chain as the other input not answering converged() (every swarm leaf and composite over one does; Chainlink, LivePoolPrice and ProvenPoolPrice do not): proven = (proven(a) && !hasConverged(b)) || (proven(b) && !hasConverged(a)) with a FeedTraits.hasTrait helper; mirror it in _provenAtDeploy (a PRODUCT is proven only when its other leg is CHAINLINK or another proven node), or have ParametersRules refuse an ADD_ILK spot that reports proven() and also exposes converged(). Merges three specialists' reports.

**Reproduction**

DoorLeaf leaf (production SwarmPricePolicy, 1 h, 2000 bps) set(1e18) then set(10e18) in the same epoch -> stored 1.2e18, converged() false. ProductFeed p = new ProductFeed(MockProven{proven()=true, 100e18}, leaf); RateFeed r over p. Expected: FeedTraits.proven(p) == false (an attester is in the path; FeedTraits.converged(p) is false). Actual: FeedTraits.proven(p) == true and FeedTraits.proven(r) == true. Pricer with median 100e18 (plain), spot p (120e18), skew 5%: expected q.low = 100e18 (median rule), actual q.priced true, q.agree false, q.low = 120e18 (twin rule applied, a pushed swarm factor raised low). Run: forge test --match-path 'test/scratch/ProofC5Proven.t.sol' -vv -> [FAIL: C5: proven() must be false with an attester in the path] test_productOfProvenAndSwarmLeafReportsProven(); [FAIL: median rule expected: the spot has an attester in its path, pushed spot raised low: 120000000000000000000 != 100000000000000000000] test_pricerGivesTwinRuleToSpotWithAttesterInPath().

**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 {Test} from "forge-std/Test.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {SwarmFeed} from "src/feeds/SwarmFeed.sol";
import {SwarmPricePolicy} from "src/feeds/SwarmFeeds.sol";
import {ProductFeed} from "src/feeds/ProductFeed.sol";
import {RateFeed} from "src/feeds/RateFeed.sol";
import {FeedTraits} from "src/feeds/FeedTraits.sol";
import {Pricer} from "src/Pricer.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";

contract DoorLeaf is SwarmPricePolicy {
    constructor() SwarmFeed(address(1), address(0), 1, 3, 1 hours, 2000) {}
    function set(uint256 t) external { _accept(t, uint64(block.timestamp)); }
}

contract MockFeed is IFeed {
    uint256 public v;
    constructor(uint256 v_) { v = v_; }
    function set(uint256 v_) external { v = v_; }
    function latestValue() external view returns (uint256, uint64) { return (v, uint64(block.timestamp)); }
    function isStale() external pure returns (bool) { return false; }
    function maxAge() external pure returns (uint256) { return 6 hours; }
}

contract MockProven is MockFeed {
    constructor(uint256 v_) MockFeed(v_) {}
    function proven() external pure returns (bool) { return true; }
}

contract Rate1 { function convertToAssets(uint256 x) external pure returns (uint256) { return x; } }

contract MockParams {
    ParametersBase.Config internal cfg;
    ParametersBase.Risk internal rsk;
    function setConfig(ParametersBase.Config memory c) external { cfg = c; }
    function setRisk(ParametersBase.Risk memory r) external { rsk = r; }
    function config(bytes32) external view returns (ParametersBase.Config memory) { return cfg; }
    function storedRisk(bytes32) external view returns (ParametersBase.Risk memory) { return rsk; }
    function maxLull() external pure returns (uint256) { return 0; }
    function cap(bytes32) external pure returns (uint256) { return 0; }
}

contract Reader {
    function proven(IFeed f) external view returns (bool) { return FeedTraits.proven(f); }
    function converged(IFeed f) external view returns (bool) { return FeedTraits.converged(f); }
}

/// C5: ProductFeed.proven() = proven(a) || proven(b). A product of a proven pool price and a swarm leaf reports proven
/// (and RateFeed over it forwards it) although an attester is in its path, and the Pricer then gives it the twin rule.
contract ProofC5Proven is Test {
    Reader r;
    function setUp() public { vm.chainId(1); vm.warp(1_800_000_000); vm.roll(26_000_000); r = new Reader(); }

    function test_productOfProvenAndSwarmLeafReportsProven() public {
        DoorLeaf leaf = new DoorLeaf();
        leaf.set(1e18);
        leaf.set(10e18); // same epoch: clamped to 1.2e18, not converged
        MockProven pv = new MockProven(100e18);
        ProductFeed p = new ProductFeed(IFeed(address(pv)), IFeed(address(leaf)));
        RateFeed rf = new RateFeed(address(new Rate1()), Rate1.convertToAssets.selector, true, IFeed(address(p)), 0);
        assertFalse(r.converged(IFeed(address(p))), "the leaf is clamped: not converged");
        assertTrue(r.proven(IFeed(address(rf))), "RateFeed forwards proven");
        assertFalse(r.proven(IFeed(address(p))), "C5: proven() must be false with an attester in the path");
    }

    function test_pricerGivesTwinRuleToSpotWithAttesterInPath() public {
        DoorLeaf leaf = new DoorLeaf();
        leaf.set(1e18);
        leaf.set(10e18); // stored 1.2e18 (pushed +20%, clamped)
        MockProven pv = new MockProven(100e18);
        ProductFeed spot = new ProductFeed(IFeed(address(pv)), IFeed(address(leaf))); // 120e18
        MockFeed median = new MockFeed(100e18);
        MockParams mp = new MockParams();
        ParametersBase.Config memory c;
        c.token = address(0xC0FFEE); c.median = IFeed(address(median)); c.spot = IFeed(address(spot));
        ParametersBase.Risk memory rk; rk.mat = 1.7e18; rk.chop = 0.2e18; rk.skew = 0.05e18;
        mp.setConfig(c); mp.setRisk(rk);
        Pricer p = new Pricer(Parameters(address(mp)));
        Pricer.Quote memory q = p.quote("X");
        emit log_named_uint("q.low", q.low);
        assertTrue(q.priced); assertFalse(q.agree);
        assertEq(q.low, 100e18, "median rule expected: the spot has an attester in its path, pushed spot raised low");
    }
}
```

### 6. Low: ProvenPoolPrice.prove accepts ANY block newer than the held one among the last 256, so a prover picks the most favourable end-of-block price of ~51 minutes at no push cost (up to skew below the median

`src/feeds/ProvenPoolPrice.sol:101`

```
        if (number <= provenBlock) return _value;
```

The only ordering rule is 'newer than the held block'. With the held block H and head N (N - H up to 255) a prover may prove any block in (H, N]; nothing prefers the latest, and the fixture test shows a block 250 behind the head accepted. The README residual ('a proven spot pushed DOWN within skew lowers low by up to skew while that proof stands') prices this as a push held across a block end and exposed to arbitrage. Selection needs no push: IMD's end-of-block price over 256 blocks moves several percent on its own, so a liquidator proves the lowest block within skew (5%) of the median and bites in the same bundle: agree stays true (within skew, both converged), low = min(median, spot) = that spot, and positions with CR within up to 5% above mat are liquidated at the 20% chop; the standing bid (agree true) buys at that low. A newer honest proof afterwards does not undo the bite. The known residual therefore holds at a lower cost than written (no push, no arbitrage exposure, ~1M gas for the proof). Reachable with the deploy config (PROVEN_MAX_AGE 6 h, skew 5%, chop 20%). Smallest fix: bound how far back a NEW proof may reach, e.g. refuse `block.number - number > PROVE_WINDOW` (32 blocks, ~6 min: the keeper proves 'the previous block'), shrinking the menu from 256 to 32 candidates; or, in the Pricer's agree branch, use low = median when the spot is proven and below it (the proven spot then only ever RAISES low, which is its role in design C), at the cost of the 5% of borrower protection the spot adds there.

**Reproduction**

Real mainnet fixture (test/fixtures/ProvenPoolFixture.sol, pool 0xb07d, block 26407674). Deploy ProvenPoolPrice(manager, 0xb07d, false, 6 h); vm.roll(F.BLOCK + 250); vm.setBlockhash(F.BLOCK, F.BLOCK_HASH); prove(F.header(), F.accountProof(), F.storageProof()). Expected (the latest or a recent-few-blocks price): refused as too old, or the price of the head's neighbourhood. Actual: accepted, provenBlock = 26407674 (250 blocks behind the head), isStale() false, and it stands for 6 h or until a newer block is proved. Run: forge test --match-path 'test/scratch/ProofProveAnyBlock.t.sol' -vv -> [PASS] test_blockFarBehindHeadIsAccepted() (gas: 2453256), the PASS showing the acceptance. Economic step (code reading): with the head price p_N and a block i* in (H, N] where p_i* >= 0.95 x median, Pricer.quote gives agree = true and low = p_i* x ETH/USD x rate; Liquidator.bite in the same bundle liquidates a position with CR in [mat, mat x median / p_i*).

---

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