# Audit report

> Audit every contract in src/ the beta deploys (README.md scope), read together, at the pinned commit, for a capped mainnet beta. Read whatever else in src/ these depend on, but report on this scope.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum. Positions are NFT ids; borrowers set their own interest 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 from swarm-attested feeds (EIP-712 attestations bound to pinned questions). README.md gives the scope, the key invariants, the trust model and the known issues: read it first.
>
> BUILD AND TEST (required; Foundry, solc 0.8.26 via_ir per foundry.toml). Never build or test the whole project: with every suite it needs about 49 GB and the compiler will be killed. Run only this panel's tests: `forge test --match-path '{test/unit/FullSystem.t.sol,test/invariant/Invariants.t.sol}'` (measured: about 3.1 GB peak, 5 minutes). One build at a time on your machine. Write each proof as a new file test/unit/Proof<Name>.t.sol, add it to the glob and run it; paste it with its output into the finding, then delete it: your submission must leave the tree unchanged. With Foundry 1.9 or later, `forge test --use solar --no-match-path 'test/fork/*'` builds everything and runs all 1,179 tests in seconds under 1 GB (Solar accepts a little syntax solc refuses: confirm a proof with the solc command).
>
> test/utils/FullSystem.sol runs the real deploy script (script/Deploy.s.sol) and wires every module together on a local Uniswap v4 PoolManager with mock tokens, vaults and feeds; it uses MainnetConfig; BetaConfig turns some of those modules off and sets other values, so say whether each finding holds under BetaConfig. test/invariant/Invariants.t.sol fuzzes the core. Build every attack on these, across contracts, as the live system would see it.
>
> Answer each numbered question, including the ones where nothing is wrong:
> 1. SUPPLY EQUATION (README.md key invariants). Every path that mints or burns imdUSD: borrow, repay, interest, redemption, liquidation by a caller and by a sleeve, Treasury cover and retire, the peg keeper, the migrator, the flash mint. Break the equation with a sequence across contracts.
> 2. THE LIQUIDATION MONEY PATH: mark, bite, the standing bid, bad debt, the edge sleeve's first loss, the Treasury's cover. Value in must equal value out at every step; find where it does not.
> 3. FLASH. Flash-minted imdUSD into redemption, a caller liquidation, a Backstop deposit, peg pool swaps and PegPositionZap, within one transaction.
> 4. PEG TO ALLOCATOR TO BACKSTOP: the hook's keeper and buffer, an Allocator sale through a route, Backstop.sell. Can value leak between the protocol's pots or to a caller?
> 5. ORACLE INTO EVERYTHING. One accepted attestation pair at the edge of its cap: the worst outcome across liquidation, redemption, borrowing, sleeve conversion and edge capacity.
> 6. Each specialist applies their lens (math, permissions, economics, control flow) to every one of these paths, not to one contract.
>
> Not findings: anything listed under README.md 'Known issues and accepted risks' (say so if you find it worse than written); src/bridge, src/dex, src/earn/LoopVault.sol and src/stocks (after the beta) unless a question names them; test/ and its mocks; gas optimisations unless they change behaviour.
>
> For every finding: severity by impact; file, line and the lines copied; the call sequence from an external caller; a concrete failing input or state with expected against actual; whether it is reachable with the values in script/DeployConfig.sol (BetaConfig); the smallest fix; and a Foundry test that fails on this commit, RUN as BUILD says and pasted in full in the finding with its output (the judge reruns it). The test/ tree has harnesses to reuse (test/utils/System.sol, the unit suites). Answer every numbered question, including those where nothing is wrong. Give a coverage row (holds, finding or unreached, with a reason) for every external function of the contracts in scope. Also report every comment or NatSpec that claims a property the code does not have.

| | |
|---|---|
| Repository | https://github.com/fa11up/imdusd-v2-audit.git |
| Commit | `2875ffb22a726f041bd6891f32f35ddc7cdb983d` |
| Job | `4384ebcc-37f4-4bc3-8e2b-fc48f01f0701` |
| Judged | 2026-11-10 21:36 UTC |
| Findings | 4 low · 9 info |

Four agents audited the code as it is at `2875ffb`, 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: Ledger.setRate's charged path adds debt and mints imdUSD while the unbacked-supply brake is on (no _checkBrake)

`src/Ledger.sol:161`

```
            s.debt += premium.toUint128();
```

LedgerBase.sol:320 documents the brake as 'new debt stops on every type while unbacked() exceeds the governed fraction of the circulating supply', and Ledger.sol:296-297 repeats it on the borrow path, which calls _checkBrake() before token.mint (Ledger.sol:301). The charged branch of Ledger.setRate (a rate change inside RATE_COOLDOWN = 7 days, Ledger.sol:156-170) also adds debt (line 161) and mints it (line 165, _mintInterest), and runs the type line, _checkLines, _checkEdge, the borrowable/agree check and the health check, but never _checkBrake. While the brake is on, a position owner can still grow type debt and totalSupply by debt x oldRate x 7/365 per call and repeat it by alternating two rates until the line or health stops it. The minted imdUSD goes to savers, the edge premium and the Treasury, not to the borrower, and the supply equation holds (debt and supply rise together), so no value is taken; the impact is that a documented safety stop does not apply to one debt-adding path. README known issues list the peg keeper mint as outside the brake, not this path. Reachable under BetaConfig on every listed type (unbackedBrake default 0.01e18, RATE_COOLDOWN constant). Reproduced by reading the code and with the specialist's test (its run is reported in the reproduction field). Smallest fix: call _checkBrake() next to _checkLines/_checkEdge at Ledger.sol:163-164, or document the premium as exempt at LedgerBase.sol:320 and Ledger.sol:296-297.

**Reproduction**

State (standalone harness in the proof): ETH type mat 1.4, chop 0.1, rateFloor 1%; alice 10 WETH / 14,000 imdUSD at 5%, dave 200 WETH / 50,000 imdUSD at 5%; ETH median and spot 2,000 -> 1,000; dave calls Liquidator.liquidate(alice's id), which books about 4,013 bad debt so unbacked() (about 3,952) exceeds the brake allowance (1% of circulating, 540). Control: dave's ledger.open(ETH, 0, Adjust(0, 1_000e18, ...)) reverts Braked. Input: dave calls ledger.setRate(daveId, 0.06e18, 0, 0) in the same block (inside the 7-day cooldown). Expected per LedgerBase.sol:320: revert Braked, no new debt. Actual: succeeds; ilkState(ETH).debt and totalSupply both rise by about 47.99e18 (50,000 x 5% x 7/365). Test: test/scratch/BrakePremium.t.sol (the proof below), run with forge test --match-path test/scratch/BrakePremium.t.sol -vv; it fails on this commit with 'next call did not revert as expected' and passes once _checkBrake() is added to the charged path. See the proof field for the test source and the end of this field for the run status on this machine. Run on this commit (forge 1.8.3, solc 0.8.26 via_ir, foundry.toml profile): forge test --match-path test/scratch/BrakePremium.t.sol -vv -> [FAIL: next call did not revert as expected] test_chargedRateChangeAddsDebtWhileBraked() (gas: 2586654); Logs: unbacked 3952054794520547945205; brake allows 540000000000000000000; type debt added while braked 47991180334021392382; imdUSD minted while braked 47991180334021392382; Suite result: FAILED. 0 passed; 1 failed; 0 skipped.

**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, console2} from "forge-std/Test.sol";
import {ImdUSD} from "src/ImdUSD.sol";
import {ParametersBase} from "src/ParametersBase.sol";
import {Parameters} from "src/Parameters.sol";
import {Pricer} from "src/Pricer.sol";
import {Treasury, ICoverable, IERC20} from "src/Treasury.sol";
import {PositionNFT} from "src/PositionNFT.sol";
import {Ledger, IPulse} from "src/Ledger.sol";
import {LedgerBase} from "src/LedgerBase.sol";
import {Redeemer} from "src/Redeemer.sol";
import {Liquidator} from "src/Liquidator.sol";
import {Migrator} from "src/Migrator.sol";
import {Join} from "src/Join.sol";
import {IFeed} from "src/interfaces/IFeed.sol";
import {Adjust} from "src/interfaces/IPositions.sol";

contract Tok {
    string public name = "T";
    string public symbol = "T";
    uint8 public constant decimals = 18;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    function mint(address to, uint256 a) external {
        totalSupply += a;
        balanceOf[to] += a;
        emit Transfer(address(0), to, a);
    }

    function approve(address s, uint256 a) external returns (bool) {
        allowance[msg.sender][s] = a;
        emit Approval(msg.sender, s, a);
        return true;
    }

    function transfer(address to, uint256 a) external returns (bool) {
        balanceOf[msg.sender] -= a;
        balanceOf[to] += a;
        emit Transfer(msg.sender, to, a);
        return true;
    }

    function transferFrom(address f, address to, uint256 a) external returns (bool) {
        if (allowance[f][msg.sender] != type(uint256).max) allowance[f][msg.sender] -= a;
        balanceOf[f] -= a;
        balanceOf[to] += a;
        emit Transfer(f, to, a);
        return true;
    }
}

contract Feed is IFeed {
    uint256 public constant MAX_ALLOWANCE_BPS = 20_000;
    uint256 public value;
    uint64 public at;
    uint256 public maxAge = 1 hours;

    constructor(uint256 v) {
        set(v);
    }

    function set(uint256 v) public {
        value = v;
        at = uint64(block.timestamp);
    }

    function latestValue() external view returns (uint256, uint64) {
        return (value, at);
    }

    function isStale() external view returns (bool) {
        return block.timestamp > at + maxAge;
    }
}

/// The brake (LedgerBase._checkBrake, "new debt stops on every type") is not read by Ledger.setRate's charged path.
contract BrakePremiumTest is Test {
    bytes32 constant ETH = "ETH";
    address governor = makeAddr("governor");
    address alice = makeAddr("alice");
    address dave = makeAddr("dave");

    ImdUSD usd;
    Parameters params;
    Pricer pricer;
    Treasury treasury;
    Ledger ledger;
    Liquidator liquidator;
    Tok weth;
    Feed median;
    Feed spot;

    function setUp() public {
        vm.warp(1_800_000_000);
        weth = new Tok();
        Tok v1 = new Tok();
        median = new Feed(2000e18);
        spot = new Feed(2000e18);

        usd = new ImdUSD(address(this), 10_000_000e18);
        params = new Parameters(governor, address(this));
        pricer = new Pricer(params);
        treasury = new Treasury(governor, IERC20(address(usd)), address(this));
        PositionNFT nft = new PositionNFT(address(this));
        ledger = new Ledger(usd, params, pricer, address(treasury), address(this), IPulse(address(0)), nft);
        nft.bind(address(ledger));
        Redeemer redeemer = new Redeemer(ledger);
        liquidator = new Liquidator(ledger, pricer);
        ledger.wire(address(redeemer), address(liquidator));
        Migrator migrator = new Migrator(IERC20(address(v1)), usd, params);
        usd.wire(address(ledger), address(migrator), address(params));
        params.wire(address(ledger), address(usd));
        treasury.wire(ICoverable(address(ledger)));

        Join join = new Join(address(weth), address(this));
        join.wire(address(ledger));
        params.addGenesisIlk(
            ETH,
            ParametersBase.Config({
                token: address(weth),
                join: address(join),
                median: median,
                spot: spot,
                nhi: IFeed(address(0)),
                yieldRate: address(0),
                pegAggregator: address(0),
                liveSpot: IFeed(address(0)),
                redeemable: true,
                auction: false
            }),
            ParametersBase.Risk({
                mat: 1.4e18,
                chop: 0.1e18,
                cut: 0.5e18,
                chip: 0.1e18,
                rateFloor: 0.01e18,
                yieldFee: 0,
                skew: 0.05e18,
                pegFloor: 0,
                line: 1_000_000e18,
                dust: 100e18,
                redeemFloor: 0.005e18,
                redeemDivisor: 2,
                redeemCap: 0
            })
        );
        params.seal();

        address[2] memory users = [alice, dave];
        for (uint256 i; i < 2; ++i) {
            weth.mint(users[i], 1000e18);
            vm.prank(users[i]);
            weth.approve(address(ledger), type(uint256).max);
        }
    }

    function _ilkDebt() internal view returns (uint256) {
        (uint128 debt,,,,) = ledger.ilkState(ETH);
        return debt;
    }

    function test_chargedRateChangeAddsDebtWhileBraked() public {
        // alice 10 WETH / 14,000 (142.8% at $2,000); dave 200 WETH / 50,000, both at 5%.
        vm.prank(alice);
        uint256 a = ledger.open(ETH, 0, Adjust(10e18, 14_000e18, 0.05e18, 0, 0, false, type(uint256).max, address(0)));
        vm.prank(dave);
        uint256 dv = ledger.open(ETH, 0, Adjust(200e18, 50_000e18, 0.05e18, 0, 0, false, type(uint256).max, address(0)));

        // ETH halves: alice's 10 WETH are worth $10,000 against ~14,013 of debt. dave liquidates; ~4,000 is bad debt.
        median.set(1000e18);
        spot.set(1000e18);
        vm.prank(dave);
        (,, uint256 bad) = liquidator.liquidate(a);
        assertGt(bad, 3_900e18, "bad debt booked");
        uint256 allowed = usd.circulating() * params.unbackedBrake() / 1e18;
        assertGt(ledger.unbacked(), allowed, "the system is past the brake");
        console2.log("unbacked      ", ledger.unbacked());
        console2.log("brake allows  ", allowed);

        // Control: a borrow on the healthy position is refused by the brake.
        vm.prank(dave);
        vm.expectPartialRevert(LedgerBase.Braked.selector);
        ledger.open(ETH, 0, Adjust(0, 1_000e18, 0, 0, 0, false, type(uint256).max, address(0)));

        // What a charged rate change does on this commit (measured, then rolled back).
        uint256 snap = vm.snapshotState();
        uint256 debt0 = _ilkDebt();
        uint256 supply0 = usd.totalSupply();
        vm.prank(dave);
        try ledger.setRate(dv, 0.06e18, 0, 0) {
            console2.log("type debt added while braked ", _ilkDebt() - debt0);
            console2.log("imdUSD minted while braked   ", usd.totalSupply() - supply0);
        } catch {
            console2.log("setRate reverted");
        }
        vm.revertToState(snap);

        // Expected (LedgerBase.sol:320, Ledger.sol:296-297): no new debt on any type while past the brake.
        vm.prank(dave);
        vm.expectPartialRevert(LedgerBase.Braked.selector);
        ledger.setRate(dv, 0.06e18, 0, 0);
    }
}
```

### 2. Low: Liquidator.settle (seat auction sales) books bad debt without the in-transaction cover that bite performs

`src/Liquidator.sol:212`

```
        return ledger.liquidatePosition(id, price, msg.sender, marker, reserve);
```

Every fungible liquidation in Liquidator.bite ends with _cover(ilk, bad) (Liquidator.sol:175 and :184), whose NatSpec (lines 187-191) promises that booked bad debt is covered in the liquidation's own transaction so 'no depositor can leave between the loss and its cover, and the unbacked brake sees only what both could not pay'. The auction path does not: settle (Liquidator.sol:202-213), reached from SeatJoin.take / takeFloor -> _settle (src/seats/SeatJoin.sol:578), returns ledger.liquidatePosition's result straight to the join, which uses bad only for its own penalty split. The seat type is live in BetaConfig (seatSpec: mat 250%, chop 10%, line 40k), so a seat sale below the debt leaves Ledger.totalBadDebt() and ilkState(SEAT).badDebt non-zero although the Treasury holds imdUSD it could burn. Until someone calls Treasury.coverBadDebt('SEAT'): Treasury.retireReserve reverts BadDebtOutstanding for every type, unbacked() reads the whole hole (and brakes every type if it exceeds 1% of circulating), and fee-note redemptions compete for the same balance. No value is lost and the supply equation holds (supply == debt + badDebt), so low. Reachable under BetaConfig. Smallest fix: in settle, capture bad and call _cover(ilk, bad) after ledger.liquidatePosition (the join holds no Ledger lock there, and Treasury.coverBadDebt on a non-edge type only burns Treasury imdUSD). Reproduced by reading Liquidator.settle and SeatJoin._settle; no runnable proof is attached (the specialist's test used the SeatSystem harness, not supplied).

**Reproduction**

BetaConfig seat type (mat 2.5e18, chop 0.1e18, rateFloor 0.08e18, dust 100e18; seat median 2e18 wei x ETH/USD 2000e18 = $4,000 a seat). 1) alice deposits seat #1 through SeatJoin.deposit and opens a SEAT position: collateral 1e18 units, debt 1,500 imdUSD at 8%. 2) Five strictly newer median attestations of 0.8e18 with SeatFeed.poke between them walk the accepted median 2 -> 1.6 -> 1.28 -> 1.024 -> 0.8192 -> 0.8 ETH ($1,600). 3) Liquidator.liquidate(id) marks and opens the Dutch auction at $1,600; after 6h of priced time the price is $1,120. 4) bob holds imdUSD, the Treasury holds 2,000 imdUSD; bob approves the join and calls SeatJoin.take(id, type(uint256).max). 5) The Ledger books bad = debt (1,500 + upfront fee + interest) - 1,120, about 382 imdUSD. Expected per Liquidator._cover's NatSpec and README invariant 5: ledger.totalBadDebt() == 0 after the sale and the Treasury balance down by about 382. Actual: ledger.totalBadDebt() == about 382e18 while the Treasury still holds its 2,000 imdUSD; treasury.retireReserve(1) reverts BadDebtOutstanding; a later treasury.coverBadDebt('SEAT') burns the 382 and clears it.

### 3. Low: Treasury.retireReserve is permissionless: a stranger can burn the Treasury's liquid bad-debt cover one block before a loss (README entry stale, NatSpec overclaims)

`src/Treasury.sol:136`

```
    function retireReserve(uint256 amount) external {
```

retireReserve lets any caller burn up to reserveBacked of the Treasury's imdUSD (Ledger.retire, Ledger.sol:386-391). The only guard (line 137) refuses while bad debt is ALREADY booked; nothing stops a caller from draining the balance ahead of a loss. That balance is the system's only liquid bad-debt cover: LedgerBase.unbacked() (LedgerBase.sol:224-228) nets ONLY token.balanceOf(treasury) against totalBadDebt and feeds _checkBrake on every borrow of every type, Treasury.coverBadDebt can burn only that balance, and Treasury.payNote pays matured fee notes from it. reserveBacked grows with every yield harvest of the beta's yield types (S-USDS, S-USDC-STEAKHOUSE, WSTETH carry yieldFee 0.1), so after weeks it is large enough to absorb the Treasury's whole interest income. Sequence: (1) anyone calls treasury.retireReserve(type(uint256).max) while totalBadDebt == 0, burning the whole balance (bounded by reserveBacked); (2) a blue position is bitten and books bad debt B; Liquidator._cover -> Treasury.coverBadDebt finds balance 0 and covers nothing; (3) unbacked() == B instead of B minus the Treasury's accrued income, and when B > 1% of circulating every type's borrowing reverts Braked until someone burns imdUSD through Ledger.cover; with a FeeNotes series open, every matured FeeNotes.redeem reverts TreasuryShort. The accounting is supply-neutral (yield shares back the retired supply), which is what the NatSpec at Treasury.sol:35-37 means by 'can never make the system less solvent'; but the act converts the protocol's liquid cover into illiquid vault shares at a stranger's discretion and at the worst moment, so that claim is wider than the code. README.md:188 lists 'retireReserve is permissionless and does not check outstanding bad debt' as accepted; the bad-debt check now exists (line 137), so the README entry is stale, and the remaining pre-emptive-drain consequence is reported here as the materially worse reading (brake griefing across every type, fee-note default). This merges three specialist entries (the drain, the Treasury.sol:35 NatSpec, the stale README line). Holds under BetaConfig (yield types on, FeeNotes deployed dormant, brake 1%). Smallest fix: make retireReserve onlyGovernor, or require the burn to leave max(FeeNotes outstanding, a governed reserve floor) of imdUSD in the Treasury; and update README.md:188.

**Reproduction**

Measured by the specialist on a CoreTest-derived harness and checked against the code here: (1) alice opens SUSDC 10,000e6 shares / 5,000e18 debt at 2%; the vault accrues; warp 6 days; ledger.harvest(SUSDC,[id]) -> ledger.reserveBacked() > 400e18. (2) alice opens ETH 10e18 / 14,000e18, dave opens ETH 200e18 / 50,000e18: usd.balanceOf(treasury) == X (about 65e18 of fees and interest) < reserveBacked. (3) attacker (holds no imdUSD): treasury.retireReserve(type(uint256).max). Expected per Treasury.sol:35-37 and the README trust model: a stranger cannot remove the Treasury's cover. Actual: usd.balanceOf(treasury) == 0, reserveBacked fell by X. (4) ETH 2000 -> 1200; dave: liquidator.liquidate(alice's ETH id) books B about 2,013e18. Actual: ledger.unbacked() == B (the in-transaction _cover burned 0); without step 3 the same liquidation covers X and leaves unbacked == B - X. (5) unbacked > 1% of circulating: ledger.open(ETH, +1,000e18) reverts Braked. Also: Treasury.retireReserve(x) with totalBadDebt == 1 wei reverts BadDebtOutstanding, which README.md:188 says it would not.

### 4. Low: ImdUSD flash cap bounds loans in flight, not the transaction: sequential loans each get the full flashCap (NatSpec claims a per-transaction bound)

`src/ImdUSD.sol:167`

```
        _setFlashOutstanding(before);
```

The contract header (ImdUSD.sol:21-23: 'up to flashCap PER TRANSACTION ... so nested or repeated loans inside one transaction share the cap') and flashLoan's @dev (lines 148-150: 'so the cap bounds the transaction, not one call') claim a per-transaction bound. flashLoan restores the transient counter to `before` when each loan is repaid (line 167), so after a loan unwinds the next loan in the same transaction again sees the whole cap: only the amount in flight at one moment is bounded (which is what the flashCap @notice at line 28 says). No supply break follows (every loan is burned before return and circulating() excludes the in-flight part), but any reasoning or monitoring that relies on 'at most flashCap flash-minted per transaction' (for example sizing flash attacks on redemption, a caller liquidation, a Backstop deposit or the peg pool, the panel's question 3) is wrong: one transaction can flash-mint N x flashCap sequentially. Holds under BetaConfig (flashCap 100_000e18). Reproduced with the specialist's proof (status in the reproduction field). Smallest fix: correct the NatSpec to 'at most flashCap in flight at any moment', or, if a per-transaction bound is intended, keep a second transient counter of the cumulative amount lent that is never decremented and check value <= flashCap - cumulative.

**Reproduction**

ImdUSD deployed with flashCap = 100_000e18 (BetaConfig). A receiver contract loops imdUSD.flashLoan(this, imdUSD, 100_000e18, '') three times in one external call, repaying each in its callback. Expected per ImdUSD.sol:21-23 and 148-150: the second loan reverts ERC3156ExceededMaxLoan(0). Actual: all three succeed, 300_000e18 flash-minted in one transaction, flashOutstanding() never above 100_000e18. Test: test/scratch/ProofFlashCap.t.sol (proof field), forge test --match-path test/scratch/ProofFlashCap.t.sol -vv; run status on this machine is appended at the end of the proof's description. Run on this commit (forge 1.8.3, solc 0.8.26 via_ir, foundry.toml profile): forge test --match-path test/scratch/ProofFlashCap.t.sol -vv -> [FAIL: three sequential full-cap loans in one transaction succeeded: the cap does not bound the transaction] test_sequentialLoansDoNotShareTheCap() (gas: 569683); Suite result: FAILED. 0 passed; 1 failed; 0 skipped.

**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 {ImdUSD} from "src/ImdUSD.sol";
import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";

contract Looper is IERC3156FlashBorrower {
    ImdUSD public immutable usd;
    uint256 public maxSeen;
    constructor(ImdUSD u) { usd = u; }
    function run(uint256 amount, uint256 times) external {
        for (uint256 i; i < times; ++i) usd.flashLoan(this, address(usd), amount, "");
    }
    function onFlashLoan(address, address, uint256 amount, uint256, bytes calldata) external returns (bytes32) {
        if (usd.flashOutstanding() > maxSeen) maxSeen = usd.flashOutstanding();
        usd.approve(address(usd), amount);
        return keccak256("ERC3156FlashBorrower.onFlashLoan");
    }
}

contract ProofFlashCap is Test {
    function test_sequentialLoansDoNotShareTheCap() public {
        ImdUSD usd = new ImdUSD(address(this), 100_000e18); // BetaConfig.flashCap
        Looper l = new Looper(usd);
        // NatSpec (ImdUSD.sol:21-23, 149): "up to flashCap PER TRANSACTION ... nested or repeated loans inside one
        // transaction share the cap"; "the cap bounds the transaction, not one call".
        // One call (one transaction) takes the whole cap three times in a row: 300k flash-minted in total.
        bool ok;
        try l.run(100_000e18, 3) {
            ok = true;
        } catch {}
        assertFalse(ok, "three sequential full-cap loans in one transaction succeeded: the cap does not bound the transaction");
    }
}
```

### 5. Info: Comment claims closeBid counts an edge premium that arrives during an open bid; closeBid never does

`src/LedgerBase.sol:293`

```
                IEdgeSleeve(edge).sync(); // streams over 7 days; a no-op inside an open bid (closeBid counts it then)
```

Backstop.sync (src/backstop/Backstop.sol:588-608) returns early while a bid is open (line 595). Backstop.closeBid (lines 532-563) sets spent = repaid, does tracked -= spent and coll[token] += received, and adds no arrival to tracked or to the stream; its own comment (line 550) says an arrival during the bid 'only raises usdAfter'. The premium is folded in by the next sync() call, which starts its 7-day stream then. No value moves: the imdUSD sits in the sleeve as untracked balance until that call. Comment only; reword to 'the next sync counts it'. Reachable under BetaConfig once the SIMD line opens (edge type with edgePremium 0.2e18).

**Reproduction**

State: an edge-type (SIMD) position is unhealthy, the edge sleeve has room, at least one second has passed since the type last accrued. Liquidator.bite -> Backstop.openBid -> Ledger.liquidatePosition -> _accrue -> _mintInterest mints the edge premium P to the sleeve and calls sync(), which returns at Backstop.sol:595 because a bid is open -> Backstop.closeBid(ilk, repaid). Expected per the comment: after closeBid, tracked includes P. Actual: tracked fell by repaid only; imdUSD.balanceOf(sleeve) - tracked - staged == P until someone calls sync().

### 6. Info: LivePoolPrice NatSpec says the live leg only ever raises the redemption payout and never measures a borrower; Pricer also zeroes the payout and clears agree with it

`src/feeds/LivePoolPrice.sol:13`

```
/// is never used to measure a borrower: the Pricer only ever raises the payout price with it
```

Lines 12-14 state the live pool price is 'THE REDEMPTION PAYOUT LEG ONLY', 'never used to measure a borrower', and that the Pricer 'only ever raises the payout price with it'. Pricer._applyLive (src/Pricer.sol:93-104) does two more things: when the leg reads 0 or stale it sets q.payout = 0 and q.agree = false (lines 97-99), and when the pool is below low by more than skew it sets q.agree = false (line 102). agree gates the sleeve's standing bid in Liquidator.bite (line 165) and a borrower's charged rate change (Ledger.sol:166 reverts NotPriced). The behaviour is documented in the README's known issues ('The live leg sets the redemption payout and agree only') and in Pricer's comments; only this NatSpec is out of date. Reachable under BetaConfig on SIMD (the only type with a live leg). Fix: reword lines 12-14 to name the two other readers.

**Reproduction**

SIMD with attested median = spot = 5.00 (low = high = 5.00), skew 5%. Input A: live pool price 4.70 (6% under low). Expected per the NatSpec: payout = max(5.00, 4.70) = 5.00 and nothing else. Actual: payout = 5.00 and agree = false, so Liquidator.bite skips the standing bid (the caller path takes the position) and Ledger.setRate inside the cooldown reverts NotPriced. Input B: live leg returns 0 or is stale. Expected per 'only ever raises the payout': payout >= high. Actual: payout = 0 (Redeemer.redeem reverts NotPriced) and agree = false.

### 7. Info: ImdUSD.burn NatSpec ('each minter only burns on an action from initiated') does not hold for the standing bid: the Ledger burns from the Backstop sleeve on a third party's call

`src/ImdUSD.sol:116`

```
    /// @notice Burn from `from` without an allowance, by a minter (each minter only burns on an action
```

ImdUSD.sol:116-117 states each minter only burns from `from` on an action `from` initiated through it. In Liquidator.bite's standing-bid path (Liquidator.sol:172) the Ledger is called with payer = the Backstop sleeve, and LedgerSettlement.liquidatePosition (LedgerSettlement.sol:185, token.burn(payer, repaid)) burns repaid from the sleeve's balance with no allowance, on a call any third party initiated (anyone may call Liquidator.liquidate/bite). This is the intended design (the sleeve is a standing bid, guarded by openBid/closeBid's room and BadPrice checks), but the token-level comment misstates the trust property integrators read. Fix: reword the NatSpec to name the standing-bid exception. Holds under BetaConfig (blue sleeve lists ETH, WSTETH, CBBTC, WBTC, S-USDS, S-USDC-STEAKHOUSE).

**Reproduction**

BetaConfig: an ETH position becomes unhealthy while the blue sleeve has room >= its debt and the legs agree; any EOA calls Liquidator.liquidate(id). Expected per ImdUSD.sol:116-117: only the initiator's imdUSD is burned. Actual: repaid imdUSD is burned from the blue Backstop (Liquidator.sol:172 -> LedgerSettlement.sol:185) without its allowance; the sleeve's imdUSD balance falls by repaid and its collateral rises by received.

### 8. Info: Backstop header says the edge sleeve covers seats (and stocks); seats are an auction type that can never be listed in a sleeve

`src/backstop/Backstop.sol:16`

```
/// exist per chain: `blue` (ETH, BTC, staked stables) and `edge` (sIMD, seats, stocks). The edge sleeve also burns its
```

ParametersRules._validate refuses ADD_SLEEVE_ILK for any auction type (src/ParametersRules.sol:90, 'if (c.auction) revert BadConfig();'), Liquidator.bite returns before the standing bid for every auction type (Liquidator.sol:154-158), MainnetConfig.backstopSpec (used by BetaConfig) lists only SIMD with edge = true, and the README says seats 'sell by Dutch auction' with no sleeve. So the seat type has no standing bid, no first-loss sleeve and no edge-capacity bound, and its bad debt reaches only the Treasury (Treasury.coverBadDebt asks the sleeve only when params.edgeIlk(ilk)). A reader of this header would expect seat losses to hit edge depositors first. Two specialists reported this; merged. Fix: correct the comment.

**Reproduction**

Under BetaConfig: backstopSpec(SIMD_LINE_TARGET).ilks has 7 entries, only SIMD with edge = true; edge.ilks('SEAT').on == false and edge.bidRoom('SEAT') == 0. Propose Parameters.propose(abi.encode(ADD_SLEEVE_ILK, 'SEAT', true, 0, 0, 0)): _validate reverts BadConfig() at ParametersRules.sol:90 because config('SEAT').auction == true. Expected per the header: seats are an edge-sleeve type. Actual: they cannot be listed in either sleeve.

### 9. Info: Parameters header says the savers' share is governed within 0-80%; the bound in code is 50%

`src/Parameters.sol:11`

```
///    within 0-80%; open a fee-note series (tenor 30/90/180 days, discount <= 10%, a size cap); move a capped chain's
```

ParametersBase.MAX_SAVINGS_SHARE = 0.5e18 (src/ParametersBase.sol:119, '50% since 2026-10-29'); Parameters.setGenesisSavings (Parameters.sol:55) and the SET_SAVINGS_SHARE validation (ParametersRules.sol:46) revert OutOfBounds above it, with a 10-point step (MAX_SAVINGS_STEP). The README ('savings share 35%') and DeployConfig agree with the code; only this header is stale. The code's bound is the tighter one, so informational. Two specialists reported this; merged. Fix: change the header to 0-50% and mention the 10-point step.

**Reproduction**

governor: params.propose(abi.encode(SET_SAVINGS_SHARE, uint64(0.6e18))) under BetaConfig (savingsShare 0.35e18). Expected per the header: accepted (60% is within 0-80%). Actual: reverts OutOfBounds() (0.6e18 > MAX_SAVINGS_SHARE 0.5e18; the step from 0.35e18 also exceeds MAX_SAVINGS_STEP 0.1e18).

### 10. Info: Redeemer.decayedBaseRate NatSpec: the fee does not reach the 0.5% floor in ~40h; it reads about 1% then

`src/Redeemer.sol:79`

```
    /// the fee falls from 5% to a 0.5% floor in ~40h after launch. Before the seal it reads the cap.
```

_fee (Redeemer.sol:152-156) is min(redeemFloor + decayedBaseRate + increase, FEE_CAP), and decayedBaseRate starts at FEE_CAP (5%) at listedAt and decays by SECOND_DECAY = 999983955055097432 per second (half-life 43,200 s = 12h). After 40h the base alone is 0.05 x 0.5^(40/12) = about 0.0050, so with the beta's 0.5% blue floors the fee reads about 1.0%, not 0.5%; it is within 0.1% of the floor only after about 68h. Informational: the formula is as designed (the known-issues list covers fee sizing); only the comment misstates the number.

**Reproduction**

Fresh type with redeemFloor 0.005e18 and no redemption yet, 40h after Parameters.seal(): redeemer.feeFor(ilk, 1) returns about 0.00997e18 (floor 0.005e18 + base 0.05e18 x 999983955055097432^144000 / 1e18 = about 0.00497e18), not about 0.005e18 as the comment says.

### 11. Info: Edge bootstrap allowance can be renewed by re-listing: disableSleeveIlk (instant) + ADD_SLEEVE_ILK (48h) reset listedAt and genesisLine, so edgeCapacity is not bounded by vested imdUSD (trust assumpti

`src/backstop/Backstop.sol:233`

```
            k.listedAt = uint64(block.timestamp);
```

README key invariant 4 and the Backstop header describe edgeCapacity = max(3 x net vested imdUSD, a 60-day bootstrap allowance) as a one-off bootstrap. A re-listing path exists: the governor calls Parameters.disableSleeveIlk(ilk, true) (instant, Parameters.sol:181-187), then proposes ADD_SLEEVE_ILK with any genesisLine, and 48h later Backstop.addIlk takes the k.token != address(0) branch (Backstop.sol:230-236), restarting listedAt and overwriting genesisLine. bootstrap(ilk) (lines 367-372) then reads a fresh 60-day allowance and edgeCapacity (lines 374-378) = max(3 x netVested, newGenesisLine) regardless of how little the sleeve holds. ParametersRules._checkEdgeListing (lines 190-205) only requires the EXISTING edge debt to fit max(3 x netVested, genesisLine), which the proposed genesisLine itself satisfies. While the type is disabled (up to 48h) its standing bid, first-loss cover and edge capacity are off. Impact: governance (2-of-3 Safe) can keep sIMD debt uncovered by real sleeve capital indefinitely, weakening the 'first loss is paid for' property depositors and the Treasury rely on; it is within the Safe's documented, timelocked powers, so reported as a trust assumption to document, not a defect. Reachable under BetaConfig (edge sleeve on, SIMD edge type, genesisLine 50k). Fix if wanted: in addIlk keep the original listedAt/genesisLine for a previously listed type, or cap a re-listing's genesisLine at the remaining bootstrap() of the old listing.

**Reproduction**

State: edge sleeve with netVested about 0, SIMD listed at genesis with genesisLine 50,000e18, day 61 (bootstrap 0). governor: params.disableSleeveIlk('SIMD', true); params.propose(abi.encode(ADD_SLEEVE_ILK, 'SIMD', true, uint128(50_000e18), saleMax, saleSlope)); warp 48h; anyone: params.applyPending(ADD_SLEEVE_ILK). Expected per README invariant 4: edgeCapacity('SIMD', 0) == 3 x netVested, about 0 (bootstrap spent). Actual: edge.bootstrap('SIMD') == 50,000e18 and edge.edgeCapacity('SIMD', 0) == 50,000e18 for another 60 days.

### 12. Info: ImdUSD NatSpec says the keeper minter is set 'by the same timelocked setter' as the bridge; Parameters.setGenesisKeeper names it with no timelock before the seal

`src/ImdUSD.sol:18`

```
///  - `keeper` is set once by the same timelocked setter: the v4 peg hook (src/peg/PegHook.sol), capped by
```

ImdUSD.setKeeper (lines 95-102) is callable by bridgeSetter (Parameters), and Parameters exposes two callers of it: the timelocked SET_KEEPER kind in ParametersRules, and setGenesisKeeper (Parameters.sol:63-68), which the deployer (wirer) calls before seal() with no delay; the beta deploy does exactly this (script/deploy/StageGenesis.sol:106). The README trust model states it correctly ('set by the deployer before the seal'); the token's own NatSpec, which an integrator reads, says it was timelocked and public for 48h first. No functional impact (one-shot, sealed afterwards). Fix: say 'wired by Parameters: at genesis by the deployer before the seal, otherwise through the 48h SET_KEEPER proposal'.

**Reproduction**

script/deploy/StageGenesis.sol:104-107 and Parameters.sol:63-68: d.params.setGenesisKeeper(address(d.hook)) runs in the deploy transaction sequence; IBridgeSettable(token).setKeeper(keeper_) executes with msg.sender == wirer and no pending proposal. Expected per ImdUSD.sol:18: a 48h public proposal precedes KeeperSet. Actual: KeeperSet is emitted in the deploy itself.

### 13. Info: ParametersBase NatSpec says 'mainnet is uncapped' but the beta mainnet deployment caps the chain at 300k through setGenesisChainLine

`src/ParametersBase.sol:145`

```
    /// @notice The chain's global debt cap, on chains whose genesis capped it (Robinhood); mainnet is uncapped.
```

BetaConfig.get() sets c.chain.capped = true and chainLine = 300_000e18 (script/DeployConfig.sol:678) and the deploy calls params.setGenesisChainLine, after which chainCapped can never be cleared (SET_CHAIN_LINE only moves the number, ParametersRules.sol:134-136). A reader of the source would otherwise expect Ledger._checkLines to be inert on mainnet. No functional impact; update the comment (the full MainnetConfig is uncapped, the beta is not).

**Reproduction**

After the beta deploy: params.chainCap() returns (true, 300_000e18). Expected per the comment: (false, 0) on chain 1. Actual: capped; Ledger._checkLines reverts ChainLineExceeded once the summed debt + bad debt of every type reaches 300k.

---

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