# Audit report

> RE-CHECK the wave-2 fixes in src/peg/Allocator.sol, src/backstop/Backstop.sol, src/ImdUSD.sol, src/Redeemer.sol, src/Treasury.sol, and REVIEW the gas-driven layout in src/Ledger.sol, src/LedgerBase.sol, src/LedgerSettlement.sol, src/SortedPositions.sol, src/managers/RateManager.sol, at the pinned commit, for a capped mainnet beta.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum. Positions are NFT ids; borrowers set their own rate and redemptions take from the lowest rates first; liquidation is mark then bite, with a standing bid from Backstop sleeves; 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{AuctionExit,RedeemFeeBase},AuditW1RetireKeepsNotes,AllocatorRules,GasSlots,Core,Redemption,SleeveListing},test/invariant/Invariants}.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-6: 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. Auction staleness is keyed on Backstop.collIn (only rises) with a 5% restart threshold. Can new collateral still be sold under its top past 5%, can an in-kind exit or a buy hide an arrival, and how cheaply can restarts or sub-5% arrivals be used to hold the sale up?
> 2. ImdUSD.circulating() is now the supply before the transaction's first mint or burn (flash mints included). Any path that still moves the redemption fee base, the base-rate rise, the unbacked brake or the savings uptake inside one transaction, and does freezing it at the transaction's start break a legitimate path (several redemptions in one transaction, a savings mint, the brake after a cover)?
> 3. retireReserve is governor-only and a never-redeemed type starts its base rate at 0.5% (was the 5% cap). Re-run the wave-2 proofs; is a launch-day redemption run now cheap enough to matter, and is anything left that burns the Treasury's cover?
> 4. LIST ORDER WITHOUT ITS OWN RATE. SortedPositions keeps only each node's links; a node's rate is read from Ledger.rateOf. Find any path where the list order and the Ledger's recorded rate can disagree (a rate change without _relist, a listed position at rate 0, liquidation, redemption, setRate, a batch, a revert in the middle, RateManager), and what a disagreement breaks (redemption order, insertion, a walk that never ends). Measure insert/reinsert/remove gas against keeping the rate in the node.
> 5. THE TYPE IN THE RECORD. A position's type is a 16-bit index in its record (Position.ilkIndex; lastUpdate/lastRateChange narrowed to uint40) and ilkOf(id) a view over it. Can ilkOf read wrong or zero for a live, repaid or liquidated position, can two types share an index, and do every reader of Ledger.position (RateManager, SeatJoin, StockJoin, LoopVault, PegPositionZap) decode the new field order?
> 6. GAS ON USER PATHS. Measure open (first and later), borrow, repay, setRate, redeem, liquidate and bite, and count storage slots each creates (test/unit/GasSlots.t.sol). Rank: further slot cuts, Solady fullMulDiv / SafeTransferLib in place of OpenZeppelin's (list every call site whose revert behaviour would change), anything else; with the Glamsterdam figures.
>
> 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 | `f3a96d58-3fc2-418b-b2e9-cd72c50fd656` |
| Judged | 2026-11-14 17:50 UTC |
| Findings | 1 medium · 4 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. Medium: Redemption fee base and base-rate rise are frozen per transaction only: the wave-2 borrow/redeem/repay dilution still works as three transactions of one block (or consecutive blocks) at the same cost

`src/ImdUSD.sol:156`

```
    function circulating() external view returns (uint256) {
        uint256 start;
        assembly ("memory-safe") {
            start := tload(TX_SUPPLY_SLOT)
        }
        return start == 0 ? totalSupply() : start - 1;
    }
```

Wave 2 (job 5fcd4063, medium) showed that debt borrowed earlier in the redeemer's transaction and repaid before its end inflated the supply that Redeemer._fee (src/Redeemer.sol:162-163) and the base-rate rise (src/Redeemer.sol:152-156) divide by. The fix records the supply in TRANSIENT storage at the transaction's first mint or burn, so AuditW2RedeemFeeBase (one transaction) now passes. Transient storage clears between transactions, so the same three steps as three ordinary transactions of one block from one EOA (or a builder bundle, or three consecutive blocks at the cost of one block of interest) are not caught: tx1 opens a fresh position at a high rate and borrows B (the redemption never visits it); tx2 redeems R, and its first burn marks circulating() at totalSupply() + B; tx3 repays B and withdraws the collateral. The fee falls from floor + base + R/S/divisor to floor + base + R/(S+B)/divisor and the type's base rate is left at the diluted figure for every later redeemer in the ~12 h half-life. Cost: the borrow's upfront fee (RATE_COOLDOWN = 7 days of interest at the type's average rate on B, LedgerBase._upfrontFee) plus gas; the position carries no price risk inside a bundle and 12 s of it across two blocks. Measured (ETH type, divisor 2, floor 0.5%, 90,000 honest supply, 30 days in): a 9,000 redemption pays 2.99% instead of the 5% cap and takes 0.0903 WETH (~180 imdUSD at 2,000) more than an honest redemption for an upfront fee of 85.9 imdUSD; base rate left 2.49% instead of 4.995%. The ratio saving/cost is independent of size: saving ~ R x (cap - diluted), cost ~ B x avg x 7/365, profitable whenever the type's average rate is under roughly 13-25% depending on how far the ramp is above the cap. Who loses: the Treasury (the fee's collateral) and the protocol's run defence (the ramp is the toll's wall). With BetaConfig: reachable on any type with room under its line and the 300k chain cap; with ETH divisor 4 / blue divisor 16 the saving on a 10k redemption is ~22 imdUSD against ~86 of upfront fee on a 90k borrow, so it is unprofitable in the beta's blue types and profitable on sIMD (divisor 2) once its line and redeemCap admit a redemption of a few percent of the supply, and on the full mainnet config. README 'Known issues' lists the in-transaction fix and the 'imdUSD borrowed elsewhere' deflation variant, not this inflation across transactions through the protocol's own borrow path. NOTE ON THE FIX: a per-BLOCK mark (regular slot holding (block.number, supply), one warm SSTORE per block) prices a bundle at the block's opening supply but does not change the economics, since the attacker borrows in block N and redeems in N+1 for 12 s of interest; the real bound is the upfront fee. Smallest fix that changes the cost: divide the ramp and the rise by min(circulating(), a supply reference that same-day debt cannot raise), e.g. the supply recorded at the previous redemption of the type when it is under 24 h old, or a time-weighted supply kept in ImdUSD._update (one warm slot write per mint/burn: 5,000 gas now, 12,100 under Glamsterdam); otherwise accept and document under Known issues with the bound (saving <= FEE_CAP x amount; cost = upfront fee on the inflating borrow). Merged from audit_flow, audit_permissions and audit_economics (same mechanism, same proof).

**Reproduction**

Setup as test/unit/AuditW2RedeemFeeBase.t.sol (ETH type mat 1.5, redeemDivisor 2, redeemFloor 0.5%, alice owes 90,000 at 5%, 30 days later). foundry.toml has isolate = true, so each top-level call is its own transaction at the same block. mallory, holding 100 WETH and 10,000 imdUSD: tx1 ledger.open(ETH, 0, Adjust(100e18, 90_000e18, 0.5e18, ...)); tx2 redeemer.feeFor(ETH, 9_000e18) then redeemer.redeem(ETH, 9_000e18, 1e18, 1, 0); tx3 ledger.adjust(id, Adjust(-100e18, -debtOf(id), ...)). Expected (the wave-2 acceptance test's own assertions): fee 0.05e18, collateral out <= honest 4.275 WETH, rates(ETH).baseRate == min(baseAtRest + 9000/90086/2, 5%) = 0.04995e18. Actual on c64ecee: fee 0.029924883711104473e18, collateral out 0.0903 WETH above honest, baseRate 0.024924883711104473e18, upfront fee paid 85.95 imdUSD. Run: forge test --match-path test/scratch/ProofFeeBaseBundle.t.sol -vv -> [FAIL: the fee of a redemption does not depend on debt that lives only inside its block: 29924883711104473 != 50000000000000000] (compiled with solc 0.8.26 via_ir per foundry.toml).

**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 {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ImdUSD} from "src/ImdUSD.sol";
import {Parameters} from "src/Parameters.sol";
import {ParametersBase} from "src/ParametersBase.sol";
import {Pricer} from "src/Pricer.sol";
import {Treasury, ICoverable} from "src/Treasury.sol";
import {PositionNFT} from "src/PositionNFT.sol";
import {Ledger} from "src/Ledger.sol";
import {IPulse} 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 PbTok is ERC20 {
    constructor() ERC20("WETH", "WETH") {}
    function mint(address to, uint256 a) external { _mint(to, a); }
}

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

/// @notice Wave 2 froze `circulating()` at the TRANSACTION's first mint or burn. The same dilution runs as a bundle of
/// three transactions in one block (foundry `isolate = true`: every top-level call below is its own transaction, so the
/// transient mark clears between them): tx1 borrows 90,000 on a fresh high-rate position, tx2 redeems 9,000 against the
/// inflated supply, tx3 repays and takes the collateral back. The redeemer pays the fee and leaves the base rate that the
/// wave-2 test (AuditW2RedeemFeeBase) says an honest book must not allow. Cost: the borrow's upfront fee (7 days at the
/// type's average rate) and three transactions' gas; no flash loan, no price risk inside a bundle.
contract ProofFeeBaseBundleTest is Test {
    bytes32 constant ETH = "ETH";
    ImdUSD usd;
    Ledger ledger;
    Redeemer redeemer;
    PbTok weth;
    address alice = makeAddr("alice");
    address mallory = makeAddr("mallory");

    function setUp() public {
        vm.warp(1_800_000_000);
        usd = new ImdUSD(address(this), 100_000e18);
        Parameters params = new Parameters(makeAddr("gov"), address(this));
        Pricer pricer = new Pricer(params);
        Treasury treasury = new Treasury(makeAddr("gov"), 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 = new Redeemer(ledger);
        ledger.wire(address(redeemer), address(new Liquidator(ledger, pricer)));
        usd.wire(address(ledger), address(new Migrator(IERC20(address(new PbTok())), usd, params)), address(params));
        params.wire(address(ledger), address(usd));
        treasury.wire(ICoverable(address(ledger)));
        weth = new PbTok();
        Join join = new Join(address(weth), address(this));
        join.wire(address(ledger));
        PbFeed feed = new PbFeed(2000e18);
        params.addGenesisIlk(
            ETH,
            ParametersBase.Config({
                token: address(weth), join: address(join), median: feed, spot: feed, nhi: IFeed(address(0)),
                yieldRate: address(0), pegAggregator: address(0), liveSpot: IFeed(address(0)), redeemable: true,
                auction: false
            }),
            ParametersBase.Risk({
                mat: 1.5e18, 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();
        // The honest book: alice owes 90,000 at 5%.
        weth.mint(alice, 100e18);
        vm.startPrank(alice);
        weth.approve(address(ledger), type(uint256).max);
        ledger.open(ETH, 0, Adjust(100e18, 90_000e18, 0.05e18, 0, 0, false, type(uint256).max, address(0)));
        vm.stopPrank();
        vm.warp(block.timestamp + 30 days);
    }

    function test_threeTransactionBundleStillDilutesTheFeeAndBaseRate() public {
        uint256 amount = 9_000e18;
        uint256 supplyAtRest = usd.totalSupply();
        uint256 honestFee = redeemer.feeFor(ETH, amount);
        uint256 baseAtRest = redeemer.decayedBaseRate(ETH);
        uint256 honestOut = (amount * 1e18 / 2000e18) * (1e18 - honestFee) / 1e18;
        assertEq(honestFee, 0.05e18, "9,000 on 90,000 at divisor 2 is the 5% cap");

        weth.mint(mallory, 100e18);
        deal(address(usd), mallory, amount + 1_000e18);
        vm.startPrank(mallory);
        weth.approve(address(ledger), type(uint256).max);
        usd.approve(address(ledger), type(uint256).max);
        // tx1 (same block): borrow 90,000 at a high rate so the redemption never visits this position.
        uint256 id = ledger.open(ETH, 0, Adjust(100e18, 90_000e18, 0.5e18, 0, 0, false, type(uint256).max, address(0)));
        uint256 upfront = ledger.debtOf(id) - 90_000e18;
        // tx2 (same block): redeem 9,000. Its first burn marks circulating() at the INFLATED supply.
        uint256 feeSeen = redeemer.feeFor(ETH, amount);
        (, uint256 out) = redeemer.redeem(ETH, amount, 1e18, 1, 0);
        // tx3 (same block): repay and leave. Nothing of the borrow survives the block.
        ledger.adjust(id, Adjust(-100e18, -int256(ledger.debtOf(id)), 0, 0, 0, false, type(uint256).max, address(0)));
        vm.stopPrank();

        emit log_named_decimal_uint("honest fee (at rest)", honestFee, 18);
        emit log_named_decimal_uint("fee paid by the bundle", feeSeen, 18);
        emit log_named_decimal_uint("extra WETH taken", out - honestOut, 18);
        emit log_named_decimal_uint("cost: upfront fee on the 90,000 borrow", upfront, 18);
        (uint192 base,) = redeemer.rates(ETH);
        uint256 honestBase = baseAtRest + (amount * 1e18 / supplyAtRest) / 2;
        if (honestBase > redeemer.FEE_CAP()) honestBase = redeemer.FEE_CAP();
        emit log_named_decimal_uint("honest base rate after", honestBase, 18);
        emit log_named_decimal_uint("base rate left by the bundle", uint256(base), 18);

        assertApproxEqRel(usd.totalSupply(), supplyAtRest - amount, 0.01e18, "the borrow is gone again");
        assertEq(feeSeen, honestFee, "the fee of a redemption does not depend on debt that lives only inside its block");
        assertLe(out, honestOut, "no more collateral than an honest redemption pays");
        assertEq(uint256(base), honestBase, "the base rate rose by the redeemed share of the supply at rest");
    }
}
```

### 2. Info: Treasury header still says retireReserve is permissionless; it is governor-only since wave 2

`src/Treasury.sol:40`

```
/// @dev `coverBadDebt` and `retireReserve` are permissionless because both only burn the Treasury's own
/// imdUSD against liabilities, which can never make the system less solvent. Investing reserves (the
```

The contract-level docstring (src/Treasury.sol:40-42) names both coverBadDebt and retireReserve permissionless. retireReserve carries onlyGovernor (src/Treasury.sol:144) and its own docstring and the README trust model say governor only (wave 2). A reader of the trust model from the header is told the wrong caller set for the function that burns the bad-debt cover. Documentation only; behaviour is correct. Fix: reword lines 40-41 to say coverBadDebt is permissionless and retireReserve is the governor's. Merged from audit_permissions.

**Reproduction**

Read src/Treasury.sol:40-42 against src/Treasury.sol:144 (`function retireReserve(uint256 amount) external onlyGovernor`). Behaviourally (checked in test/scratch/GasPanel.t.sol, since removed): vm.prank(stranger); treasury.retireReserve(1) reverts NotGovernor(), while the header says anyone may call it.

### 3. Info: Parameters docstrings still say a type's redemption base rate starts at the cap; the Redeemer starts it at LISTING_BASE (0.5%) since wave 2

`src/Parameters.sol:329`

```
    /// The Redeemer starts each type's redemption base rate at its cap from this moment (launch at the cap).
```

Redeemer.LISTING_BASE = 0.005e18 and Redeemer.decayedBaseRate (src/Redeemer.sol:88-99) start a never-redeemed type at 0.5% from listedAt. The listedAt docstring (src/Parameters.sol:329) and the seal comment (src/Parameters.sol:322, 'a second seal would restart every type's redemption fee at the cap') describe the pre-wave-2 behaviour. Stale documentation of the launch fee (the README calls it the toll's wall). Fix: update both comments to LISTING_BASE / 0.5%. Merged from audit_permissions.

**Reproduction**

After params.seal() with no redemption, redeemer.decayedBaseRate(ilk) returns 0.005e18 decaying (Redeemer.sol:95 `base = LISTING_BASE`), not FEE_CAP (0.05e18) as the comment states; redeemer.feeFor(ilk, small) reads ~1.0% on a 0.5% redeemFloor at the seal (the panel's AuditW2* and Redemption tests pass with that figure).

### 4. Info: RateManager's ManagedPosition comment names the wrong eighth field of LedgerBase.Position (decoding itself is correct)

`src/managers/RateManager.sol:5`

```
/// first seven fields, in order; Position's eighth (`uint32 version`) is not read. A field inserted ahead of these in
```

Since the gas-driven layout, LedgerBase.Position (src/LedgerBase.sol:92-102) has nine fields: collateral, debt, rate, lastUpdate (uint40), lastRateChange (uint40), premiumRate, ilkIndex (uint16), yieldMark (uint192), version (uint32). ManagedPosition is the correct seven-field prefix (ABI types match, so the decoder accepts the longer return and the uint40 words validate), and RateManager reads only lastRateChange and rate; but the comment says the eighth field is `uint32 version`, which is now the ninth (the eighth is `uint192 yieldMark`). A maintainer trusting the comment at the next struct change would not see that the prefix rule, not the field count, protects the reads. Every other reader of Ledger.position (SeatJoin.sol:621/644, StockJoin.sol:118, LoopVault.sol:219/384/663, PegPositionZap.sol:29/196) uses the LedgerBase.Position type itself and decodes the new order correctly. Merged from audit_economics.

**Reproduction**

Read src/managers/RateManager.sol:4-6 against src/LedgerBase.sol:92-102: the comment's 'eighth (`uint32 version`)' is the struct's ninth member; the eighth is `uint192 yieldMark`. No failing behaviour (GasSlots.t.sol test_ilkOfAndListRateFollowTheLedger and the panel pass); a comment fix.

### 5. Info: Gas layout: Position.version shares slot 3 with yieldMark, so once a type's riskVersion is non-zero every open on a non-yield type creates an 8th storage slot (+22,100 gas now, +110,020 under Glamster

`src/LedgerBase.sol:101`

```
        uint32 version; // liquidation-risk version bound at the last risk-increasing action
```

Position packs slot 1 = collateral+debt (256 bits), slot 2 = rate(64)+lastUpdate(40)+lastRateChange(40)+premiumRate(64)+ilkIndex(16) = 224 bits, slot 3 = yieldMark(192)+version(32). On a type without yieldRate (every beta type but the ERC-4626 ones) yieldMark is never written, so slot 3 is written only by `p.version = uint32(params.riskVersion(ilk))` (src/Ledger.sol:297, src/LedgerSettlement.sol:287). While riskVersion is 0 (genesis) that write is zero-to-zero and GasSlots.t.sol's 7 new slots hold; after the first governed mat/chop change (riskVersion >= 1) every open with debt creates a third Ledger slot: measured 2 -> 3 new Ledger slots and +22,100 gas today, +110,020 at the Glamsterdam figures given, on every open for the life of the type. Moving `uint32 version` after `uint16 ilkIndex` fills slot 2 exactly (224 + 32 = 256 bits), keeps it in a slot the open writes anyway, changes no check, bound or invariant, keeps RateManager's 7-field ManagedPosition prefix intact (version becomes the 8th field, yieldMark the 9th), and the other readers (SeatJoin, StockJoin, LoopVault, PegPositionZap) read fields by name through the compiled struct. Not a defect: a measured layout item for question 6. Merged from audit_flow and audit_permissions (same mechanism, same fix).

**Reproduction**

Measured on c64ecee with test/scratch/GasPanel.t.sol (removed after the run; solc 0.8.26 via_ir, isolate = true, slots counted from vm.stopAndReturnStateDiff as GasSlots.t.sol does), ETH type mat 1.4, non-yield. Open of a later position by a first-time holder at riskVersion 0: 443,543 gas, 7 new slots (Ledger 2, PositionNFT 2, SortedPositions 2, ImdUSD 1), 11 updated. After a governed SET_RISK (chop 0.10 -> 0.11, applied after 48 h; params.riskVersion(ETH) = 1), the same open by another first-time holder: 508,539 gas, 9 new slots (Ledger 3, PositionNFT 2, SortedPositions 2, ImdUSD 1, plus 1 Treasury revenue-meter day bucket from the 2-day warp, unrelated), 12 updated; position.version = 1. Expected after the reorder: Ledger 2 at any version.

---

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