{
 "item": "brake-exotic-margin",
 "commit": "ff1c192b3798542997f600091f2dc73ff05e4c40",
 "forge": "forge 1.9.0 (--use solar; forge test --match-path test/scratch/BrakeExotic.t.sol, HubBase fixture from test/utils)",
 "verdict": "findings",
 "findings": [
  {
   "id": "brake-exotic-margin-F1",
   "severity": "low",
   "title": "Core borrow mints its own upfront fee (and in-cooldown premium) to the Treasury BEFORE _checkBrake, so the fee counts as Treasury cover of core bad debt and a braked system lends",
   "property": "P1",
   "claim": "P1: new core debt reverts while max(0, core bad debt - Treasury imdUSD) + max(0, hub.unbacked() - min(m, hub.exoticUnbacked())) > unbackedBrake x feeBase(). Ledger._adjust calls _mintInterest(ilk, fee) (Treasury share minted to the Treasury, LedgerBase.sol:296-299) at Ledger.sol:234 and the reopen premium at Ledger.sol:261, then _checkBrake() at Ledger.sol:271, which reads token.balanceOf(treasury) (LedgerBase.sol:326). The charged setRate path does the opposite order (_checkBrake at LedgerSettlement.sol:243 before _mintInterest at :245).",
   "files": [
    "src/Ledger.sol:229",
    "src/Ledger.sol:234",
    "src/Ledger.sol:261",
    "src/Ledger.sol:271",
    "src/LedgerBase.sol:296",
    "src/LedgerBase.sol:326",
    "src/LedgerSettlement.sol:243"
   ],
   "sequence": "1) Core bad debt stands so that the brake reading exceeds unbackedBrake x feeBase() by `over` (any liquidation shortfall; the test writes totalBadDebt = Treasury imdUSD + allowed + over). 2) A small borrow (fee < over) reverts Braked. 3) Any stranger opens/tops up a position whose upfront fee x (1 - savings share) > over (here 120,000 imdUSD at 5%: fee ~115 imdUSD): the fee is minted to the Treasury first, the reading falls under `allowed`, the borrow passes. Fuzzed over `over` in (small fee, big fee): 500/500 runs lend while braked (shown as a property test that fails on its first run). One transaction, no key, no spoke.",
   "expected": "Braked(u, allowed): the brake is judged on the state before the borrow (as setRate does), so no new core debt while the pre-borrow reading exceeds the limit.",
   "actual": "The borrow succeeds: Ledger.open returns, new debt 120,000 + fee minted while the pre-transaction reading was over the brake by up to the borrow's own fee share. The cover is imdUSD backed only by the same new debt; the bypass scales with the borrow (about 0.096% of the amount at a 5% average rate, 7-day RATE_COOLDOWN) and is bounded by the type's line and the borrower's collateral.",
   "reachableAtDeploy": "yes once C1 opens core lines and any core bad debt stands (no governance action needed; the savings split only shrinks the Treasury share)",
   "fix": "In Ledger._adjust call _checkBrake() before the fee/premium _mintInterest calls (e.g. at the top of the dDebt > 0 branch), or read the Treasury balance before the mints and pass it in, as LedgerSettlement.setRate already orders it.",
   "test": {
    "source": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {stdStorage, StdStorage} from \"forge-std/Test.sol\";\nimport {HubBase} from \"../utils/HubBase.sol\";\nimport {LedgerBase} from \"../../src/LedgerBase.sol\";\nimport {Adjust} from \"../../src/interfaces/IPositions.sol\";\n\ncontract BrakeExoticTest is HubBase {\n    using stdStorage for StdStorage;\n\n    uint256 constant MARGIN = 10_000e18;\n\n    function setUp() public {\n        _setUpHub();\n        _borrow(alice, 100e18, 100_000e18);\n        uint8 k = params.SET_EXOTIC_MARGIN();\n        vm.prank(governor);\n        params.propose(abi.encode(k, MARGIN));\n        _pass(48 hours + 1);\n        params.applyPending(k);\n        house.mint(address(house), 50_000e18);\n        mod.mint(address(mod), 50_000e18);\n        mod.mint(stranger, 20_000e18);\n        _pass(3 hours);\n    }\n\n    // ---- the brake reading, exactly as P1 writes it\n    function _reading(uint256 m) internal view returns (uint256 u) {\n        uint256 bad = ledger.totalBadDebt();\n        uint256 t = usd.balanceOf(ledger.treasury());\n        u = bad > t ? bad - t : 0;\n        uint256 h = hub.unbacked();\n        uint256 e = hub.exoticUnbacked();\n        uint256 me = m < e ? m : e;\n        u += h > me ? h - me : 0;\n    }\n\n    function _allowed() internal view returns (uint256) {\n        return usd.feeBase() * params.unbackedBrake() / 1e18;\n    }\n\n    function _open(address who, uint256 coll, uint256 debt) internal returns (bool ok) {\n        (uint256 p, uint256 n) = sorted.findInsertPosition(ETH, 0.05e18);\n        vm.prank(who);\n        try ledger.open(ETH, uint256(keccak256(abi.encode(who, debt, gasleft()))), Adjust(int256(coll), int256(debt), 0.05e18, p, n, false, type(uint256).max, address(0))) {\n            ok = true;\n        } catch (bytes memory err) {\n            assertEq(bytes4(err), LedgerBase.Braked.selector, \"only the brake refuses\");\n        }\n    }\n\n    // ================= F1: a borrow's own upfront fee, minted to the Treasury BEFORE _checkBrake, lifts the brake it is judged by\n    function testFuzz_F1_feeMintedBeforeBrakeLiftsIt(uint256 over) public {\n        ledger.accrue(ETH);\n        uint256 debt = 120_000e18;\n        uint256 fee = ledger.upfrontFeeFor(ETH, debt, 0.05e18); // all to the Treasury here (no savings split)\n        uint256 small = ledger.upfrontFeeFor(ETH, 1_000e18, 0.05e18);\n        over = bound(over, small + 1, fee - 1); // past what the small borrow's fee could cover, under the big one's\n        uint256 t = usd.balanceOf(ledger.treasury());\n        stdstore.target(address(ledger)).sig(\"totalBadDebt()\").checked_write(t + _allowed() + over);\n        uint256 before = _reading(params.exoticMargin());\n        assertGt(before, _allowed(), \"P1 premise: braked before the borrow\");\n        assertFalse(_open(carol, 1e18, 1_000e18), \"a small borrow is braked\");\n        assertFalse(_open(bob, 200e18, debt), \"P1: new core debt while braked\");\n    }\n\n    // control: an excess the fee cannot cover still brakes the same borrow\n    function test_F1_control_excessPastFeeBrakes() public {\n        ledger.accrue(ETH);\n        uint256 debt = 120_000e18;\n        uint256 fee = ledger.upfrontFeeFor(ETH, debt, 0.05e18);\n        uint256 t = usd.balanceOf(ledger.treasury());\n        stdstore.target(address(ledger)).sig(\"totalBadDebt()\").checked_write(t + _allowed() + fee + 1e18);\n        assertFalse(_open(bob, 200e18, debt), \"braked\");\n    }\n\n",
    "ran": "yes: forge test --use solar --match-path test/scratch/BrakeExotic.t.sol --fuzz-runs 500",
    "result": "[FAIL: P1: new core debt while braked; counterexample: args=[57600]] testFuzz_F1_feeMintedBeforeBrakeLiftsIt(uint256) (runs: 0); [PASS] test_F1_control_excessPastFeeBrakes() (an excess larger than the fee still brakes the same borrow); with the assertion inverted the same test passed 500/500 runs."
   }
  }
 ],
 "claims": [
  {
   "id": "C1",
   "result": "holds",
   "evidence": "Known route (README:612-619) needs a spoke to payReserve its own mint then reportLoss; restore mint-back refused when frozen (MinterHub.sol:225). Spoke-free routes tried in testFuzz_P2_C2_sequences (500 runs x 24 random acts: stranger donation into the hub, stranger coverFromReserve on either row, stranger cover(), Safe markLoss, spoke mint/report/payReserve/burn, warps): the brake reading never fell by more than the imdUSD the stranger burned or parked (assert C1). A borrower of an exotic spoke donating the borrowed imdUSD then defaulting costs 1:1 like any cover. FixedLoans._payFee (src/spokes/FixedLoans.sol:676-683) pays the reserve share of the fee out of its own fresh hub.mint (FixedLoans.sol:268) and later reportLoss (:704): that is the designed reserve income, netted pooled once in unbacked(), inside the README:612 bound; not past it."
  },
  {
   "id": "C2",
   "result": "holds",
   "evidence": "MinterHub.unbacked() (MinterHub.sol:273) and exoticUnbacked() (:293) checked after every act of the 500-run sequence fuzz against an independent recomputation sum max(bad, min(mark, out+bad)) less balanceOf(hub): always equal. The marks counter (++ at :405, -- at LOWER_MARK apply) never desynchronised; covered_s excluded as documented; a cover under a standing mark can only raise the reading (KNOWN, MinterHub.sol:615-617)."
  },
  {
   "id": "C3",
   "result": "holds",
   "evidence": "P2 is structural in _checkBrake (LedgerBase.sol:329-337): the hub part is reduced by min(m, e, h) and core bad debt is added outside it. Fuzzed m over [0, MAX_EXOTIC_MARGIN = 1,000,000e18] (ParametersBase.sol:169), set by SET_EXOTIC_MARGIN applied by a stranger after 48 h: r(0) - r(m) <= min(m, exoticUnbacked) and r(m) >= max(0, coreBad - Treasury) in every state. The placeholder sizes (DeployConfig.sol:461 Ethereum 1,000; :656 Robinhood 3,000; :597/:807 Base 0) are sizes only."
  },
  {
   "id": "C4",
   "result": "holds",
   "evidence": "src/Migrator.sol calls only hub.room (:49), hub.mint (:52), hub.burn (:59), never reportLoss; the Safe's H4 adds it exotic (script/launch/SafeBatch.s.sol:223 NewSpoke(mig, ..., true, 0)). No core collateral type is v1 imdUSD, so a v1 depeg reaches the brake only via markLoss on that exotic row, inside the margin (testFuzz_P2_C2 marks exotic rows). No other route found."
  },
  {
   "id": "C5",
   "result": "holds",
   "evidence": "testFuzz_C5_reportOrder (500 runs, losses n, x and reserve r each fuzzed up to 20,000): the exotic-first order never reads less than non-exotic-first at margin 10,000; stranger coverFromReserve between reports never lowered the reading (sequence fuzz)."
  },
  {
   "id": "P1-doc",
   "result": "refuted",
   "evidence": "README:21 says the limit is `unbackedBrake x circulating()`; the code divides by feeBase() (LedgerBase.sol:348), as the sheet notes. feeBase() <= circulating(), so the code brakes sooner than README:21 states; documentation only."
  }
 ],
 "holds": [
  {
   "property": "P1",
   "tried": "Holds for the hub term and for the charged setRate path (check before mint). FAILS in Ledger._adjust: see F1. Accrued interest minted by _accrue inside the same call is also Treasury cover, but anyone can call accrue(ilk) beforehand, so it is the state, not a bypass. Readers of the brake: Ledger._adjust (Ledger.sol:271), LedgerSettlement.setRate (:243); view Ledger.unbacked (LedgerBase.sol:221). Writers of its inputs: totalBadDebt (LedgerSettlement.sol:165 +, Ledger.sol:358 -), Treasury imdUSD (_mintInterest, coverBadDebt, payNote/payout), hub rows (mint/burn/reportLoss/restore/payReserve/cover/coverFromReserve/repayReserve/markLoss/LOWER_MARK/RELEASE_COVERED/RELEASE_RESERVE), exoticMargin (setGenesisExoticMargin pre-seal <= MAX, SET_EXOTIC_MARGIN, lowerExoticMargin), unbackedBrake (SET_UNBACKED_BRAKE, lowerUnbackedBrake), feeBase (ImdUSD._noteStart)."
  },
  {
   "property": "P2",
   "tried": "testFuzz_P2_C2_sequences: 500 runs x 24 acts (both spoke kinds mint/report/payReserve/burn, Safe markLoss on either row, stranger donation/cover/coverFromReserve, hour warps), margin fuzzed 0..MAX and applied by a stranger: after every act r(0) - r(m) <= min(m, exoticUnbacked()) and r(m) >= max(0, core bad - Treasury). Never violated."
  },
  {
   "property": "P3",
   "tried": "Margin fuzzed over the whole rule range via the 48 h SET_EXOTIC_MARGIN applied by a stranger with losses and positions live; lowerExoticMargin(0) first then raise; P2 held. The genesis setter (Parameters.sol:85-91) has the same MAX bound and is wirer-only before seal. Any unbackedBrake <= MAX_UNBACKED_BRAKE leaves F1 in place (the fee route works at any limit); caps change only exoticUnbacked's bound (<= exoticUsed)."
  }
 ],
 "notRun": [
  "No [fork]/[data] claim in this sheet; no fork test was RUN (NOT RUN: no RPC used).",
  "Real FixedLoans/MorphoLender/house spokes were not wired into the sequence fuzz (TestSpoke stand-ins from test/utils/HubBase.sol); their fee-to-reserve route was reasoned from code."
 ]
}