{
 "item": "stock-oracle-s-price",
 "commit": "ff1c192b3798542997f600091f2dc73ff05e4c40",
 "forge": "forge 1.9.0 (6056c58), --use solar (Solar 0.8.38), --match-path test/scratch/SPrice.t.sol, --fuzz-runs 20000",
 "verdict": "holds",
 "findings": [],
 "claims": [
  {
   "id": "F1",
   "result": "holds",
   "evidence": "StockOracle.sol:223-224 price=min(a0,a1) only if |a0-a1|*1e4 <= a1*JUMP. testFuzz_F1F2_oneWrongRound (20000 runs, every configured ticker's LLTV/JUMP from StocksConfig.tickers(), honest moves -20%..+20%, one wrong round anywhere in [MIN_ANSWER,MAX_ANSWER] at any of the last 3 positions): whenever priced, price >= min(honest a0,a1) x (1-JUMP) and a borrower at LLTV x that honest level fully liquidated at the price with Morpho's LIF (min(1.15,1/(1-0.3(1-LLTV)))) repays >= its debt: no lender loss found. Algebra: a0 wrong -> p=a0>=a1(1-J); a1 wrong -> p=a1>=a0/(1+J)>a0(1-J). test_F1_example_and_duration: 100,100,94 -> Jump revert; then 98 -> 94; then 98 -> 98; a wrong low within JUMP (95) prices as latest and through the corrective round (99), dropped at the round after. The duration in wall time ('up to about a trading day' on SPY/AAPL/SGOV) is a [data] statement about feed print cadence: NOT RUN (no fork/replay run); code-wise it prices exactly while it is one of the last two rounds. Note: measured against the honest round BEFORE a refused wrong round (100 in 100,94,98) the price is below 100x(1-J); the README's 'adjacent honest round' bound holds against the honest member of the priced pair, which is what the liquidation math needs."
  },
  {
   "id": "F2",
   "result": "holds",
   "evidence": "price <= a0 and <= a1 (min, StockOracle.sol:224). testFuzz_F1F2_oneWrongRound asserts: a wrong round outside the pair is never read (price == honest oracle's), and with one wrong round in the pair the price never exceeds the honest member of the pair; C3 differential confirms min over all sequences. A price above the honest pair requires both a0 and a1 above it, i.e. two consecutive wrong rounds within JUMP of each other."
  },
  {
   "id": "F6",
   "result": "holds",
   "evidence": "test_F6_fastOpen: Fri close 100, Mon open+1s 104 -> SESSION_ROUNDS off prices 100 (one round under), SESSION_ROUNDS on reverts NotYet; next round 104.5 -> both price 104. Structural: min of last two can be at most one round behind; a gap past JUMP reverts Jump (F4)."
  },
  {
   "id": "F7",
   "result": "holds",
   "evidence": "As written (README:814-818): two consecutive rounds within JUMP price any level in [MIN_ANSWER,MAX_ANSWER] (C3 differential reproduces this; no older-level bound exists in price()). Below MIN_ANSWER: BadAnswer (StockOracle.sol:220, :309; C3 + C1 edges). The bad-debt bound 'market cap and lender row' lives in MorphoLender/MinterHub caps (outside this sheet's mechanism); no loss past it was constructed. Known issue, not worse than written as far as this item's code goes."
  },
  {
   "id": "C1",
   "result": "holds",
   "evidence": "testFuzz_C1_edges (20000 runs): maxAnswer=uint128.max, minAnswer=1, JUMP 1..2000, answers within 1e6 of 1 and of uint128.max: priced iff d*1e4 <= a1*JUMP exactly, value min*SCALE, otherwise Jump; d*1e4 and a1*JUMP <= 2^128*2e3 cannot overflow (maxAnswer <= uint128.max, StockOracle.sol:187). min*SCALE cannot overflow for configured decimals (1e13*1e28)."
  },
  {
   "id": "C2",
   "result": "holds",
   "evidence": "StockOracle.sol:186-187. test_C2_constructor: minAnswer 0, minAnswer==maxAnswer, jump 2001, jump 0, pulse = an EOA all revert BadConfig; jump 2000 with minAnswer=maxAnswer-1 deploys."
  },
  {
   "id": "C3",
   "result": "holds",
   "evidence": "testFuzz_C3_differential: independent reference model of THE RULE (NatSpec lines 23-35) over the test's own copy of the rounds, vs price() of both SESSION_ROUNDS settings: 1-9 rounds, 1/4 of steps in the same block, steps up to 20 h across Fri pre/post market, weekend and Mon session edges, phase changes (~1/11 rounds, empty new phase), moves of -6..+6% plus answers at MIN/MAX_ANSWER +-2, <=0 and random, query up to 4 days later. Asserted equal: priced/unpriced, value AND revert selector (order of checks). 20000 runs, 0 mismatches; a 400-seed coverage loop showed priced, Jump, Closed, BadAnswer, Stale, NoPrevious and NotYet outcomes all reached."
  }
 ],
 "holds": [
  {
   "property": "P1 price() is min(a0,a1) x SCALE or reverts; never 0; never above either round; never outside [MIN_ANSWER,MAX_ANSWER] x SCALE",
   "tried": "C3 differential (20000 runs, value and selector equal to the model), C1 edge fuzz at 1 and uint128.max, F1/F2 fuzz. Every failure reverts (StockOracle.sol:211-223); both answers checked against MIN/MAX (:220, :309), so min is in range and >0."
  },
  {
   "property": "P2 LLTV x LIF / (1 - JUMP) < 1 for every market, so a liquidation at ONE wrong-low round leaves no bad debt",
   "tried": "test_P2_configuredMarkets with MorphoLender.sol:291-293 arithmetic over all 9 tickers (SPY .77/5%, AAPL..SPCX .625/5%, CRCL/MSTR .385/5%, SGOV .86/2%: worst SGOV 0.916). testFuzz_F1F2_oneWrongRound simulates full liquidation of a borrower at LLTV x honest level at the oracle price for every ticker: no bad debt in 20000 runs. MorphoLender APPROVE enforces it per market at propose and apply (_check, MorphoLender.sol:282-293) reading the oracle's own JUMP; LIF formula and rounding match Morpho's wDivDown. (DeployConfig.sol:900-901 and StocksConfigRules R1 cite the weaker LLTV x (1+JUMP) x LIF; R1b and the lender check the exact /(1-JUMP).)"
  },
  {
   "property": "P3 SCALE = 10^(36 + loan - collateral - feed)",
   "tried": "StockOracle.sol:202; testFuzz_P3_scale over loan decimals 0..36 and feed decimals 0..36 with an 18-decimal token: SCALE matches, decimals that would underflow revert BadConfig (:183). Configured tokens/feeds on 4663 (18-dec tokens, 8-dec feeds per DeployConfig comments) [fork]: NOT RUN."
  },
  {
   "property": "Writers/readers of the state the properties name",
   "tried": "Writers: immutables only in the constructor; deployed by script/deploy/StageChain.sol:47-66 with StocksConfig per-ticker jump/sessionRounds/minAnswer, MAX_ANSWER 1e13, pulse=d.pulse (checked wiring by reading); feed/calendar/pulse external. Readers: Morpho Blue (borrow/liquidate/withdrawCollateral), StockLiquidator (prices seize via Morpho), MorphoLender APPROVE (VERSION==2, token, loanToken, morpho, governor, calendar, JUMP rule; MorphoLender.sol:282-293), script/launch/SafeBatch.s.sol:191 (market params). No other src/ or script/ caller of price(). No route found that bypasses the rule."
  }
 ],
 "notRun": [
  "[fork] configured token/feed decimals and live Chainlink rounds on 4663: NOT RUN (no RPC used)",
  "[data] F1 wall-clock duration on SPY/AAPL/SGOV: NOT RUN",
  "Earlier job submissions (api.imd.fun) not fetched: no finding to deduplicate"
 ],
 "tests": {
  "path": "test/scratch/SPrice.t.sol (extends test/utils/StockOracleBase.sol)",
  "source": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.38;\n\nimport {StockOracleBase} from \"../utils/StockOracleBase.sol\";\nimport {StockOracle} from \"../../src/stocks/StockOracle.sol\";\nimport {MockDecimals, MockPhasedFeed} from \"../utils/StockOracleMocks.sol\";\nimport {StocksConfig} from \"../../script/DeployConfig.sol\";\n\ncontract SPriceTest is StockOracleBase {\n    struct R { int256 a; uint256 t; }\n    R[][] internal ph; // reference copy of every phase's rounds\n\n    function setUp() public {\n        _deploy();\n        ph.push();\n    }\n\n    function _p(uint256 at, int256 a) internal {\n        if (vm.getBlockTimestamp() < at) vm.warp(at);\n        feed.pushAt(a, at);\n        ph[ph.length - 1].push(R(a, at));\n    }\n\n    function _newPhase() internal {\n        feed.newPhase();\n        ph.push();\n    }\n\n    /// Reference model of THE RULE, written from the NatSpec, reading only the test's own copy of the rounds.\n    function _model(bool sr, uint256 jump) internal view returns (bool, uint256, bytes4) {\n        R[] storage r = ph[ph.length - 1];\n        uint256 n = r.length;\n        int256 a0 = n == 0 ? int256(0) : r[n - 1].a;\n        uint256 t0 = n == 0 ? 0 : r[n - 1].t;\n        if (a0 <= 0 || uint256(a0) < MIN_ANSWER || uint256(a0) > MAX_ANSWER) return (false, 0, StockOracle.BadAnswer.selector);\n        if (t0 == 0 || t0 > block.timestamp) return (false, 0, StockOracle.BadTime.selector);\n        if (block.timestamp - t0 > 49 hours && cal.openTime(t0, block.timestamp) > 49 hours) {\n            return (false, 0, StockOracle.Stale.selector);\n        }\n        (uint8 kind,, uint64 open,) = cal.session(block.timestamp);\n        if (kind != 1) return (false, 0, StockOracle.Closed.selector);\n        if (n <= 1) return (false, 0, StockOracle.NoPrevious.selector);\n        int256 a1 = r[n - 2].a;\n        uint256 t1 = r[n - 2].t;\n        if (t1 == 0 || t1 > t0) return (false, 0, StockOracle.BadRound.selector);\n        if (a1 <= 0 || uint256(a1) < MIN_ANSWER || uint256(a1) > MAX_ANSWER) return (false, 0, StockOracle.BadAnswer.selector);\n        if (sr && t1 < open) return (false, 0, StockOracle.NotYet.selector);\n        uint256 x0 = uint256(a0);\n        uint256 x1 = uint256(a1);\n        uint256 d = x0 > x1 ? x0 - x1 : x1 - x0;\n        if (d * 10_000 > x1 * jump) return (false, 0, StockOracle.Jump.selector);\n        return (true, x0 < x1 ? x0 : x1, bytes4(0));\n    }\n\n    function _ans(uint256 s) internal pure returns (int256) {\n        uint256 m = s % 6;\n        if (m == 0) return int256(MIN_ANSWER) - 2 + int256((s >> 8) % 5);\n        if (m == 1) return int256(MAX_ANSWER) - 2 + int256((s >> 8) % 5);\n        if (m == 2) return int256((s >> 8) % 3) - 1;\n        if (m == 3) return int256(uint256(int256(P)) * 90 / 100 + (s >> 8) % uint256(int256(P) / 5));\n        if (m == 4) return int256(P) * 95 / 100 + int256((s >> 8) % 1000);\n        return int256((s >> 8) % (MAX_ANSWER * 2));\n    }\n\n    /// C3: differential fuzz of price() (both SESSION_ROUNDS settings) against the reference model over random round\n    /// sequences: several rounds per block, pre/post-market and weekend prints, phase changes, any query instant.\n    function testFuzz_C3_differential(uint256 seed, uint8 nRounds, uint256 q) public {\n        uint256 t = (seed % 2 == 0 ? monOpen - 30 minutes : friOpen - 7 hours) + (seed >> 1) % (seed % 3 == 0 ? 3 days : 7 hours);\n        vm.warp(t);\n        uint256 n = 1 + nRounds % 9;\n        int256 prev;\n        for (uint256 i; i < n; ++i) {\n            uint256 s = uint256(keccak256(abi.encode(seed, i)));\n            if (s % 11 == 0) _newPhase();\n            uint256 step = (s >> 32) % 4 == 0 ? 0 : ((s >> 36) % 3 == 0 ? (s >> 40) % 20 hours : (s >> 40) % 40 minutes);\n            t += step;\n            int256 a = (s >> 200) % 3 != 0 && prev > 0\n                ? prev * int256(9_400 + (s >> 210) % 1_200) / 10_000 // a move of -6%..+6% from the last print\n                : _ans(s >> 64);\n            if (a > 0 && uint256(a) < MIN_ANSWER + 1e6 && (s >> 220) % 2 == 0) a = int256(MIN_ANSWER) + int256((s >> 224) % 3) - 1;\n            _p(t, a);\n            prev = a;\n        }\n        vm.warp(t + (q % 3 == 0 ? q % 4 days : q % 1 hours));\n        for (uint256 k; k < 2; ++k) {\n            StockOracle x = k == 0 ? o : oS;\n            (bool okM, uint256 vM, bytes4 wM) = _model(k == 1, JUMP);\n            (bool ok, uint256 v, bytes4 w) = _try(x);\n            assertEq(ok, okM, \"priced vs model\");\n            assertEq(v, vM, \"value vs model\");\n            assertEq(w, wM, \"reason vs model\");\n        }\n    }\n\n    /// F1/F2/P1/P2: one wrong round (high or low) injected into an honest series. Whenever priced: never above either\n    /// answer, never above the honest-series price, never below min(honest of the same two rounds) x (1 - JUMP), and a\n    /// borrower at LLTV x that honest level, fully liquidated at the price with Morpho's LIF, leaves no bad debt, for every\n    /// configured (LLTV, JUMP).\n    function testFuzz_F1F2_oneWrongRound(uint256 h2, uint256 r1, uint256 r0, uint256 w, uint8 pos, uint8 tk) public {\n        StocksConfig.Ticker[] memory T = StocksConfig.tickers();\n        StocksConfig.Ticker memory tick = T[tk % T.length];\n        StockOracle.Config memory c = _cfg(false);\n        c.jump = tick.jump;\n        MockPhasedFeed fw = new MockPhasedFeed(8);\n        MockPhasedFeed fh = new MockPhasedFeed(8);\n        c.feed = address(fw);\n        StockOracle ow = new StockOracle(c);\n        c.feed = address(fh);\n        StockOracle oh = new StockOracle(c);\n        uint256[3] memory H;\n        H[0] = bound(h2, 20e8, 1000e8);\n        H[1] = H[0] * bound(r1, 8_000, 12_000) / 10_000; // honest moves, inside or past JUMP\n        H[2] = H[1] * bound(r0, 8_000, 12_000) / 10_000;\n        uint256 k = pos % 3;\n        uint256 wv = bound(w, MIN_ANSWER, MAX_ANSWER);\n        vm.warp(monOpen + 1 minutes);\n        for (uint256 i; i < 3; ++i) {\n            fh.pushAt(int256(H[i]), block.timestamp);\n            fw.pushAt(int256(i == k ? wv : H[i]), block.timestamp);\n            vm.warp(block.timestamp + 1 minutes);\n        }\n        (bool okW, uint256 pW,) = _try(ow);\n        if (!okW) return;\n        uint256 a0 = k == 2 ? wv : H[2];\n        uint256 a1 = k == 1 ? wv : H[1];\n        assertEq(pW, a0 < a1 ? a0 : a1, \"P1 min\");\n        assertLe(pW, a0, \"F2 <= latest\");\n        assertLe(pW, a1, \"F2 <= previous\");\n        uint256 hon = H[1] < H[2] ? H[1] : H[2];\n        if (k == 0) assertEq(pW, hon, \"a wrong round outside the pair is never read\");\n        else assertLe(pW, H[k == 1 ? 2 : 1], \"F2 never above the honest member of the pair\");\n        (bool okH, uint256 pH,) = _try(oh);\n        if (okH && k == 0) assertEq(pW, pH);\n        assertGe(pW * 10_000, hon * (10_000 - tick.jump), \"F1 floor: min(honest pair) x (1 - JUMP)\");\n        // Morpho: LIF = min(1.15, 1 / (1 - 0.3 (1 - LLTV))); seize all C at pW repays C x pW / LIF; debt C x LLTV x hon\n        uint256 lif = 1e36 / (1e18 - 0.3e18 * (1e18 - tick.lltv) / 1e18);\n        if (lif > 1.15e18) lif = 1.15e18;\n        uint256 C = 1e18;\n        uint256 debt = C * hon / 1e8 * tick.lltv / 1e18;\n        uint256 repaidAll = C * pW / 1e8 * 1e18 / lif;\n        assertGe(repaidAll, debt, \"P2 no bad debt from one wrong round\");\n    }\n\n    /// F1 as written: 100, 94 (wrong, past 5%), 98 -> 94; it prices only while it is one of the last two rounds.\n    function test_F1_example_and_duration() public {\n        _p(monOpen + 1 minutes, 100e8);\n        _p(monOpen + 2 minutes, 100e8);\n        _p(monOpen + 3 minutes, 94e8);\n        _unpriced(o, StockOracle.Jump.selector);\n        _p(monOpen + 4 minutes, 98e8);\n        assertEq(_priced(o), 94e8);\n        _p(monOpen + 5 minutes, 98e8);\n        assertEq(_priced(o), 98e8);\n        // within JUMP: wrong low prices as latest and through the corrective round, then drops\n        _p(monOpen + 6 minutes, 95e8);\n        assertEq(_priced(o), 95e8);\n        _p(monOpen + 7 minutes, 99e8);\n        assertEq(_priced(o), 95e8);\n        _p(monOpen + 8 minutes, 99e8);\n        assertEq(_priced(o), 99e8);\n    }\n\n    /// F6: at the open the price is the lower of the last two rounds (Friday close vs Monday's first print).\n    function test_F6_fastOpen() public {\n        _p(friClose - 1 minutes, 100e8);\n        _p(monOpen + 1, 104e8);\n        assertEq(_priced(o), 100e8);\n        _unpriced(oS, StockOracle.NotYet.selector);\n        _p(monOpen + 2, 104.5e8);\n        assertEq(_priced(o), 104e8);\n        assertEq(_priced(oS), 104e8);\n    }\n\n    /// C1: the JUMP comparison at MIN_ANSWER / MAX_ANSWER, MAX_ANSWER = uint128.max, JUMP = MAX_JUMP: exact, no overflow.\n    function testFuzz_C1_edges(uint256 a1, uint256 a0, uint256 j, bool top) public {\n        StockOracle.Config memory c = _cfg(false);\n        c.maxAnswer = type(uint128).max;\n        c.minAnswer = 1;\n        c.jump = bound(j, 1, 2_000);\n        MockPhasedFeed f = new MockPhasedFeed(8);\n        c.feed = address(f);\n        StockOracle x = new StockOracle(c);\n        uint256 lo = top ? type(uint128).max - 1e6 : 1;\n        a1 = bound(a1, lo, lo + 1e6);\n        a0 = bound(a0, lo, lo + 1e6);\n        vm.warp(monOpen + 1 minutes);\n        f.pushAt(int256(a1), block.timestamp);\n        f.pushAt(int256(a0), block.timestamp);\n        uint256 d = a0 > a1 ? a0 - a1 : a1 - a0;\n        bool within = d * 10_000 <= a1 * c.jump;\n        uint256 m = a0 < a1 ? a0 : a1;\n        bool fits = m <= type(uint256).max / SCALE;\n        try x.price() returns (uint256 p) {\n            assertTrue(within && fits, \"priced only within JUMP\");\n            assertEq(p, m * SCALE);\n        } catch (bytes memory e) {\n            if (!within) assertEq(bytes4(e), StockOracle.Jump.selector);\n            else assertFalse(fits, \"unexpected revert\");\n        }\n    }\n\n    /// C2: the constructor refuses minAnswer 0, minAnswer >= maxAnswer, JUMP > MAX_JUMP, JUMP 0, and a pulse without code.\n    function test_C2_constructor() public {\n        StockOracle.Config memory c = _cfg(false);\n        c.minAnswer = 0;\n        vm.expectRevert(StockOracle.BadConfig.selector);\n        new StockOracle(c);\n        c = _cfg(false);\n        c.minAnswer = c.maxAnswer;\n        vm.expectRevert(StockOracle.BadConfig.selector);\n        new StockOracle(c);\n        c = _cfg(false);\n        c.jump = 2_001;\n        vm.expectRevert(StockOracle.BadConfig.selector);\n        new StockOracle(c);\n        c = _cfg(false);\n        c.jump = 0;\n        vm.expectRevert(StockOracle.BadConfig.selector);\n        new StockOracle(c);\n        c = _cfg(false);\n        c.pulse = makeAddr(\"eoa\");\n        vm.expectRevert(StockOracle.BadConfig.selector);\n        new StockOracle(c);\n        c = _cfg(false);\n        c.jump = 2_000;\n        c.minAnswer = c.maxAnswer - 1;\n        new StockOracle(c);\n    }\n\n    /// P3: SCALE = 10^(36 + loan - collateral - feed) for any accepted decimals.\n    function testFuzz_P3_scale(uint8 ld, uint8 fd) public {\n        ld = uint8(bound(ld, 0, 36));\n        fd = uint8(bound(fd, 0, 36));\n        StockOracle.Config memory c = _cfg(false);\n        c.loanToken = address(new MockDecimals(ld));\n        c.feed = address(new MockPhasedFeed(fd));\n        if (18 + uint256(fd) > 36 + uint256(ld)) {\n            vm.expectRevert(StockOracle.BadConfig.selector);\n            new StockOracle(c);\n            return;\n        }\n        assertEq(new StockOracle(c).SCALE(), 10 ** (36 + uint256(ld) - 18 - fd));\n    }\n\n    /// P2 over the configured markets with MorphoLender's own arithmetic.\n    function test_P2_configuredMarkets() public pure {\n        StocksConfig.Ticker[] memory T = StocksConfig.tickers();\n        for (uint256 i; i < T.length; ++i) {\n            uint256 lif = 1e36 / (1e18 - 0.3e18 * (1e18 - T[i].lltv) / 1e18);\n            if (lif > 1.15e18) lif = 1.15e18;\n            assertLt(T[i].lltv * lif / 1e18 * 1e4, (1e4 - T[i].jump) * 1e18);\n        }\n    }\n}\n\n",
  "ran": "forge 1.9.0 test --use solar --match-path test/scratch/SPrice.t.sol --fuzz-runs 20000",
  "result": "Ran 8 tests: [PASS] testFuzz_C1_edges (runs: 20000) [PASS] testFuzz_C3_differential (runs: 20000) [PASS] testFuzz_F1F2_oneWrongRound (runs: 20000) [PASS] testFuzz_P3_scale (runs: 20000) [PASS] test_C2_constructor [PASS] test_F1_example_and_duration [PASS] test_F6_fastOpen [PASS] test_P2_configuredMarkets. 8 passed; 0 failed"
 }
}