# Audit report

> AUDIT src/spokes/FixedLoans.sol: imdUSD lent against sIMD for a fixed term at a price governance sets; no feed, no liquidation; a hub spoke (read MinterHub.reportLoss: a lot's loss goes there).
>
> imdUSD v2 day 1, a CDP stablecoin (README: 'Day 1', known issues). NEW CODE: first public audit.
>
> BUILD (required; solc 0.8.38 via_ir; not the whole project): `forge test --match-path 'test/{unit/{FixedLoans*,AuditW6Fixed*}.t.sol,invariant/FixedInvariants.t.sol}'` (--use solar, then solc). Mutants (git checkout): `python3 -I test/fixtures/fixed-loans/mutants.py`. Fork: test/fork/FixedLoans.fork.t.sol (mainnet RPC, real sIMD). Say RAN (block, RPC) or NOT RUN per [fork] / [data] claim.
>
> PROPERTIES:
> P1 Until forfeit(id) (earliest: expiry + grace) anyone can burn a loan's debt and the borrower gets all its collateral in one transaction; no governance or hub state, other loan or sale blocks it; a repayment over the debt is clamped: a stranger's dust repayment cannot revert a full one.
> P2 Before expiry + grace nobody (governance included) can move, sell or reduce a loan's collateral, raise its debt or shorten its term.
> P3 openDebt + saleDebt == hub.rows(i).outstanding at all times; only open() mints, never past the cap (outstanding + bad + covered).
> P4 In any closed window T new debt <= dailyLimit x (1 + T / 1 day) (the largest in force in T) and <= surgeLimit between two affirm() calls; only time refills the bucket. No minimum: a stranger can use both up for the fee; extensions need neither.
> P5 A loan's terms are copied at open and replaced only when its borrower extends; no governance act changes an open loan or a lot.
> P6 A lot's price per share is a function of time only: lotDebt x startMultiple x 2^-(t / halfLife), floored at floorBps x lotDebt, over lotShares (fixed at forfeit); partial takes change no later buyer's price.
> P7 Loss per loan = debt - imdUSD burned for it, >= 0, reported in the transaction that ends the lot; the reserve's part stays covered inside used: the losses this spoke stands are at most its cap until imdUSD is repaid into the reserve or RELEASE_COVERED (48 h).
> P8 A lot brings at most its debt: the take that pays it off costs exactly the debt left, for at least one share, and every share not needed goes back to the borrower in that call; the spoke never holds imdUSD at rest.
> P9 Lend amount rounds down; fee and price round up; collateral released on a partial repayment rounds down; no sequence raises debt per share above its value at open or leaves debt with no collateral.
> P10 The spoke never calls withdraw or redeem on the collateral vault.
> P11 After expiry + grace anyone forfeits, anyone buys, after the sale anyone closes; given one caller a loan ends within its first term + the terms in force at each extension (at most maxExtensions then in force) + grace + saleLength.
> P12 A loan extends only in the last extendWindow() = min(3 days, term / 4) before expiry, at or above the minimum and at the lend price in force (debt above it burned from the borrower, no collateral released): the window is shorter than the term it adds, so extensions are never bought together.
>
> THREAT MODEL: the market (we are short a put: ACCEPTED, bounded by the cap); a borrower using a stale high lend price after a crash (bounded by P4 and the affirm period, 1-14 days, placeholder 7); a roller; a stranger using up bucket and surge; a sale griefer controls dust transfers (the sIMD one-block hold), front-running, being the lone buyer (the borrower buying her own lot: ACCEPTED); a block builder controls ordering; IMD's owner key minting IMD (ACCEPTED, bounded by P4); the Safe by mistake (lend price +25% per 48 h step; SET_TERMS / SET_LIMITS any size after 48 h; lower, pause, affirm at once); a stranger's repayReserve on the row; a donor to the sIMD vault. Cheapest coalition: a crash watcher + a stranger applying a matured raise the Safe forgot + a dust sender.
>
> PATH: open: debt = convertToAssets(shares) x lendPrice, hub.mint, fee to hub.payReserve + Treasury; repay / extend / take: pull imdUSD + hub.burn; a lot's end: hub.reportLoss -> the reserve burns at once (non-exotic rows first) -> covered, inside used (no room back); unsold shares to the Treasury, which the Safe sells to repayReserve. READERS: the hub row (exotic); the keeper (forfeit, close; alerts on affirm due, price over 0.4 x the 30-day low, surge or cap, lots, loss = bad + covered, Closed(loss > 0), hub-loss); the site (quote, quoteTake, openRoom, extendWindow). Launch: cannot lend (no row, unaffirmed, bucket empty); numbers PLACEHOLDER.
>
> CLAIMS TO CHECK:
> C1 Issues debt: open() ONLY. These reopen issuance, no other: affirm, UNPAUSE, SET_LIMITS, SET_LEND_PRICE, SET_TERMS; hub SET_CAP, SET_TOTAL_CAP, SET_EXOTIC_CAP, UNFREEZE, ADD_SPOKE, a burn, cover, repayReserve or RELEASE_COVERED on any row; a reserve-paid loss reopens nothing. None refills the bucket; only affirm resets the surge count.
> C2 The paying-off take's shares = min(asked, max(floor(debt x lotShares / price), 1)); the 10% minimum rest neither strands a lot nor delays the loss report past the sale.
> C3 Price maths: never under the formula (ours: 1e-18; header: 1e-25: measure), monotone, never under the floor, no overflow at uint128 debts and a 50x start; >= 32 half-lives give the floor.
> C4 Each instant lower drops the proposal that would undo it (pause: all four), also after a stranger applies a matured raise first.
> C5 (fixed) extend refuses (TooSmall) a loan under the minimum in force, paid down or not; none raises debt per share, passes maxExtensions or shortens a loan, at any term allowed (1-90 days).
> C6 [fork] Dust stamping the spoke each block delays only the receiver's unwrap a block (RedeemMoreThanMax()); convertToAssets never falls and rises only by IMD given to all holders.
> C7 [data] 0.4 x trailing 30-day low: 0 loss windows in 97 days of hourly IMD (one cycle); worst-decile replay 0% at 0.4 / 0.5, 2.1% at 0.6; placeholder 0.70 = 0.48 x low, lowered before the first affirm. The surge limit is the bound.
> C8 reserveShare is read at open and extend: a hub change or a reverting payReserve blocks only those; reportLoss never reverts or runs out of gas at 16 rows.
> C9 With a hooked collateral every money function is guarded; sIMD has no hooks.
> C10 (framing review r1; fixed by decision 1: P7) The cap bounds the loss: a reserve-paid close or sold-out take reopens no room (rows(i).covered, lossOf, keeper alerts) until repayReserve or RELEASE_COVERED.
>
> SOUNDNESS: Hub reserve / row room: 4 defects + 1 wrong assumption in 4 of 5 framing reviews (fixed: covered_s). One invariant: P7 over time. Extensions: 1 internal + 2 framing-review defects (fixed). Can a governed price with speed limits and no feed bound the loss below the cap? Tightest bound between two affirms; smallest change to tighten it.
>
> PROOF STANDARD: invariant tests over open, repay (part, full, for another), extend, forfeit, take (part, full), close, time and every governance and hub act in any order; fuzz prices, terms and 24-decimal shares.
>
> Answer each (break it or show it holds):
> 1. (P1, P2, P11) Repay, forfeit, the end.
> 2. (P3, P4) Issuance limits.
> 3. (P6, P7, P8, P9) The sale, the loss, rounding.
> 4. (P5, P12) Terms, extensions.
> 5. (P10) Unwraps, exits.
>
> Not findings: README 'Known issues' as written (worse than written IS one); test/, mocks; a PLACEHOLDER's size, unless a property fails at a value governance may set.
>
> Each finding: severity, file:line, call sequence, expected vs actual, reachable at deploy config?, smallest fix, a failing test RUN per BUILD, with output.

| | |
|---|---|
| Repository | https://github.com/imdusd/imdusd-v2-audit.git |
| Commit | `5719b27b9907113575dda2defe82e7ef9d52a877` |
| Job | `157d860f-dc22-4fa5-9ce4-a1683d3da28c` |
| Judged | 2026-12-01 16:08 UTC |
| Findings | 1 medium · 4 low · 3 info |

Four agents audited the code as it is at `5719b27`, 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: extend() overwrites the loan's grace with the one in force: a paid extension can bring the forfeit date (expiry + grace) EARLIER (C5 'none shortens a loan' and P2 fail at terms governance may set)

`src/spokes/FixedLoans.sol:547`

```
        l.grace = t.grace;
```

Merged from four specialists (ids 79f2f5bf, 10e81935, ae4c8ff1, 4ecffb2b); reproduced by the judge. extend() does `l.expiry += t.term;` (line 300) and then `_copyTerms(l, t)` (line 301), which replaces l.grace with the grace in force (line 547). forfeit() is gated only by expiry + grace (line 314), so the date from which anyone may take the collateral moves by t.term + t.grace - oldGrace, which is NEGATIVE whenever the loan's own grace is longer than the new term + the new grace. _checkTerms allows grace 12 h..14 days and term >= 1 day independently, so the date can move up to 12.5 days earlier, and the borrower pays the full extension fee for it. extend() has only `maxPay`: nothing lets her bound the result, and applyPending(SET_TERMS) is open to anyone, so a matured SET_TERMS can be applied in the block of her extend (the threat model's stranger / block builder). The suite's tests compare only `expiry`, never `expiry + grace`. Reachable at the deploy config? Not alone (grace 24 h < the smallest term + grace, 36 h): it needs a loan opened or extended under a grace above 36 h and a later SET_TERMS whose term + grace is below that grace (e.g. grace 7 d, then term 3 d / grace 1 d: 3 days lost), both values governance may set, which the brief counts. Impact: the borrower's own loss of time (she can still repay in full before the new date, or pay the debt as the lot's first taker); a keeper forfeits at once. Smallest fix (keeps 'an extension takes the terms in force' and P11's bound): in extend(), `uint256 was = uint256(l.expiry) + l.grace;` before `l.expiry += t.term;` and, after `_copyTerms(l, t);`, `if (uint256(l.expiry) + l.grace < was) l.grace = uint32(was - l.expiry);` (the kept grace is at most the old one). The judge applied exactly these two lines to a scratch copy of the contract: the attached test then passes (see reproduction).

**Reproduction**

State: SET_TERMS (term 14 d, grace 14 d, rest as deployed) applied; alice opens: forfeitable after expiry + 14 d = 1802764800. SET_TERMS (term 1 d, grace 12 h) applied (extendWindow() = 6 h). Call: 6 h before expiry alice calls extend(id, type(uint256).max) and pays the 1% fee. Expected (C5, P2): expiry + grace after the call >= 1802764800. Actual: 1801684800, 1,080,000 s (12.5 days) earlier. RUN by the judge (forge test --use solar --match-path test/scratch/Proof_10e81935dade.t.sol): `[FAIL: an extension brought the forfeit date earlier: 1801684800 < 1802764800] test_extendNeverBringsTheForfeitDateEarlier()`. The other two specialists' proofs fail the same way (`1801684800 < 1802764800`, and `1598401 < 2073601` for grace 7 d -> term 1 d / grace 12 h). Fix check RUN by the judge: the two lines of the fix applied to a scratch copy of FixedLoans.sol, the same test file pointed at it: `[PASS] test_extendNeverBringsTheForfeitDateEarlier()`. solc 0.8.38 via_ir: NOT RUN by the judge (solar only; the flow specialist reports the same failure under solc).

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {Test} from "forge-std/Test.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ImdUSD} from "src/ImdUSD.sol";
import {MinterHub} from "src/hub/MinterHub.sol";
import {IMinterHub} from "src/hub/IMinterHub.sol";
import {FixedLoans} from "src/spokes/FixedLoans.sol";

contract RvCode {}

/// @dev A hub spoke that only mints test imdUSD.
contract RvFaucet {
    MinterHub immutable hub;

    constructor(MinterHub h) {
        hub = h;
    }

    function mint(address to, uint256 amount) external {
        hub.mint(to, amount);
    }
}

/// @dev The collateral: 24-decimal shares, 8 underlying per 1.0 share, no hooks.
contract RvShares is ERC20("sIMD", "sIMD") {
    function decimals() public pure override returns (uint8) {
        return 24;
    }

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

    function convertToAssets(uint256 shares) external pure returns (uint256) {
        return shares * 8 / 1e6;
    }
}

contract FixedLoansReviewTest is Test {
    uint256 constant MAX = type(uint256).max;
    address governor = makeAddr("safe");
    address treasury = makeAddr("treasury");
    address alice = makeAddr("alice");
    address stranger = makeAddr("stranger");
    ImdUSD usd;
    MinterHub hub;
    RvShares simd;
    FixedLoans fl;

    function _terms(uint32 term, uint32 grace, uint8 maxExt) internal pure returns (FixedLoans.Terms memory) {
        return FixedLoans.Terms(term, grace, 100, maxExt, 80_000, 6 hours, 72 hours, 5_000);
    }

    function setUp() public {
        vm.warp(1_800_000_000);
        usd = new ImdUSD(address(this), 0, address(0));
        hub = new MinterHub(usd, governor, treasury, 5_000_000e18, 500_000e18, 500_000e18, 3);
        usd.wire(address(new RvCode()), address(hub), address(new RvCode()));
        simd = new RvShares();
        fl = new FixedLoans(
            IMinterHub(address(hub)), IERC20(address(simd)), treasury, governor, 0.7e18, _terms(14 days, 24 hours, 3),
            FixedLoans.Limits(1_000e18, 3_000e18, 50e18, 7 days)
        );
        RvFaucet faucet = new RvFaucet(hub);
        MinterHub.NewSpoke[] memory list = new MinterHub.NewSpoke[](2);
        list[0] = MinterHub.NewSpoke(address(faucet), 1_000_000e18, false, 0);
        list[1] = MinterHub.NewSpoke(address(fl), 10_000e18, true, 5_000);
        vm.prank(governor);
        hub.propose(abi.encode(uint8(0x10), list));
        skip(48 hours);
        hub.applyPending(0x10);
        faucet.mint(alice, 10_000e18);
        simd.mint(alice, 1_000e24);
        vm.startPrank(alice);
        simd.approve(address(fl), MAX);
        usd.approve(address(fl), MAX);
        vm.stopPrank();
        vm.prank(governor);
        fl.affirm();
    }

    function _setTerms(FixedLoans.Terms memory t) internal {
        vm.prank(governor);
        fl.propose(abi.encode(uint8(2), t));
        skip(48 hours);
        vm.prank(stranger);
        fl.applyPending(2);
        vm.prank(governor);
        fl.affirm();
    }

    /// @dev 1.0 share = 8 IMD = 5.6 imdUSD at 0.70: 20 shares borrow 112.
    function _open() internal returns (uint256 id) {
        vm.prank(alice);
        id = fl.open(20e24, 0);
    }

    /// C5 / P2: no extension brings the date a loan can be forfeited EARLIER. Fails: 12.5 days earlier.
    function test_extendNeverBringsTheForfeitDateEarlier() public {
        _setTerms(_terms(14 days, 14 days, 3)); // a long grace, allowed (12 h - 14 days)
        uint256 id = _open();
        _setTerms(_terms(1 days, 12 hours, 3)); // later: short terms, allowed (1 - 90 days, 12 h - 14 days)
        FixedLoans.Loan memory l = fl.loan(id);
        uint256 forfeitableBefore = uint256(l.expiry) + l.grace;
        vm.warp(l.expiry - fl.extendWindow());
        vm.prank(governor);
        fl.affirm();
        vm.prank(alice);
        fl.extend(id, MAX); // she pays a full fee
        l = fl.loan(id);
        assertGe(uint256(l.expiry) + l.grace, forfeitableBefore, "an extension brought the forfeit date earlier");
    }
}
```

### 2. Low: A stranger's partial repay decides the borrower's loan: it takes her extension away for good (TooSmall), and 1 wei in front reverts her own partial repayment

`src/spokes/FixedLoans.sol:258`

```
            if (rest < l.minDebt) revert TooSmall();
```

Merged from two specialists (ids c54cf8b1, e79502c5); reproduced. repay() lets ANYONE repay a loan in part, bounded only by the loan's copied minimum (line 258), and releases the same proportion of shares to the borrower. (a) extend() lends against the shares left (`fits = _lendable(l.shares)`, line 286) and refuses a debt under the minimum in force (line 295). There is no way to add collateral, so once a stranger's payment has pushed `fits` under the minimum the loan can never extend again: the borrower repays all of it before expiry + grace or is forfeited into the sale. It is cheap right after an instant lowerLendPrice (the expected act after a crash) for every loan whose debt at the new price is a few percent above minDebt, and after a SET_LIMITS that raised minDebt. The payment is a gift to the debt, so the cost is small; a lot buyer gains from the forced forfeit. (b) P1's clamp protects only a FULL repayment: a borrower's repay(id, debt - minDebt) reverts TooSmall after a stranger's repay(id, 1), each block for 1 wei + gas. No funds are lost and P1 as written holds. Reachable at the deploy config (minDebt 50e18, lend price 0.7) after one instant lowerLendPrice; (b) with no governance act. Smallest fix: only the borrower may repay in part, anyone may still repay in full (P1 unchanged): in repay's else-branch add `if (msg.sender != l.borrower) revert NotBorrower();`; for (b) alone, clamp instead of reverting (`amount = debt - l.minDebt`). The judge applied the first fix to a scratch copy: both tests of the attached proof then pass.

**Reproduction**

(a) Deploy numbers. alice opens 60e18; the Safe calls lowerLendPrice(0.6e18); in the extend window, control: alice.extend(id, max) succeeds (paid 9.0857e18). Instead first stranger.repay(id, 2e18) (rest 58e18 >= 50e18), then alice.extend(id, max): fits = 58 x 0.6 / 0.7 = 49.71e18 < 50e18. Expected: she can still extend. Actual: revert TooSmall(), at every later block. (b) alice has debt d >= 100e18 and sends repay(id, d - 50e18); stranger.repay(id, 1) in front. Expected: hers lands. Actual: TooSmall(). RUN by the judge (forge test --use solar --match-path test/scratch/Proof_c54cf8b110e7.t.sol): `[FAIL: TooSmall()] test_strangerPartialRepayTakesTheExtensionAway()` and `[FAIL: TooSmall()] test_dustInFrontRevertsAPartialRepayment()`. Fix check RUN by the judge (the borrower-only partial repay applied to a scratch copy): both tests `[PASS]`. solc 0.8.38 via_ir: NOT RUN by the judge (solar only).

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;

import {Test} from "forge-std/Test.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {ImdUSD} from "src/ImdUSD.sol";
import {MinterHub} from "src/hub/MinterHub.sol";
import {IMinterHub} from "src/hub/IMinterHub.sol";
import {FixedLoans} from "src/spokes/FixedLoans.sol";

contract HasCode {}

contract Imd is ERC20 {
    constructor() ERC20("IMD", "IMD") {}

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

/// 24-decimal vault shares over 18-decimal IMD, as sIMD.
contract Simd is ERC4626 {
    constructor(IERC20 a) ERC4626(a) ERC20("Staked IMD", "sIMD") {}

    function _decimalsOffset() internal pure override returns (uint8) {
        return 6;
    }
}

/// A plain hub spoke that hands out test imdUSD.
contract Faucet {
    MinterHub immutable hub;

    constructor(MinterHub h) {
        hub = h;
    }

    function mint(address to, uint256 amount) external {
        hub.mint(to, amount);
    }
}

/// A real ImdUSD + MinterHub + FixedLoans at the deploy config's numbers (script/DeployConfig.sol, EthConfig.fixedLoans).
abstract contract Base is Test {
    uint256 constant MAX = type(uint256).max;
    address governor = makeAddr("safe");
    address treasury = makeAddr("treasury");
    address alice = makeAddr("alice");
    address stranger = makeAddr("stranger");
    ImdUSD usd;
    MinterHub hub;
    Imd imd;
    Simd simd;
    FixedLoans fl;

    function _terms() internal pure returns (FixedLoans.Terms memory) {
        return FixedLoans.Terms(14 days, 24 hours, 100, 3, 80_000, 6 hours, 72 hours, 5_000);
    }

    function setUp() public {
        vm.warp(1_800_000_000);
        usd = new ImdUSD(address(this), 1_000_000e18, address(0));
        hub = new MinterHub(usd, governor, treasury, 5_000_000e18, 500_000e18, 500_000e18, 3);
        usd.wire(address(new HasCode()), address(hub), address(new HasCode()));
        imd = new Imd();
        simd = new Simd(IERC20(address(imd)));
        fl = new FixedLoans(
            IMinterHub(address(hub)), IERC20(address(simd)), treasury, governor, 0.7e18, _terms(),
            FixedLoans.Limits(1_000e18, 3_000e18, 50e18, 7 days)
        );
        Faucet faucet = new Faucet(hub);
        MinterHub.NewSpoke[] memory list = new MinterHub.NewSpoke[](2);
        list[0] = MinterHub.NewSpoke(address(faucet), 4_000_000e18, false, 0);
        list[1] = MinterHub.NewSpoke(address(fl), 10_000e18, true, 5_000);
        vm.prank(governor);
        hub.propose(abi.encode(uint8(0x10), list));
        skip(48 hours);
        hub.applyPending(0x10);
        address[2] memory who = [alice, stranger];
        for (uint256 i; i < 2; ++i) {
            faucet.mint(who[i], 100_000e18);
            imd.mint(who[i], 100_000e18);
            vm.startPrank(who[i]);
            imd.approve(address(simd), MAX);
            simd.deposit(100_000e18, who[i]);
            simd.approve(address(fl), MAX);
            usd.approve(address(fl), MAX);
            vm.stopPrank();
        }
        vm.prank(governor);
        fl.affirm();
    }

    /// @dev alice opens a loan of at least `debt` at the lend price in force.
    function _open(uint256 debt) internal returns (uint256 id) {
        uint256 assets_ = (debt * 1e18 + fl.lendPrice() - 1) / fl.lendPrice();
        uint256 shares = simd.convertToShares(assets_) + 1e7;
        vm.prank(alice);
        id = fl.open(shares, 0);
    }

    function _setTerms(FixedLoans.Terms memory t) internal {
        vm.prank(governor);
        fl.propose(abi.encode(uint8(2), t));
        skip(48 hours);
        vm.prank(stranger);
        fl.applyPending(2);
    }

    /// @dev To the first second of the loan's extend window, the price affirmed.
    function _toExtend(uint256 id) internal {
        vm.warp(fl.loan(id).expiry - fl.extendWindow());
        vm.prank(governor);
        fl.affirm();
    }
}

/// A stranger's partial repayment must not decide whether the borrower can extend, nor revert her own partial repayment.
/// Fails on the audited code (TooSmall); passes once only the borrower can repay in part (a stranger's partial `repay`
/// then reverts, which the try below allows) or once a stranger's payment no longer reaches `extend`'s minimum check.
contract F1StrangerRepayTest is Base {
    function test_strangerPartialRepayTakesTheExtensionAway() public {
        uint256 id = _open(60e18);
        vm.prank(governor);
        fl.lowerLendPrice(0.6e18); // instant, after a crash: the loan fits 51.43 >= the minimum 50
        _toExtend(id);
        uint256 snap = vm.snapshotState();
        vm.prank(alice);
        uint256 paid = fl.extend(id, MAX);
        emit log_named_decimal_uint("control: extend works, paid", paid, 18);
        vm.revertToState(snap);

        vm.prank(stranger);
        try fl.repay(id, 2e18) {} catch {} // rest 58 >= the loan's own minimum 50
        emit log_named_decimal_uint("debt now", fl.loan(id).debt, 18);
        vm.prank(alice);
        fl.extend(id, MAX); // 58 x 0.6 / 0.7 = 49.71 < 50: TooSmall, for good
    }

    function test_dustInFrontRevertsAPartialRepayment() public {
        uint256 id = _open(100e18);
        uint256 debt = fl.loan(id).debt;
        vm.prank(stranger);
        try fl.repay(id, 1) {} catch {}
        vm.prank(alice);
        fl.repay(id, debt - 50e18); // signed to leave exactly her minimum; after the 1 wei it leaves 1 wei less
    }
}
```

### 3. Low: affirm() does not bind the price it affirmed: a matured SET_LEND_PRICE anyone applies afterwards lends the whole surge (and every extension) at 1.25x the affirmed price; SOUNDNESS answer

`src/spokes/FixedLoans.sol:513`

```
            (, lendPrice) = abi.decode(payload, (uint8, uint128));
```

Merged from two specialists (ids 631e462e, 6b2a89b6); reproduced. affirm() means 'the Safe looked at the lend price' and opens lending for affirmEvery with a fresh surge count, but _apply(SET_LEND_PRICE) (line 513) changes lendPrice and leaves affirmedAt and issuedSinceAffirm untouched, and applyPending is open to anyone for 14 days after the ETA. The threat model's cheapest coalition works as written: a stranger applies the +25% raise the Safe forgot right AFTER its affirm (or in front of its lowerLendPrice, which would have dropped it), and the crash watcher borrows at 1.25x the affirmed price. SOUNDNESS. Can a governed price with speed limits and no feed bound the loss below the cap? No for debt already open: every open loan is a put struck at the price of its open or last extension and P2 forbids touching it, so the standing bound is the row's used (the cap, P7). The limits bound only NEW debt at a stale price: between two affirms new debt <= min(surgeLimit - issuedSinceAffirm, bucket + dailyLimit x affirmEvery / 1 day, hub room) = 3,000 of the 10,000 cap at the placeholders, and in any window T dailyLimit x (1 + T / 1 day). Extensions need neither bucket nor surge: inside one affirm period every loan in its window is rolled a full term at that price. The strike of all of it is NOT the affirmed price but up to 1.25x it: 0.875 instead of 0.70 = 0.60 x the 30-day low instead of 0.48, the level where C7's own replay stops being 0% (2.1% at 0.6). The same holds for a forgotten SET_LIMITS (a higher surgeLimit, or a longer affirmEvery that revives a stale affirm) applied by a stranger. C4 itself holds (each instant lower drops its proposal). Smallest change that tightens it: a raised price lends only once the Safe has looked at it: in _apply's SET_LEND_PRICE branch add `affirmedAt = 0;` (open and extend revert PriceStale until the next affirm; repay, forfeit, take, close never read it). Then the bound between two affirms is the surge at exactly the affirmed price. To bound the stock too, count an extension's debt in issuedSinceAffirm (a design decision). Not a permission bypass: the raise is the Safe's own proposal. Reachable at the deploy config: yes. JUDGE'S RUN LOG (all findings): BUILD suites RAN with forge 1.9.0 --use solar (Solar 0.8.38): 7 suites, 70 passed, 0 failed. solc 0.8.38 via_ir: NOT RUN to the end (the whole-tree solc build did not finish within 10 minutes here; every reproduction was RUN under solar). Mutants (mutants.py): NOT RUN. [fork] C6: RAN, test/fork/FixedLoans.fork.t.sol 4 of 4 passed against real sIMD on mainnet at the head block (26,536,344 read just before the run; not pinned), RPC https://ethereum-rpc.publicnode.com as the specialists name it: a stamp on the spoke in every block blocks no repay / extend / take / close, an unsold lot closes under a stamp, a donation changes no debt and no shares. [data] C7: NOT RUN independently (only the repository's FixedLoansReplay tests, 4 passed). Held, checked against the code: P3 (the suite's invariant and _assertBooks), P10 (no withdraw / redeem call in the file), C9 (all six money functions are nonReentrant), C1's lists, C2 (take-all always executes), C4, C8, C10 (reportLoss leaves used unchanged).

**Reproduction**

Deploy config (0.70, surge 3,000, affirm every 7 days). The Safe proposes SET_LEND_PRICE 0.875e18 and leaves it; 10 days later (inside 48 h + 14 days) it calls affirm() at 0.70. A stranger calls applyPending(1); alice opens 100e24 shares (800 IMD). Expected under 'affirm = the Safe looked at the lend price': debt <= 800 x 0.70 = 560e18 until the next affirm. Actual: 699.999999999999999999e18 (0.875 per IMD), and so for the rest of the surge limit and every extension in the period. RUN by the judge (forge test --use solar, scratch test on the repository's FixedBase): `[FAIL: lent above the affirmed price: 699999999999999999999 > 560000000000000000000] test_F_affirmedPeriodLendsAtAPriceNotAffirmed()`.

### 4. Low: open() and extend() bind the caller to whatever Terms are in force when the transaction lands: a matured SET_TERMS applied in front gives a 1-day loan to a borrower quoted 14 days (minOut / maxPay bou

`src/spokes/FixedLoans.sol:234`

```
        l.expiry = uint40(block.timestamp + t.term);
```

From the flow specialist (id a1aeb35f; the permissions specialist noted the same gap); reproduced. applyPending(SET_TERMS) is permissionless once matured and stays applicable for 14 days. open(shares, minOut) and extend(id, maxPay) read `_terms` at execution (lines 227 and 279); the caller's only bounds are on the money, not on what is bought: the term, the grace, maxExtensions and the sale terms copied into the loan for good (P5). With an unchanged feeBps the minOut check passes and the borrower holds a loan with another expiry than quote() / terms() showed her (14 days -> 1 day: repay within 36 h or lose the collateral to the sale, maxExtensions possibly 0), or spends one of her extensions on 1 day instead of 14 at the same fee. minOut is also only a floor on the amount: a matured SET_LEND_PRICE raise applied in front lends 25% more debt (and its fee) against the same shares. The 48 h timelock makes the change public, but no transaction can refuse it. Reachable at the deploy config with any pending SET_TERMS. Smallest fix: one more argument on both, `uint40 minExpiry` (`if (l.expiry < minExpiry) revert`), or the keccak of the Terms the caller saw, returned by quote(). No proof file: the fix changes the functions' signatures.

**Reproduction**

State: deploy terms (14 d, fee 1%); the Safe proposed SET_TERMS (term 1 d, grace 12 h, maxExtensions 0, fee 1%) 48 h ago, not applied. alice reads quote(shares) -> out and terms().term = 14 days and sends open(shares, out). In front a stranger calls applyPending(2). Expected: her open reverts or her loan expires at now + 14 days (1801555200). Actual: it succeeds, minOut met, loan.expiry = now + 1 day (1800432000). RUN by the judge (forge test --use solar, scratch test on FixedBase): `[FAIL: the loan's term is not the one quoted: 1800432000 != 1801555200] test_B_openCannotBeGivenAnotherTermInFront()`.

### 5. Low: P12 fails across a SET_TERMS apply: two extensions bought in one block at one lend price (the window is taken from the term in force, not the loan's)

`src/spokes/FixedLoans.sol:283`

```
        if (l.expiry - block.timestamp > _window(t.term)) revert ExtendTooEarly();
```

Merged from two specialists (ids 7e8fb827, af44c2d0); reproduced. The 'too early' check compares the time left with the window of the term IN FORCE NOW. P12's argument (the window is shorter than the term it adds) holds only while the terms do not change between two extensions. After an extension under a short term (r + term1 <= 3 days), a SET_TERMS to a term >= 4 x (r + term1) widens the window and the loan is inside it again: the borrower calls extend, applyPending(SET_TERMS) (anyone may), extend in one transaction; both extensions are checked against the same lend price in the same block, the 'one long put' the header's P13 says cannot be bought ('whatever the term SET_TERMS allows'). testFuzz_W4_extensionsCannotBeBoughtTogether fuzzes one constant term only. Bounded: one extra short term per SET_TERMS apply (48 h apart), each fee paid, maxExtensions and P11's bound respected. Not reachable at the deploy terms alone (14 days > 3 days); reachable at terms SET_TERMS allows (a 1-3 day term followed by a longer one). Smallest fix: copy the window into the loan with its terms (`l.window = uint32(_window(t.term))` in _copyTerms) and require `l.expiry - block.timestamp <= min(l.window, _window(t.term))`; or store the time of the last extension and refuse a second one before `_window(t.term)` has passed.

**Reproduction**

SET_TERMS (term 2 days) applied; the Safe proposes SET_TERMS (term 90 days) and leaves it. 12 h later alice opens 500 imdUSD (expiry in 2 days, window 12 h). 36 h later (proposal mature, loan in its window, price affirmed) alice, in one block: extend(id, max) -> 216,000 s left; applyPending(2); extend(id, max). Expected: the second extend reverts ExtendTooEarly (P12). Actual: it succeeds: 7,992,000 s (92.5 days) left, extensions == 2. RUN by the judge (forge test --use solar, scratch test on FixedBase): `[FAIL: next call did not revert as expected] test_C_twoExtensionsAreNeverBoughtInOneBlock()`, logs `left after the first extension 216000`, `left after the second extension 7992000 extensions 2`.

### 6. Info: A one-raw-share take in front (1 wei of imdUSD) reverts any partial take sized to the 10% minimum rest; only take-all is immune (C2 itself holds)

`src/spokes/FixedLoans.sol:341`

```
        } else if (rest * 10_000 < uint256(l.lotShares) * MIN_REST_BPS) {
            revert TooSmall();
```

From the flow specialist (id 8c26b4aa); reproduced. A take that neither pays the debt off nor sells the lot out reverts TooSmall when it would leave under 10% of lotShares. `shares` is absolute, so the largest allowed partial take (l.shares - 10% of lotShares) is invalid as soon as anyone takes one raw share in front (1 wei at 24-decimal shares, plus gas, repeatable each block). C2 holds: take(id, type(uint256).max, maxPay) is clamped to what is left and always executes, so no lot is stranded and no loss report is delayed past the sale. But a buyer who will not buy the whole rest is kept out for as long as the griefer pays gas, which thins competition while the price falls (the lone-buyer position, bought for dust); quoteTake does not check the rule, so the site cannot show it. Smallest fix: clamp instead of reverting: lower `taken` to `l.shares - ceil(lotShares x MIN_REST_BPS / 10_000)` (revert only if that is 0) and price that amount.

**Reproduction**

A forfeited lot (debt 100e18) 30 h into the sale, untouched. Control: bob.take(id, lotShares * 9 / 10, max) succeeds. Instead a stranger first calls take(id, 1, max) and pays 1 wei; bob's same take then reverts. Expected: bob's take executes (or is clamped to leave 10%). Actual: TooSmall(). RUN by the judge (forge test --use solar, scratch test on FixedBase): `[FAIL: TooSmall()] test_E_dustTakeInFrontRevertsAPartialTake()`, log `griefer pays (wei) 1`.

### 7. Info: feeBps has no lower bound: at feeBps = 0 (allowed by _checkTerms) a stranger uses up the bucket and the surge limit for gas alone (worse than the known issue 'for the fee')

`src/spokes/FixedLoans.sol:612`

```
            t.term < 1 days || t.term > 90 days || t.grace < 12 hours || t.grace > 14 days || t.feeBps > 1_000
```

From the math specialist (id 6b743202); reproduced. P4 and the README's known issue price the exhaustion of the bucket and the surge limit at 'the fee'. _checkTerms bounds feeBps only from above, and ceil(debt x 0 / 10_000) = 0, so with SET_TERMS feeBps = 0 an open() followed by repay(id, max) in one transaction costs no imdUSD and no shares and still spends the bucket and counts in issuedSinceAffirm (only affirm resets it). Once a day it keeps openRoom() at 0; after surgeLimit of such opens nobody borrows until the next affirm. With any feeBps >= 1 the round-up makes the fee at least 1 wei per open and the documented cost holds. Not reachable at the deploy config (feeBps 100); reachable at a value governance may set. Smallest fix: `t.feeBps == 0 ||` in _checkTerms, or say in the known issue that the cost is zero at a zero fee.

**Reproduction**

SET_TERMS with feeBps = 0 applies; affirm. stranger: id = open(sharesFor(999e18), 0); repay(id, type(uint256).max) in the same block. Expected (P4 / README): using up the bucket costs the fee. Actual: imdUSD cost 0, sIMD cost 0, openRoom() == 0. RUN by the judge (forge test --use solar, scratch test on FixedBase): `[FAIL: using up the bucket cost nothing: 500000000000000000000000 >= 500000000000000000000000] test_G_zeroFeeExhaustionCostsSomething()`, logs `openRoom left 0`, `sIMD cost 0`.

### 8. Info: C3 measured: the lot price is never under the formula, monotone and overflow-free, but '(within 1e-25 of the formula)' holds only for the multiplier; the price is within 1 wei, up to 4e-18 relative (a

`src/spokes/FixedLoans.sol:589`

```
    /// rounded up (within 1e-25 of the formula). 2^-(dt/h) = 2^-(n + 1) x e^(ln2 x (h - r) / h) with n, r = dt divmod h; the
    /// exponential by its series (every term positive and rounded down, so it is monotone; + 32 units = more than was lost).
```

From the math specialist (id 1451337c); re-measured by the judge with an exact integer replica of _lotPrice against 120-digit decimals (20,000 random and edge points: halfLife 1 h-7 d, dt at 0, 1, h-1, h, h+1, 31h, 32h-2 and random, debts 1e18..2^128-1, startMultiple 1x-50x). C3 holds where it matters: price under the formula 0 cases; the series sum under e^y 0 cases; rising with time 0 cases (dt -> dt+1, across half-life boundaries); at most 24 iterations; debt x startMultiple x s at most 238 bits (no overflow at uint128 debts and 50x); at 32 half-lives the price is the floor. The multiplier is at most 3.2e-26 over (the header's 1e-25 is right for it). But the final Math.ceilDiv (line 606) adds up to 1 wei, so the PRICE is within 1e-25 only for lots above about 1e25 wei: at the deploy config (debt 50e18, 8x, 6 h) the worst relative excess is 4.9e-20; at the smallest values _checkLimits / _checkTerms allow (minDebt 1e18, 1x, floor 25%) it is 3.98e-18, above the brief's 'ours: 1e-18'. Nobody loses by it (the rounding is against the buyer, under 1 wei per lot); the defect is the stated bound. Smallest fix: the comment and the claim: 'rounded up: within 3.3e-26 of the formula plus 1 wei' (a 1e-18 relative bound needs a floor price of at least 1e18 wei, i.e. minDebt x floorBps / 10_000 >= 1e18).

**Reproduction**

Input: lotDebt = 1e18, startMultipleBps = 10_000, halfLife = 3600, block.timestamp - saleStart = 7175, floor 25%: _lotPrice returns 251206281423816967; the formula 1e18 x 2^-(7175/3600) is 251206281423816966.00057: relative excess 3.979e-18. Expected by the header: within 1e-25 (by the brief: 1e-18). Deploy config (50e18, 80_000, 21600), dt in [1 s, 26 h]: worst 4.932e-20. RUN by the judge off chain (Python integer copy of lines 591-608 against decimal arithmetic at 120 digits); output: `points 20000 under 0 nonmono 0 max iterations 24 max bits of the product 238`, `worst rel multiplier excess 3.192e-26`, `deploy config worst 4.932e-20`, `251206281423816967 251206281423816966.00056701388 3.979e-18`, `32 half-lives: True`.

---

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