{
 "item": "brake-fee-base",
 "commit": "ff1c192b3798542997f600091f2dc73ff05e4c40",
 "forge": "forge 1.9.0, --use solar (Solar 0.8.38); scratch tests only (--match-path test/scratch/*.t.sol), --fuzz-runs 1000-3000",
 "verdict": "findings",
 "findings": [
  {
   "id": "BFB-1",
   "severity": "low",
   "title": "Third gas-only round trip: the Morpho allocator's withdraw (hub.burn) then supply (hub.mint) lowers feeBase by the amount for 1-2 h; README:620 names only the Migrator and the bridge",
   "property": "P1/P3 cost bound of C2 (fee-free round trips bounded as README:620-631 states)",
   "claim": "C2, C3",
   "files": [
    "src/morpho/MorphoLender.sol:151",
    "src/morpho/MorphoLender.sol:158",
    "src/morpho/MorphoLender.sol:166",
    "src/morpho/MorphoLender.sol:415",
    "src/ImdUSD.sol:255",
    "src/ImdUSD.sol:216",
    "src/LedgerBase.sol:348",
    "src/Redeemer.sol:141",
    "README.md:626"
   ],
   "sequence": "Chain 4663. Lender row 0 has principal P (100k) supplied >2 buckets ago. tx1 (allocator hot key): lender.withdraw(0,x) -> _exit -> hub.burn(x). tx2 (same or next block): lender.supply(0,x) -> hub.mint(x). Supply returns to its old value, the allocator pays nothing (no fee on either leg; Morpho interest for one block only), but _noteStart recorded tx2's start supply S-x, so feeBase() = S-x for the rest of the bucket and the next; repeatable every bucket to hold it down indefinitely, bounded by Σ row principal and each market's idle liquidity.",
   "expected": "README:626 (quoted: 'repay is free) or the stable module's exit and mint fees, and GAS ONLY through two fee-free routes: the Migrator (`toV1` then') lists the only gas-only routes: Migrator (<= outstanding) and a feeBps-0 bridge path. Any other round trip costs an upfront fee or module fees.",
   "actual": "feeBase falls from 750,003e18 to 651,003e18 after a 99,000e18 allocator round trip with the allocator's balance and the row's principal unchanged: the core brake (allowed = unbackedBrake x feeBase) trips on a ~13% smaller base and every redemption's fee ramp / base-rate rise divides by the smaller figure (redeemers pay more) for 1-2 h, at gas cost, by an actor the threat model lists (the Morpho allocator) and not covered by README:620.",
   "reachableAtDeploy": true,
   "fix": "Either state the lender as a third gas-only route in README:620 with its bound (Σ lender caps x idle), or make lender supply/withdraw not cheap to cycle: e.g. refuse a supply on a row in the same FEE_BASE_WINDOW bucket as its last withdraw (and vice versa), or have the hub count a spoke's burn-then-mint within one bucket as no fall (net per-spoke flow per bucket) before _noteStart sees it.",
   "test": {
    "source": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {LenderBase} from \"../utils/LenderBase.sol\";\n\n/// C2 (a cheaper grief): the Morpho allocator's withdraw (hub.burn) then supply (hub.mint) in two txs is a third fee-free\n/// round trip, not among README:620's two (Migrator, bridge): it lowers feeBase by the amount for 1-2 h for gas only.\ncontract LenderRoundTripTest is LenderBase {\n    function testFuzz_C2_allocatorRoundTripLowersFeeBaseForGas(uint256 x) public {\n        _supply(0, 100_000e18);\n        _pass(3 hours);\n        uint256 fb = usd.feeBase();\n        x = bound(x, 1e18, 99_000e18);\n        uint256 balA = usd.balanceOf(allocator);\n        uint256 prin = _principal(0);\n        vm.prank(allocator);\n        lender.withdraw(0, x); // tx1: burns x\n        vm.roll(block.number + 1);\n        vm.prank(allocator);\n        lender.supply(0, x); // tx2 (next block or same block): mints x back\n        assertEq(_principal(0), prin, \"position restored\");\n        assertEq(usd.balanceOf(allocator), balA, \"no fee paid by the allocator\");\n        // P1 lower-bound side as documented in README:620 covers only Migrator + bridge as gas-only routes\n        assertEq(usd.feeBase(), fb, \"C2: feeBase lowered by a fee-free allocator round trip\");\n    }\n}\n",
    "ran": "forge test --use solar --match-path test/scratch/LenderRoundTrip.t.sol (uses the repo's test/utils/LenderBase.sol: real ImdUSD + MinterHub + MorphoLender + Morpho)",
    "result": "[FAIL: C2: feeBase lowered by a fee-free allocator round trip: 651003000000000000000000 != 750003000000000000000000; counterexample: x = 99000e18] (also failed for every other x tried, e.g. 1673.0e18 -> 748328990849846855406646 != 750003000000000000000000)"
   }
  },
  {
   "id": "BFB-2",
   "severity": "info",
   "title": "A record of 0 reads as none not only at launch: whenever the supply at a minting/burning tx start is 0 again, a fresh mint counts in feeBase at once",
   "property": "P1 Down (outside the record-0 window, supply minted in the current bucket never counts before it stood across a bucket boundary)",
   "claim": "C4",
   "files": [
    "src/ImdUSD.sol:225",
    "src/ImdUSD.sol:255",
    "README.md:629-631"
   ],
   "sequence": "Spoke chain (Base / 4663) long after launch, supply S held by bridgers/borrowers. tx1: the last units leave (bridge send / repay) -> supply 0. tx2 same bucket: a mint of M (bridge claim, hub spoke, borrow). _noteStart records low 0, feeBase() reads m == 0 as 'no record' and returns circulating() = M.",
   "expected": "README:630 limits it to 'for the first 1-2 h of each chain's launch (Base and Robinhood Chain: from the first bridge claim)'; P1: M must not count before it stood across a bucket edge (figure 0 -> brake allowed 0, fee at cap).",
   "actual": "feeBase() = 1,000,000e18 in the same bucket as the mint, 5 h after launch.",
   "reachableAtDeploy": true,
   "fix": "Store at+1 in the record (0 stays 'no record', a true 0 low is kept) or add a 'recorded' bit; or document that the window reopens whenever the chain's supply returns to 0.",
   "test": {
    "source": "see BFB-3-model below: test_C4_zeroRecordRecursAfterLaunch in FeeBaseModel.t.sol (same file as the holds fuzz)",
    "ran": "forge test --use solar --match-path test/scratch/FeeBaseModel.t.sol",
    "result": "[FAIL: P1: 1,000,000 minted this bucket counts at once: 1000000000000000000000000 != 0] test_C4_zeroRecordRecursAfterLaunch() (gas: 273293)"
   }
  }
 ],
 "claims": [
  {
   "id": "C1",
   "result": "holds",
   "evidence": "grep src/ script/: _lows (ImdUSD.sol:63) written only in _noteStart (ImdUSD.sol:255), called only from _update (ImdUSD.sol:232) when the transient TX_SUPPLY_SLOT is 0, i.e. once per tx at its first mint/burn (flashLoan's _mint included); read only by feeBase (ImdUSD.sol:216). The other `_lows` in src/house/feeds/ImdDepth.sol:59 is a different contract. No hits in script/. Model fuzz testFuzz_feeBaseMatchesModel (3000 runs) confirms."
  },
  {
   "id": "C2",
   "result": "refuted",
   "evidence": "A cheaper grief than 'one upfront fee or module fees' exists outside the two fee-free routes README:626 names: the Morpho allocator's withdraw->supply (BFB-1), gas only, repeatable each bucket. Stable module: its curve has 'free while empty: refilling costs nothing' (StableModule.sol:27) so a round trip's cost depends on governed feeMin/mintFeeMax; not tested further (not-checked)."
  },
  {
   "id": "C3",
   "result": "holds",
   "evidence": "Migrator: testFuzz_C3_migratorRoundTripBounded (1000 runs, real Migrator + hub): toV1(y) then toV2(y) lowers feeBase by exactly y, and toV1 above outstanding reverts; effect lasts the rest of the bucket + next (model fuzz). Bridge: send burns amount, mints amount-delivered to treasury (ImdBridge.sol:520-523), so at feeBps 0 the fall equals the round trip, bounded by outbound room (repo test AuditW7JudgeBridgeFeeBase.t.sol, not re-run here). Both routes stack with each other and with BFB-1 (independent bounds)."
  },
  {
   "id": "C4",
   "result": "refuted",
   "evidence": "Not only the first 1-2 h of a chain: any time the supply at a minting/burning tx start is 0 (BFB-2, failing test). At launch it matches README:629-631."
  },
  {
   "id": "C5",
   "result": "holds",
   "evidence": "testFuzz_C5_flashDoesNotMoveCirculating (1000 runs): inside onFlashLoan circulating() == tx-start supply for any loan size; LedgerBase.sol:286 reads circulating(). A burn one tx earlier raises uptake (README:632-633, known as written, capped by the savings share)."
  },
  {
   "id": "C6",
   "result": "holds",
   "evidence": "Invariant (checked by testFuzz_feeBaseMatchesModel, 3000 runs x 16 ops: mint, burn, burn+mint in one tx, mint+burn in one tx, flash loan with burn+re-mint inside, time-only; same block, +12 s, exact bucket edge, last second of a bucket, up to 3 h): for every tx boundary t, feeBase() == min(totalSupply, S(start of bucket b-1), S(start of bucket b), S at the start of every minting/burning tx in buckets b-1 and b), with b = now/1h, except when that min is 0 (BFB-2). Every supply-moving route (Ledger, hub spokes incl. Migrator and lender, bridge, flash) goes through ImdUSD._update, so this one invariant covers them all. Smallest replacement for its 0 hole: store low+1."
  }
 ],
 "holds": [
  {
   "property": "P1 Down",
   "tried": "Model fuzz above (3000 runs): minted supply never raised feeBase above the model's minimum of standing supplies over prev+cur bucket, in any order (mint before a fall, refill after a fall, several txs per block, consecutive blocks, bucket edge/last second). Holds except the 0-record case (BFB-2)."
  },
  {
   "property": "P2 Up",
   "tried": "Model fuzz kinds burnMint / mintBurn / flash(burn+re-mint inside the loan) in one tx: feeBase and circulating unchanged vs model in all 3000 runs (transient TX_SUPPLY_SLOT records only the tx-start supply)."
  },
  {
   "property": "P3 Liveness",
   "tried": "testFuzz_P3_brakeExactAndRepayDepositLive (1000 runs, real Ledger + hub, exotic loss 0-100k reported via the house spoke, 0-3 h elapsed): a borrow is refused (Braked) iff reading = (bad - Treasury imdUSD) + hub.unbacked() - min(exoticMargin, exoticUnbacked()) > unbackedBrake x feeBase(); deposit and repay succeed in every state. Code: _checkBrake is called only at Ledger.sol:271 (debt increase) and LedgerSettlement.sol:243 (charged rate change); redeemPosition (LedgerSettlement.sol:58), liquidatePosition (:105) and Redeemer.redeem never call it. LedgerBase.unbacked() (LedgerBase.sol:221-225) applies no margin."
  }
 ],
 "notRun": [
  "[fork]/[data]: none in this sheet; NOT RUN",
  "Bridge round trip re-run (relied on repo test AuditW7JudgeBridgeFeeBase.t.sol, not executed here)",
  "Stable-module round-trip cost at governed fee values (feeMin / mintFeeMax = 0)",
  "Liquidation and redemption under the brake were checked by code reading, not by a test"
 ],
 "tests": {
  "FeeBaseModel.t.sol": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {Test} from \"forge-std/Test.sol\";\nimport {ImdUSD} from \"../../src/ImdUSD.sol\";\nimport {IERC3156FlashBorrower} from \"@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol\";\n\ncontract HasCode2 { function governor() external pure returns (address) { return address(1); } }\n\n/// Stands in for every minter route (hub spoke, Ledger, bridge): any mint / burn mix inside ONE transaction.\ncontract Minter is IERC3156FlashBorrower {\n    ImdUSD usd;\n    constructor(ImdUSD u) { usd = u; }\n    function setToken(ImdUSD u) external { usd = u; }\n    function mint(uint256 a) external { usd.mint(address(this), a); }\n    function burn(uint256 a) external { usd.burn(address(this), a); }\n    function burnMint(uint256 a, uint256 m) external { usd.burn(address(this), a); usd.mint(address(this), m); }\n    function mintBurn(uint256 m, uint256 a) external { usd.mint(address(this), m); usd.burn(address(this), a); }\n    function flashBurn(uint256 f, uint256 a) external {\n        usd.approve(address(usd), type(uint256).max);\n        usd.flashLoan(this, address(usd), f, abi.encode(a));\n    }\n    function onFlashLoan(address, address, uint256, uint256, bytes calldata d) external returns (bytes32) {\n        uint256 a = abi.decode(d, (uint256));\n        usd.burn(address(this), a); // burn + re-mint inside the loan: a refinance in one tx\n        usd.mint(address(this), a);\n        return keccak256(\"ERC3156FlashBorrower.onFlashLoan\");\n    }\n}\n\ncontract FeeBaseModelTest is Test {\n    uint256 constant W = 1 hours;\n    ImdUSD usd;\n    Minter m;\n    // model: per minting/burning tx (bucket, supply at tx start, supply after)\n    uint256[] txB; uint256[] txPre; uint256[] txPost;\n\n    function setUp() public {\n        vm.warp(1_800_000_000);\n        usd = new ImdUSD(address(this), 1e30, address(0));\n        m = new Minter(usd);\n        usd.wire(address(new HasCode2()), address(m), address(new HasCode2()));\n    }\n\n    function _startOf(uint256 k) internal view returns (uint256 s) {\n        for (uint256 i; i < txB.length; ++i) if (txB[i] < k) s = txPost[i];\n    }\n\n    /// The property's figure: min(circulating, supply at the start of the previous and the current bucket, the supply\n    /// standing at the start of every minting/burning tx in those two buckets).\n    function _expected() internal view returns (uint256 e) {\n        uint256 b = block.timestamp / W;\n        e = usd.totalSupply();\n        uint256 s0 = _startOf(b - 1);\n        uint256 s1 = _startOf(b);\n        if (s0 < e) e = s0;\n        if (s1 < e) e = s1;\n        for (uint256 i; i < txB.length; ++i) if (txB[i] + 1 >= b && txPre[i] < e) e = txPre[i];\n    }\n\n    function _note(uint256 pre) internal {\n        txB.push(block.timestamp / W); txPre.push(pre); txPost.push(usd.totalSupply());\n    }\n\n    /// C6 / P1 / P2 / C1: over any order of mints, burns, same-tx round trips and flash loans, several per block and over\n    /// consecutive blocks and bucket edges, feeBase equals the model after every tx (a model figure of 0 aside: C4).\n    function testFuzz_feeBaseMatchesModel(uint256[16] calldata ops) public {\n        m.mint(1_000_000e18); _note(0);\n        vm.warp(block.timestamp + 3 * W);\n        bool sawZero;\n        for (uint256 i; i < 16; ++i) {\n            uint256 o = ops[i];\n            uint256 kind = o % 6;\n            uint256 bal = usd.balanceOf(address(m));\n            uint256 amt = bound(o >> 8, 0, bal + 100e18);\n            uint256 dt = (o >> 200) % 5; // 0: same block; else up to ~1.5 h, edges hit with W multiples\n            if (dt == 1) vm.warp(block.timestamp + 12);\n            else if (dt == 2) vm.warp((block.timestamp / W + 1) * W); // exactly at a bucket edge\n            else if (dt == 3) vm.warp((block.timestamp / W + 1) * W - 1); // last second of the bucket\n            else if (dt == 4) vm.warp(block.timestamp + ((o >> 180) % (3 * W)));\n            vm.roll(block.number + (dt == 0 ? 0 : 1));\n            uint256 pre = usd.totalSupply();\n            if (kind == 0) { if (amt == 0) continue; m.mint(amt); }\n            else if (kind == 1) { amt = amt > bal ? bal : amt; if (amt == 0) continue; m.burn(amt); }\n            else if (kind == 2) { amt = amt > bal ? bal : amt; if (amt == 0) continue; m.burnMint(amt, amt); }\n            else if (kind == 3) { if (amt == 0) continue; m.mintBurn(amt, amt); }\n            else if (kind == 4) { amt = amt > bal ? bal : amt; if (amt == 0) continue; m.flashBurn(1e18, amt); }\n            else { /* time only */ }\n            if (kind != 5) _note(pre);\n            uint256 e = _expected();\n            if (e == 0) { sawZero = true; continue; }\n            assertEq(usd.feeBase(), e, \"feeBase != min of standing supplies (prev+cur bucket)\");\n            assertLe(usd.feeBase(), usd.circulating());\n        }\n    }\n\n    /// C4 beyond launch: whenever the supply standing at a tx start is 0 again (every holder on a spoke chain bridged\n    /// out), the record reads as none and a fresh mint counts at once (P1), not only in a chain's first 1-2 h.\n    function test_C4_zeroRecordRecursAfterLaunch() public {\n        m.mint(100e18);\n        vm.warp(block.timestamp + 5 * W); // launch window long over\n        vm.roll(block.number + 1);\n        assertEq(usd.feeBase(), 100e18);\n        m.burn(100e18); // tx1: every unit leaves (bridge send)\n        vm.roll(block.number + 1);\n        m.mint(1_000_000e18); // tx2, same bucket: fresh supply after a fall to 0\n        vm.roll(block.number + 1);\n        // P1: supply minted in the current bucket never counts before it stood across a bucket edge\n        assertEq(usd.feeBase(), 0, \"P1: 1,000,000 minted this bucket counts at once\");\n    }\n}\n",
  "BrakeLiveness.t.sol": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {LedgerBase} from \"../../src/LedgerBase.sol\";\nimport {Adjust} from \"../../src/interfaces/IPositions.sol\";\nimport {HubBase} from \"../utils/HubBase.sol\";\nimport {ImdUSD} from \"../../src/ImdUSD.sol\";\nimport {IERC3156FlashBorrower} from \"@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol\";\n\ninterface IHubU { function unbacked() external view returns (uint256); function exoticUnbacked() external view returns (uint256); }\n\ncontract CircProbe is IERC3156FlashBorrower {\n    uint256 public seen;\n    function go(ImdUSD u, uint256 v) external { u.approve(address(u), v); u.flashLoan(this, address(u), v, \"\"); }\n    function onFlashLoan(address, address, uint256, uint256, bytes calldata) external returns (bytes32) {\n        seen = ImdUSD(msg.sender).circulating();\n        return keccak256(\"ERC3156FlashBorrower.onFlashLoan\");\n    }\n}\n\ncontract BrakeLivenessTest is HubBase {\n    uint256 aliceId;\n\n    function setUp() public {\n        _setUpHub();\n        (uint256 p, uint256 n) = sorted.findInsertPosition(ETH, 0.05e18);\n        vm.prank(alice);\n        aliceId = ledger.open(ETH, 7, Adjust(int256(100e18), int256(100_000e18), 0.05e18, p, n, false, type(uint256).max, address(0)));\n        mod.mint(address(mod), 50_000e18);\n        _pass(3 hours);\n        ethFeed.set(ethFeed.value());\n    }\n\n    function _reading() internal view returns (uint256 u) {\n        uint256 bad = ledger.totalBadDebt();\n        uint256 c = usd.balanceOf(ledger.treasury());\n        u = bad > c ? bad - c : 0;\n        uint256 h = IHubU(address(hub)).unbacked();\n        if (h != 0) {\n            uint256 m = params.exoticMargin();\n            if (m != 0) { uint256 e = IHubU(address(hub)).exoticUnbacked(); if (e < m) m = e; h = h > m ? h - m : 0; }\n            u += h;\n        }\n    }\n\n    /// P3: a borrow is refused iff the reading > unbackedBrake x feeBase; repay and deposit never brake.\n    function testFuzz_P3_brakeExactAndRepayDepositLive(uint256 loss, uint256 dt) public {\n        loss = bound(loss, 0, 100_000e18);\n        dt = bound(dt, 0, 3 hours);\n        if (loss != 0) house.report(loss);\n        _pass(dt);\n        ethFeed.set(ethFeed.value());\n        bool braked = _reading() > usd.feeBase() * params.unbackedBrake() / 1e18;\n        (uint256 p, uint256 n) = sorted.findInsertPosition(ETH, 0.05e18);\n        vm.prank(bob);\n        try ledger.open(ETH, 9, Adjust(int256(10e18), int256(1_000e18), 0.05e18, p, n, false, type(uint256).max, address(0))) {\n            assertFalse(braked, \"borrowed past the brake\");\n        } catch (bytes memory err) {\n            assertTrue(braked, \"refused under the brake\");\n            assertEq(bytes4(err), LedgerBase.Braked.selector);\n        }\n        vm.startPrank(alice);\n        ledger.adjust(aliceId, Adjust(int256(1e18), 0, 0, 0, 0, false, 0, address(0))); // deposit\n        ledger.adjust(aliceId, Adjust(0, -int256(1_000e18), 0, 0, 0, false, 0, address(0))); // repay\n        vm.stopPrank();\n    }\n\n    /// C5: inside a flash loan circulating() is the tx-start supply (the savers' share cannot be skimmed by a flash mint).\n    function testFuzz_C5_flashDoesNotMoveCirculating(uint256 v) public {\n        v = bound(v, 1, usd.maxFlashLoan(address(usd)));\n        CircProbe pr = new CircProbe();\n        uint256 s = usd.totalSupply();\n        pr.go(usd, v);\n        assertEq(pr.seen(), s);\n    }\n\n    /// C3 Migrator: toV1 then toV2 in two txs lowers feeBase by exactly the round trip, never past outstanding.\n    function testFuzz_C3_migratorRoundTripBounded(uint256 x, uint256 y) public {\n        x = bound(x, 1, 100_000e18);\n        v1.mint(carol, x);\n        vm.startPrank(carol);\n        v1.approve(address(migrator), type(uint256).max);\n        usd.approve(address(migrator), type(uint256).max);\n        migrator.toV2(x);\n        vm.stopPrank();\n        _pass(3 hours);\n        uint256 fb = usd.feeBase();\n        y = bound(y, 1, x);\n        vm.prank(carol);\n        migrator.toV1(y);\n        vm.roll(block.number + 1);\n        vm.prank(carol);\n        migrator.toV2(y);\n        assertEq(usd.feeBase(), fb - y, \"fall = round trip\");\n        vm.prank(carol);\n        vm.expectRevert();\n        migrator.toV1(x + 1); // above outstanding\n    }\n}\n"
 }
}