{
 "item": "stock-liquidator",
 "commit": "ff1c192b3798542997f600091f2dc73ff05e4c40",
 "forge": "forge Version: 1.8.3 (cae51ad458f6abb64852b7709eb784352429825d); older than 1.9, so no --use solar: compiled with solc 0.8.38 (installed), only test/sl/SLGoal.t.sol via --match-path",
 "verdict": "findings",
 "findings": [
  {
   "id": "SL-1",
   "severity": "medium",
   "title": "Under F7 (two consecutive wrong rounds price any level) the backstop, following its own keeper rule, pays the float far above market; README bounds the F7 loss only at the lender's market cap and row, the float's loss is outside that bound",
   "property": "P1 Our backstop never spends the float above market",
   "claim": "C3",
   "files": [
    "src/morpho/StockLiquidator.sol:18",
    "src/morpho/StockLiquidator.sol:20",
    "src/morpho/StockLiquidator.sol:86",
    "src/stocks/StockOracle.sol:55",
    "README.md:814",
    "README.md:835"
   ],
   "sequence": "1) Chainlink prints two consecutive wrong-high rounds within JUMP of each other (F7: 'two consecutive rounds within JUMP of each other price ANY level from MIN_ANSWER to MAX_ANSWER'); oracle prices P_w = 3 x market. 2) A stranger supplies 100 stock and borrows at the LLTV at P_w (18,750 imdUSD) from our market. 3) An hour of interest makes it liquidatable. 4) The keeper follows the rule in StockLiquidator.sol:20 ('The keeper passes at most the seized stock's value at the feed's latest answer'): maxRepaid = 70e18 x P_w. 5) Morpho pulls 70 x P_w / LIF = 18,637.5 imdUSD from the float for 70 stock worth 7,000 at market.",
   "expected": "The float never pays above market (P1, StockLiquidator.sol:21 'so the float never pays above market'); at worst bounded as README:814 states for F7 (lender bad debt bounded by the market's cap and the lender's hub row).",
   "actual": "The float paid 18637500000000000002331 for collateral worth 7000000000000000000000 at market: a loss of ~11,637 imdUSD of float, in addition to the lender's F7 bad debt. The maxRepaid/seizedAssets cap (StockLiquidator.sol:86) only binds the price to the oracle's own answer, so any F7 level passes; loss bounded only by the float (per unit up to P_w/LIF - P_true). Under F1 (one wrong LOW round) the float pays less than market (a gain to the float, loss to the borrower), so F1 gives no float loss.",
   "reachableAtDeploy": true,
   "fix": "Bound the backstop's price by a second source on-chain: liquidate takes a maxPrice that the contract checks against an independent reference (e.g. a second feed or a stored reference with a deviation band) and refuses when oracle.price() deviates, or have the keeper's reference-price check (the README's control for F7) gate the backstop on-chain; at minimum state in README:814/835 that the float is also lost under F7 and size the float for it.",
   "test": {
    "source": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {Test} from \"forge-std/Test.sol\";\nimport {LenderBase} from \"../utils/LenderBase.sol\";\nimport {MockERC20} from \"../utils/Mocks.sol\";\nimport {MockStockOracle} from \"../utils/MockMorpho.sol\";\nimport {IMorpho, MarketParams, Id} from \"../../src/vendor/morpho/IMorpho.sol\";\nimport {StockLiquidator} from \"../../src/morpho/StockLiquidator.sol\";\n\ncontract SLHandler is Test {\n    StockLiquidator liq; IMorpho morpho; IERC20 usd; address operator; address outsider; address governor;\n    MarketParams[3] mp; MockStockOracle[3] oracle; MockERC20[3] stock; address[3] who;\n    uint256 public ghostOut; uint256 public ghostIn; uint256 public ghostRecovered; bool public bad; string public why;\n    uint256 public calls; uint256 public liqs;\n\n    constructor(StockLiquidator l, IMorpho m, IERC20 u, address op, address out, address gov, MarketParams[3] memory p,\n        MockStockOracle[3] memory o, MockERC20[3] memory s, address[3] memory w) {\n        liq = l; morpho = m; usd = u; operator = op; outsider = out; governor = gov;\n        for (uint256 i; i < 3; ++i) { mp[i] = p[i]; oracle[i] = o[i]; stock[i] = s[i]; who[i] = w[i]; }\n    }\n    function _id(MarketParams memory p) internal pure returns (Id) { return Id.wrap(keccak256(abi.encode(p))); }\n\n    function borrowMax(uint256 i, uint256 w, uint256 coll) external {\n        i %= 3; address a = who[w % 3]; coll = bound(coll, 1, 50e18);\n        uint256 px = oracle[i].price();\n        vm.startPrank(a);\n        morpho.supplyCollateral(mp[i], coll, a, \"\");\n        uint256 c = morpho.position(_id(mp[i]), a).collateral;\n        uint256 maxDebt = c * px / 1e36 * 0.625e18 / 1e18;\n        (,,uint128 tba,) = (uint128(0),uint128(0),morpho.market(_id(mp[i])).totalBorrowAssets,uint128(0));\n        uint256 idle = morpho.market(_id(mp[i])).totalSupplyAssets - tba;\n        uint256 want = maxDebt * 99 / 100; uint256 b = want < idle ? want : idle;\n        if (b > 0) try morpho.borrow(mp[i], b, 0, a, a) {} catch {}\n        vm.stopPrank();\n    }\n    function movePrice(uint256 i, uint256 bps, bool up) external {\n        i %= 3; bps = bound(bps, 0, 2_000);\n        uint256 px = oracle[i].price();\n        px = up ? px * (10_000 + bps) / 10_000 : px * (10_000 - bps) / 10_000;\n        if (px < 1e36) px = 1e36;\n        oracle[i].set(px);\n    }\n    function warp(uint256 dt) external { dt = bound(dt, 0, 3 days); vm.warp(block.timestamp + dt); vm.roll(block.number + 1); }\n    function strangerLiquidate(uint256 i, uint256 w, uint256 amt) external {\n        i %= 3; address b = who[w % 3];\n        uint256 c = morpho.position(_id(mp[i]), b).collateral; if (c == 0) return;\n        amt = bound(amt, 1, c);\n        vm.prank(outsider); try morpho.liquidate(mp[i], b, amt, 0, \"\") {} catch {}\n    }\n    /// The operator (honest keeper rule: maxRepaid = seized value at the latest answer; or a thief: any maxRepaid).\n    function opLiquidate(uint256 i, uint256 w, uint256 seizedAssets, uint256 maxRepaid, bool thief) external {\n        i %= 3; address b = who[w % 3]; seizedAssets = bound(seizedAssets, 1, 100e18);\n        uint256 px = oracle[i].price();\n        if (!thief) maxRepaid = Math.mulDiv(seizedAssets, px, 1e36);\n        else maxRepaid = bound(maxRepaid, 0, 1e30);\n        uint256 f0 = usd.balanceOf(address(liq));\n        vm.prank(operator);\n        try liq.liquidate(mp[i], b, seizedAssets, 0, maxRepaid) returns (uint256 s, uint256 r) {\n            liqs++;\n            uint256 f1 = usd.balanceOf(address(liq));\n            if (f0 - f1 != r) { bad = true; why = \"float delta != repaid\"; }\n            // per unit never above the operator's cap\n            if (r * seizedAssets > maxRepaid * s) { bad = true; why = \"per-unit above maxRepaid/seizedAssets\"; }\n            // never above the value at the oracle's latest answer at inclusion (2 wei rounding slack)\n            if (r > Math.mulDiv(s, px, 1e36, Math.Rounding.Ceil) + 2) { bad = true; why = \"repaid above value at latest answer\"; }\n            ghostOut += r;\n        } catch {}\n        calls++;\n    }\n    function take(uint256 t, uint256 amt) external {\n        IERC20 tok = t % 4 == 3 ? usd : IERC20(address(stock[t % 3]));\n        amt = bound(amt, 0, tok.balanceOf(address(liq)));\n        uint256 f0 = usd.balanceOf(address(liq));\n        vm.prank(operator); try liq.take(tok, amt) {} catch {}\n        if (usd.balanceOf(address(liq)) != f0) { bad = true; why = \"take moved imdUSD\"; }\n    }\n    function donate(uint256 amt) external {\n        amt = bound(amt, 0, 1_000e18);\n        vm.prank(who[0]); usd.transfer(address(liq), amt); ghostIn += amt;\n    }\n    function recover(uint256 amt) external {\n        amt = bound(amt, 0, usd.balanceOf(address(liq)) / 10);\n        vm.prank(governor); liq.recover(usd, amt); ghostRecovered += amt;\n    }\n}\n\ncontract SLGoalTest is LenderBase {\n    SLHandler h;\n    uint256 constant FLOAT = 50_000e18;\n\n    function setUp() public override {\n        super.setUp();\n        for (uint256 i; i < N; ++i) _supply(i, 80_000e18);\n        MarketParams[3] memory p = [mp[0], mp[1], mp[2]];\n        MockStockOracle[3] memory o = [oracle[0], oracle[1], oracle[2]];\n        MockERC20[3] memory s = [stock[0], stock[1], stock[2]];\n        h = new SLHandler(liq, morpho, usd, operator, outsider, governor, p, o, s, [alice, bob, stranger]);\n        faucet.mint(stranger, 200_000e18);\n        vm.startPrank(stranger);\n        usd.approve(address(morpho), type(uint256).max);\n        for (uint256 i; i < N; ++i) { stock[i].mint(stranger, 100_000e18); stock[i].approve(address(morpho), type(uint256).max); }\n        vm.stopPrank();\n        vm.prank(outsider); usd.approve(address(morpho), type(uint256).max);\n        targetContract(address(h));\n    }\n\n    /// C6 / P1 / P2: every route that spends the float.\n    function invariant_floatOnlyLeavesByMorphoPullOrRecover() public view {\n        assertFalse(h.bad(), h.why());\n        assertEq(usd.allowance(address(liq), address(morpho)), 0, \"allowance reset\");\n        assertEq(usd.balanceOf(address(liq)), FLOAT + h.ghostIn() - h.ghostOut() - h.ghostRecovered(), \"float accounting\");\n        assertEq(usd.balanceOf(operator), 0, \"operator never holds imdUSD\");\n    }\n\n    /// The handler's liquidation path is live (keeper rule and thief), checks hold.\n    function test_handlerPathLive() public {\n        h.borrowMax(0, 0, 50e18);\n        h.movePrice(0, 2_000, false);\n        h.movePrice(0, 2_000, false);\n        h.strangerLiquidate(0, 0, 1);\n        h.opLiquidate(0, 0, 1e18, 0, false);\n        h.opLiquidate(0, 0, 1e18, type(uint256).max, true);\n        h.take(0, type(uint256).max);\n        h.take(3, type(uint256).max);\n        assertEq(h.liqs(), 2);\n        assertFalse(h.bad(), h.why());\n        invariant_floatOnlyLeavesByMorphoPullOrRecover();\n    }\n\n    /// C1: a stranger's front-run of any size cannot raise the backstop's price per unit.\n    function testFuzz_C1_frontRunCannotRaisePerUnit(uint256 front, uint256 seizedAssets, uint256 drop) public {\n        _borrow(0, 100e18, 6_000e18);\n        drop = bound(drop, 6_500, 8_500);\n        oracle[0].set(PX * drop / 10_000);\n        uint256 px = oracle[0].price();\n        seizedAssets = bound(seizedAssets, 1e6, 100e18);\n        front = bound(front, 0, 100e18);\n        if (front > 0) { vm.prank(outsider); try morpho.liquidate(mp[0], alice, front, 0, \"\") {} catch {} }\n        uint256 maxRepaid = Math.mulDiv(seizedAssets, px, 1e36);\n        uint256 f0 = usd.balanceOf(address(liq));\n        vm.prank(operator);\n        try liq.liquidate(mp[0], alice, seizedAssets, 0, maxRepaid) returns (uint256 s, uint256 r) {\n            assertEq(f0 - usd.balanceOf(address(liq)), r);\n            assertLe(r * seizedAssets, maxRepaid * s, \"per unit above the cap\");\n            assertLe(r, Math.mulDiv(s, px, 1e36, Math.Rounding.Ceil), \"above value at the latest answer\");\n        } catch {}\n        assertEq(usd.allowance(address(liq), address(morpho)), 0);\n    }\n\n    /// C4 / P3: nobody but the immutable operator (a keccak placeholder nobody holds) calls liquidate or take.\n    function testFuzz_C4_onlyOperator(address caller, uint256 amt) public {\n        vm.assume(caller != operator);\n        vm.startPrank(caller);\n        vm.expectRevert(StockLiquidator.NotOperator.selector);\n        liq.liquidate(mp[0], alice, 1e18, 0, 1e30);\n        vm.expectRevert(StockLiquidator.NotOperator.selector);\n        liq.take(IERC20(address(stock[0])), amt);\n        if (caller != governor) { vm.expectRevert(StockLiquidator.NotGovernor.selector); liq.recover(usd, amt); }\n        vm.stopPrank();\n        vm.prank(operator);\n        vm.expectRevert(StockLiquidator.SharesMode.selector);\n        liq.liquidate(mp[0], alice, 0, 1, 1e30);\n    }\n\n    /// C5: a stolen operator key needs no outside victim: it borrows at the LLTV itself, lets one block of interest make\n    /// the position liquidatable, liquidates itself from the float and takes the seized stock. Net gain = the float spent.\n    function test_C5_thiefManufacturesALiquidatablePosition() public {\n        address thief = operator;\n        stock[0].mint(thief, 1_000e18);\n        vm.startPrank(thief);\n        stock[0].approve(address(morpho), type(uint256).max);\n        morpho.supplyCollateral(mp[0], 400e18, thief, \"\");\n        morpho.borrow(mp[0], 400e18 * 100 * 625 / 1000 - 1e9, 0, thief, thief); // the LLTV less 1e9 wei: 25,000 imdUSD\n        vm.stopPrank();\n        _pass(1 hours); // an hour of interest\n        uint256 eq0 = _equity(thief);\n        uint256 f0 = usd.balanceOf(address(liq));\n        vm.startPrank(thief);\n        (uint256 s, uint256 r) = liq.liquidate(mp[0], thief, 280e18, 0, 280e18 * 100); // price unchanged: no market move\n        liq.take(IERC20(address(stock[0])), s);\n        vm.stopPrank();\n        uint256 eq1 = _equity(thief);\n        emit log_named_uint(\"float spent\", f0 - usd.balanceOf(address(liq)));\n        emit log_named_uint(\"thief equity gain\", eq1 - eq0);\n        assertEq(f0 - usd.balanceOf(address(liq)), r);\n        // the NatSpec bound \"by what is liquidatable\" (StockLiquidator.sol:34) is no bound: the thief made it so\n        assertGt(eq1 - eq0, r * 99 / 100, \"the float went to the key holder\");\n    }\n\n    function _equity(address a) internal view returns (uint256) {\n        uint256 c = morpho.position(_id(mp[0]), a).collateral + stock[0].balanceOf(a);\n        uint256 bs = morpho.position(_id(mp[0]), a).borrowShares;\n        uint256 debt = bs * (uint256(morpho.market(_id(mp[0])).totalBorrowAssets) + 1) / (uint256(morpho.market(_id(mp[0])).totalBorrowShares) + 1e6) + 1;\n        return c * oracle[0].price() / 1e36 + usd.balanceOf(a) - debt;\n    }\n\n    /// C3: F7 (two consecutive wrong rounds within JUMP price any level): a wrong HIGH level P_w. A borrower borrows at P_w,\n    /// one block later is liquidatable; the keeper follows its rule (maxRepaid = seized x latest answer) and the float pays\n    /// P_w / LIF per unit for stock worth P_true. Under F1 (wrong LOW) the float pays less than market (a gain).\n    function test_C3_F7HighFloatPaysAboveMarket() public {\n        uint256 pTrue = PX; uint256 pW = PX * 3; // a wrong level, 3x\n        oracle[0].set(pW);\n        address b = stranger;\n        vm.startPrank(b);\n        morpho.supplyCollateral(mp[0], 100e18, b, \"\");\n        morpho.borrow(mp[0], 100e18 * 300 * 625 / 1000 - 1e9, 0, b, b); // the LLTV at P_w less 1e9 wei: 18,750 imdUSD\n        vm.stopPrank();\n        _pass(1 hours);\n        uint256 f0 = usd.balanceOf(address(liq));\n        uint256 maxRepaid = Math.mulDiv(70e18, oracle[0].price(), 1e36); // the keeper's rule: value at the latest answer\n        vm.prank(operator);\n        (uint256 s, uint256 r) = liq.liquidate(mp[0], b, 70e18, 0, maxRepaid);\n        uint256 worth = Math.mulDiv(s, pTrue, 1e36);\n        emit log_named_uint(\"float paid\", f0 - usd.balanceOf(address(liq)));\n        emit log_named_uint(\"seized worth at market\", worth);\n        assertLe(r, worth, \"P1: the float never pays above market\");\n    }\n}\n",
    "ran": true,
    "result": "forge 1.8.3 (cae51ad, no --use solar in this version), solc 0.8.38 via_ir, `forge test --match-path test/sl/SLGoal.t.sol --offline -vv` on the repo's LenderBase rig (real ImdUSD, MinterHub, MorphoLender, StockLiquidator; MockMorpho with Morpho Blue's liquidation math; MockStockOracle as the latest answer). Suite: 5 passed, 1 failed: [PASS] invariant_floatOnlyLeavesByMorphoPullOrRecover() (runs: 128, calls: 8192, reverts: 0); [PASS] testFuzz_C1_frontRunCannotRaisePerUnit (runs: 256); [PASS] testFuzz_C4_onlyOperator (runs: 256); [PASS] test_C5_thiefManufacturesALiquidatablePosition (float spent: 24850000000000000003108, thief equity gain: 24849714610243246189525); [PASS] test_handlerPathLive; [FAIL: P1: the float never pays above market: 18637500000000000002331 > 7000000000000000000000] test_C3_F7HighFloatPaysAboveMarket() (gas: 650554)."
   }
  }
 ],
 "claims": [
  {
   "id": "C1",
   "result": "holds",
   "evidence": "testFuzz_C1_frontRunCannotRaisePerUnit (256 runs): a stranger's front-run liquidation of 0..100e18 (1 wei included) before the backstop; asserts float delta == repaid, repaid x seizedAssets <= maxRepaid x seized and repaid <= ceil(seized x price / 1e36). Allowance is cut with mulDiv rounding down (StockLiquidator.sol:86) while Morpho rounds repaid up, so a clipped tiny seize can only revert, never overpay. Also covered in the invariant handler (strangerLiquidate interleaved with opLiquidate over 8192 calls)."
  },
  {
   "id": "C2",
   "result": "holds",
   "evidence": "grep -rni checkpoint src script: only src/feeds/RateFeed.sol and src/house/dex/* (unrelated). liquidate's only post-Morpho call is lender.settle(n - 1) (StockLiquidator.sol:93); MorphoLender.settle (MorphoLender.sol:181) accrues and reports; StockOracle has no checkpoint (README:120-121 'no median close, soft line, rise hold, recovery rule, open grace or checkpoint')."
  },
  {
   "id": "C3",
   "result": "refuted",
   "evidence": "F1 (one wrong LOW round): price = min(a0,a1) <= latest answer, float pays price/LIF below market: no float loss (gain). F7 (wrong HIGH level from two consecutive wrong rounds): the float pays P_w/LIF per unit; test_C3_F7HighFloatPaysAboveMarket FAILS (18637.5 imdUSD paid for 7000 of stock). Bound: per liquidation (P_w/LIF - P_true) x seized, in total the whole float; not covered by README:814's bound (finding SL-1)."
  },
  {
   "id": "C4",
   "result": "holds",
   "evidence": "script/DeployConfig.sol:875 OPERATOR = address(uint160(uint256(keccak256(\"imdusd.placeholder.robinhood.stocks-keeper-liquidation-key\")))): no known private key, so before set nobody can call liquidate/take; testFuzz_C4_onlyOperator (256 runs, any caller) reverts NotOperator / NotGovernor. operator is immutable (StockLiquidator.sol:45, wired at script/deploy/StageChain.sol:78), so 'set' means redeploying the StockLiquidator; nothing else references it, and a float sent to the placeholder-operated contract is recoverable by the Safe's recover (StockLiquidator.sol:120)."
  },
  {
   "id": "C5",
   "result": "holds",
   "evidence": "As stated (README:835). test_C5_thiefManufacturesALiquidatablePosition: the thief needs no victim: borrows at the LLTV on our market, waits one hour of interest, liquidates itself from the float (280 stock, price unchanged) and takes the seized stock: float spent 24850000000000000003108, thief equity gain 24849714610243246189525 (the float, 1:1). The float does not leave as imdUSD to the thief directly (it repays the thief's debt in Morpho), take refuses imdUSD (invariant: operator's imdUSD balance stays 0), and the price is never above the oracle's latest answer (repaid <= ceil(seized x price/1e36) checked on every liquidation in the invariant). Note: the NatSpec bound 'Bounded by what is liquidatable' (StockLiquidator.sol:34) is no bound in practice; only the float bounds it, as README:835 sizes it."
  },
  {
   "id": "C6",
   "result": "holds",
   "evidence": "ONE invariant (invariant_floatOnlyLeavesByMorphoPullOrRecover, 128 runs x 64 depth, 8192 calls, handler: borrowMax, movePrice +-20%, warp 0..3 days, stranger liquidations, operator liquidations under the keeper rule and as a thief with any maxRepaid, take of every stock and imdUSD, donations, Safe recover): balance(liq) == float + donations - SUM repaid(liquidate) - SUM recover; allowance(liq, morpho) == 0 after every call; operator's imdUSD == 0; and per liquidation repaid x seizedAssets <= maxRepaid x seized and repaid <= ceil(seized x oracle.price()/1e36) + 2. It covers every route that spends the float relative to the ORACLE; it cannot cover 'market' (SL-1). Smallest replacement design for P1 against market: an on-chain maxPrice checked against a second independent reference before morpho.liquidate."
  }
 ],
 "holds": [
  {
   "property": "P1 (relative to the oracle's latest answer): maxRepaid/seizedAssets caps the price; SharesMode refused; seize = min(seizedAssets, collateral) with proportional allowance",
   "tried": "invariant (8192 calls, interleaved stranger front-runs, price moves, warps, thief maxRepaid up to 1e30), testFuzz_C1 (256 runs), SharesMode revert in testFuzz_C4. Holds vs the oracle; vs market fails under F7 (SL-1)."
  },
  {
   "property": "P2 allowance exact and reset; float leaves only by Morpho's pull in liquidate and the Safe's recover",
   "tried": "invariant asserts allowance 0 and exact float accounting after every call. Writers of the float other than these: ImdUSD.burn by a minter (ImdUSD.sol:148-154) is used only on msg.sender / own reserve / a Backstop sleeve (Ledger.sol:412, MinterHub.sol:191,251,644, ImdBridge.sol:520): none burns from the StockLiquidator; flash mint needs the receiver's callback, which StockLiquidator lacks; no callback data is passed to Morpho (StockLiquidator.sol:88)."
  },
  {
   "property": "P3 only the immutable operator; liquidate only on an approved market (NotOurMarket); take only an approved market's collateral, never imdUSD",
   "tried": "testFuzz_C4 (any caller), invariant take of imdUSD and stocks (imdUSD never moves). Approved rows are never removed (MorphoLender.sol:315-320, '24 market rows for life'): a market frozen by lowerCap(0) (MorphoLender.sol:241) stays 'our market' for liquidate and take; APPROVE requires loanToken == imdUSD (MorphoLender.sol:278), so Morpho's pull is always imdUSD within the exact allowance. The existing regressions in test/unit/AuditS12LenderOperatorKey.t.sol cover the foreign-market and imdUSD-take routes."
  },
  {
   "property": "SettleGasShort (same-transaction report)",
   "tried": "code reasoning: settle gets 63/64 of g; an OOG in settle or in a call inside it returns about g x 127/4096 < g/32, so a starved settle reverts the liquidation; only the operator can call, and a missed report is taken by the next anyone's settle (MorphoLender.sol:181). Not tested on-chain."
  }
 ],
 "notRun": [
  "No [fork] or [data] claim in this sheet: NOT RUN (no fork). Real Morpho Blue not used: MockMorpho (test/utils/MockMorpho.sol) with the same seizedAssets-mode rounding; StockOracle replaced by MockStockOracle (its F1/F7 behaviour is the stock-oracle item's). Earlier submissions (api.imd.fun) not fetched.",
  "forge 1.9 / --use solar unavailable (forge 1.8.3)."
 ]
}