{
 "lead": "usdc-precision",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "blocked": false,
 "hasCandidates": false,
 "candidates": [],
 "summary": "No fault found. On the real Midnight + VaultV2 + MidnightAdapter (deployed from compiled artifacts, 6-decimal ERC20Mock asset), dust fills of a ratified adapter maker buy offer by an untrusted taker do not cause drift that grows with fill count, never push realAssets above stored net credit, and give the taker no profit: Midnight rounds the assets paid to the taker down on every fill, so splitting costs the taker money. The only error is the documented rounding (rates floored on buys, NatSpec MidnightAdapter.sol:22), at about 1 unit of early-recognised interest per 0-asset dust fill.",
 "measurements": {
  "note": "The asset has 6 decimals, so 1 unit = 1e-6 USDC. TICK=4400 (about 0.994 assets/unit). Each scenario starts from a fresh setUp. All numbers are copied from the test output.",
  "A_single_1000u_7d": "paid 994, realAssets 994, netCredit 1000, netRate 9980518028 WAD/s; error 0",
  "C_single_200000u_7d": "paid 198820, realAssets 198820, netRate 9813188819; error 0",
  "D_1000_fills_x_200u_7d": "taker received 198000 in total (198 per fill vs 198.8 pro-rata, so the taker loses 0.8 unit per fill and 800 units per 1000 fills compared with one 200000u fill paying 198820). realAssets 198000 = paid, netRate 16701405590 (the vault earns a higher rate). realAssets rises monotonically to exactly 200000 at maturity (day1 198283 ... day7 200000)",
  "B_base1000u_then_1000_fills_x1u_7d": "each 1u fill pays the taker 0 assets. realAssets stays 994 (no jump), netCredit 1000->2000, netRate 9980518028->1673400189496. The taker gives 1000 units of debt for nothing",
  "E_single_1e15u_365d": "paid 994100700000000, realAssets 994100700020027: one-off +20027 units (~0.02 USDC, 2e-11 relative) from flooring netRate (188175680 WAD/s), as documented",
  "G_1000u_ttm_1s": "paid 994, realAssets 994, netRate 6036217303822937; error 0",
  "H_1e12u_ttm_1s": "paid 994100700000, realAssets 994100700000; error 0",
  "I_1u_alone": "reverts with panic 0x12 (division by zero), because buyerAssets=0 with no prior position. This is documented at MidnightAdapter.sol:546 ('Can revert if pre-buy amortized credit and buyerAssets are both 0'). The taker's fill fails and nothing is lost",
  "K_base1e15u_365d_then_1000x1u": "early-recognised interest 994 units in total (~0.001 USDC), 0 per fill after integer division (1 unit in N). netRate is unchanged at 188175680, so there is no compounding",
  "L_base1e15u_365d_then_1000x1e6u": "taker paid 994100000 in total. Early-recognised interest 700 units over 1000 fills (<1 unit per fill)",
  "M_base1e12u_90d_then_1000x1u": "994 units per 1000 fills (~0.001 USDC), realAssets <= netCredit",
  "N_base1e15u_365d_then_1x1u": "1 unit per fill"
 },
 "poc": {
  "path": "test/poc/UsdcPrecision.t.sol (measurement harness, not a finding)",
  "source": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport {Test, console} from \"../../lib/forge-std/src/Test.sol\";\nimport {IVaultV2} from \"../../src/interfaces/IVaultV2.sol\";\nimport {IVaultV2Factory} from \"../../src/interfaces/IVaultV2Factory.sol\";\nimport {IMidnight, Offer, Market, CollateralParams} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {IMidnightAdapter, IMidnightAdapterBase} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {IMidnightAdapterFactory} from \"../../src/adapters/midnight/interfaces/IMidnightAdapterFactory.sol\";\nimport {IMidnightAdapterPriceRatifierV1} from \"../../src/adapters/midnight/ratifiers/interfaces/IMidnightAdapterPriceRatifierV1.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {ERC20Mock} from \"../mocks/ERC20Mock.sol\";\n\n/// Local copy of lib/midnight/src/ratifiers/libraries/HashLib.sol hashPriceRatifierV1Offer (importing it OOMs/stack-too-deep on this machine).\nlibrary H {\n    function cp(CollateralParams memory c) internal pure returns (bytes32) {\n        return keccak256(abi.encode(bytes32(0x39ed3f928d24fd00574b1a02aba9c2483abcf5d9a3a366118c9a5aa29885b841), c.token, c.lltv, c.liquidationCursor, c.oracle));\n    }\n    function mk(Market memory m) internal pure returns (bytes32) {\n        bytes32[] memory hs = new bytes32[](m.collateralParams.length);\n        for (uint256 i; i < hs.length; i++) hs[i] = cp(m.collateralParams[i]);\n        return keccak256(abi.encode(bytes32(0x510b3862f3816a109c9340b76972e8a30984246be06e034ae12ed2934220391a), m.chainId, m.midnight, m.loanToken, keccak256(abi.encodePacked(hs)), m.maturity, m.rcfThreshold, m.enterGate, m.liquidatorGate));\n    }\n    function offer(Offer memory o) internal pure returns (bytes32) {\n        bytes memory a = abi.encode(bytes32(0x62a94097fbcb9b56e3cf7b4f7bb075b49540b1364815434ff4b16bc4decb303d), mk(o.market), o.buy, o.maker, o.start, o.expiry, o.tick, address(0), o.group);\n        bytes memory b = abi.encode(o.callback, keccak256(o.callbackData), o.receiverIfMakerIsSeller, o.ratifier, o.reduceOnly, o.maxUnits, o.maxAssets, o.continuousFeeCap);\n        return keccak256(bytes.concat(a, b));\n    }\n}\n\ncontract OracleMock {\n    uint256 public price;\n    function setPrice(uint256 p) external { price = p; }\n}\n\n/// Precision of MidnightAdapter with a 6-decimal asset on the real Midnight + VaultV2 (artifacts via deployCode).\ncontract UsdcPrecisionTest is Test {\n    uint256 constant TICK = 4400;\n    uint256 constant WAD = 1e18;\n    address owner = makeAddr(\"owner\");\n    address curator = makeAddr(\"curator\");\n    address allocator = makeAddr(\"allocator\");\n    address depositor = makeAddr(\"depositor\");\n    address taker = makeAddr(\"untrustedTaker\");\n\n    uint256 nonce;\n    ERC20Mock usdc;\n    ERC20Mock coll;\n    OracleMock oracle;\n    IVaultV2 vault;\n    IMidnight midnight;\n    IMidnightAdapter adapter;\n    IMidnightAdapterPriceRatifierV1 pr;\n\n    function setUp() public {\n        vm.setEvmVersion(\"osaka\");\n        usdc = new ERC20Mock(6);\n        coll = new ERC20Mock(18);\n        oracle = new OracleMock();\n        oracle.setPrice(1e36 * 1e6 / 1e18);\n        IVaultV2Factory vf = IVaultV2Factory(deployCode(\"VaultV2Factory.sol:VaultV2Factory\"));\n        vault = IVaultV2(vf.createVaultV2(owner, address(usdc), bytes32(0)));\n        vm.prank(owner);\n        vault.setCurator(curator);\n        _set(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (allocator, true)));\n        vm.prank(owner);\n        midnight = IMidnight(deployCode(\"Midnight.sol:Midnight\"));\n        vm.startPrank(owner);\n        midnight.enableLltv(1e18);\n        midnight.enableLiquidationCursor(0.25e18);\n        vm.stopPrank();\n        uint256[] memory d = new uint256[](1);\n        d[0] = 1;\n        IMidnightAdapterFactory f = IMidnightAdapterFactory(\n            deployCode(\"MidnightAdapterFactory.sol:MidnightAdapterFactory\", abi.encode(address(midnight))));\n        adapter = IMidnightAdapter(f.createMidnightAdapter(address(vault), d, address(0), bytes32(0)));\n        pr = IMidnightAdapterPriceRatifierV1(deployCode(\"MidnightAdapterPriceRatifierV1.sol:MidnightAdapterPriceRatifierV1\"));\n        _set(address(adapter), abi.encodeCall(IMidnightAdapterBase.increaseMaxTtm, (365 days)));\n        _set(address(vault), abi.encodeCall(IVaultV2.addAdapter, (address(adapter))));\n        _set(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (address(adapter), true)));\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(pr), true);\n        _caps(abi.encode(\"this\", address(adapter)));\n        _caps(abi.encode(\"collateralToken\", address(coll)));\n        Market memory m = _market(0);\n        _caps(abi.encode(\"collateralParams/rcfThreshold/liquidatorGate/enterGate\", m.collateralParams, m.rcfThreshold, m.liquidatorGate, m.enterGate));\n        _caps(abi.encode(\"this/duration\", address(adapter), uint256(1)));\n        deal(address(usdc), depositor, 1e16);\n        vm.startPrank(depositor);\n        usdc.approve(address(vault), type(uint256).max);\n        vault.deposit(1e16, depositor);\n        vm.stopPrank();\n    }\n\n    function _set(address t, bytes memory data) internal {\n        vm.prank(curator);\n        IVaultV2(t).submit(data);\n        (bool ok, bytes memory r) = t.call(data);\n        if (!ok) assembly { revert(add(r, 32), mload(r)) }\n    }\n\n    function _caps(bytes memory idData) internal {\n        _set(address(vault), abi.encodeCall(IVaultV2.increaseAbsoluteCap, (idData, type(uint128).max)));\n        _set(address(vault), abi.encodeCall(IVaultV2.increaseRelativeCap, (idData, 1e18)));\n    }\n\n    function _market(uint256 dur) internal view returns (Market memory m) {\n        CollateralParams[] memory c = new CollateralParams[](1);\n        c[0] = CollateralParams(address(coll), 1e18, 0.25e18, address(oracle));\n        m = Market(block.chainid, address(midnight), address(usdc), c, block.timestamp + dur, 0, address(0), address(0));\n    }\n\n    function _md(bytes32 id) internal view returns (uint256 nc, uint256 rate) {\n        (bool ok, bytes memory r) = address(adapter).staticcall(abi.encodeWithSignature(\"marketData(bytes32)\", id));\n        require(ok);\n        assembly { nc := mload(add(r, 32)) rate := mload(add(r, 64)) }\n    }\n\n    /// Ratified maker buy offer of the adapter, filled `fills` times with `upf` units by an untrusted taker.\n    function _run(uint256 fills, uint256 upf, uint256 dur, uint256 tick) internal returns (uint256 paid, uint256 ra, uint256 nc, uint256 rate) {\n        Market memory m = _market(dur);\n        uint256 total = fills * upf;\n        Offer memory o = Offer({market: m, buy: true, maker: address(adapter), start: block.timestamp, expiry: m.maturity,\n            tick: tick, group: keccak256(abi.encode(\"buy\", m.maturity, total, tick, ++nonce)), callback: address(adapter),\n            callbackData: abi.encode(address(0), \"\"), receiverIfMakerIsSeller: address(0), ratifier: address(adapter),\n            reduceOnly: false, maxUnits: uint128(total), maxAssets: 0, continuousFeeCap: type(uint256).max});\n        bytes32 root = H.offer(o);\n        vm.prank(allocator);\n        pr.setIsRootRatified(address(adapter), root, true, allocator);\n        bytes memory rd = abi.encode(address(pr), abi.encode(root, uint256(0), new bytes32[](0), address(0)));\n        uint256 c = total * 1e12 * 4 + 1e18;\n        deal(address(coll), taker, c);\n        vm.startPrank(taker);\n        coll.approve(address(midnight), c);\n        midnight.supplyCollateral(m, 0, c, taker);\n        uint256 b0 = usdc.balanceOf(taker);\n        for (uint256 i; i < fills; i++) midnight.take(o, rd, upf, taker, taker, address(0), \"\");\n        vm.stopPrank();\n        paid = usdc.balanceOf(taker) - b0;\n        ra = adapter.realAssets();\n        (nc, rate) = _md(IdLib.toId(m));\n    }\n\n    function _report(string memory tag, uint256 fills, uint256 upf, uint256 dur, uint256 tick) internal returns (uint256 paid, uint256 ra) {\n        uint256 nc; uint256 rate;\n        (paid, ra, nc, rate) = _run(fills, upf, dur, tick);\n        console.log(tag);\n        console.log(\"  fills / unitsPerFill / ttm:\", fills, upf, dur);\n        console.log(\"  paid / realAssets / netCredit:\", paid, ra, nc);\n        console.log(\"  netRate WAD/s:\", rate);\n        console.log(\"  realAssets-paid / paid-realAssets:\", ra > paid ? ra - paid : 0, paid > ra ? paid - ra : 0);\n        assertLe(ra, nc, \"realAssets > netCredit\");\n    }\n\n    function testA_single1000() public { _report(\"A single fill 1000u\", 1, 1000, 7 days, TICK); }\n    function testB_1000x1u_afterBase() public {\n        _report(\"B0 base fill 1000u\", 1, 1000, 7 days, TICK);\n        _report(\"B 1000 fills x 1u (0 assets each)\", 1000, 1, 7 days, TICK);\n    }\n    function testC_single200000() public { _report(\"C single fill 200000u\", 1, 200000, 7 days, TICK); }\n    function testD_1000x200() public { _report(\"D 1000 fills x 200u\", 1000, 200, 7 days, TICK); }\n    function testE_1e15_365d() public { _report(\"E single 1e15u ttm 365d\", 1, 1e15, 365 days, TICK); }\n    uint256 dp0; uint256 dra0; uint256 dp1; uint256 dra1; uint256 dnc; uint256 drate;\n    function _drift(string memory tag, uint256 base, uint256 fills, uint256 upf, uint256 dur) internal {\n        (dp0, dra0,,) = _run(1, base, dur, TICK);\n        (dp1, dra1, dnc, drate) = _run(fills, upf, dur, TICK);\n        console.log(tag);\n        console.log(\"  base paid / realAssets after base:\", dp0, dra0);\n        console.log(\"  dust fills / units each / assets paid to taker in total:\", fills, upf, dp1);\n        console.log(\"  realAssets after fills / netCredit / netRate:\", dra1, dnc, drate);\n        uint256 early = dra1 - dra0 - dp1;\n        console.log(\"  realAssets increase minus assets paid (early-recognised interest), total:\", early);\n        console.log(\"  per fill:\", early / fills);\n        assertLe(dra1, dnc);\n    }\n    function testK_1e15_365d_1000x1u() public { _drift(\"K base 1e15u 365d then 1000 x 1u\", 1e15, 1000, 1, 365 days); }\n    function testL_1e15_365d_1000x1e6u() public { _drift(\"L base 1e15u 365d then 1000 x 1e6u\", 1e15, 1000, 1e6, 365 days); }\n    function testM_1e12_90d_1000x1u() public { _drift(\"M base 1e12u 90d then 1000 x 1u\", 1e12, 1000, 1, 90 days); }\n    function testN_1e15_365d_1x1u() public { _drift(\"N base 1e15u 365d then 1 x 1u\", 1e15, 1, 1, 365 days); }\n    function testG_1000u_1s() public { _report(\"G 1000u ttm 1s\", 1, 1000, 1, TICK); }\n    function testH_1e12u_1s() public { _report(\"H 1e12u ttm 1s\", 1, 1e12, 1, TICK); }\n    function testI_1u_alone() public { _report(\"I 1u alone\", 1, 1, 7 days, TICK); }\n    function testJ_1e9_365d_1000xdust() public {\n        _report(\"J0 base 1e9u 365d\", 1, 1e9, 365 days, TICK);\n        _report(\"J 1000 fills x 1u\", 1000, 1, 365 days, TICK);\n    }\n\n    function testDustThenMaturity() public {\n        (uint256 paid,) = _report(\"D' 1000 fills x 200u\", 1000, 200, 7 days, TICK);\n        for (uint256 i; i < 7; i++) { skip(1 days); console.log(\"  day, realAssets\", i + 1, adapter.realAssets()); }\n        console.log(\"  paid\", paid);\n    }\n}\n",
  "command": "DECIMALS=6 forge test --skip 'src/adapters/Morpho*' --skip 'src/periphery/**' --match-path test/poc/UsdcPrecision.t.sol -vv",
  "output": "Ran 11 tests: 9 passed, 2 failed (expected: testI_1u_alone panic 0x12, which is documented; testF used tick 1, which is not accessible -> TickNotAccessible, a harness limitation). Separate run of testK/L/M/N: 4 passed. Key lines: 'D 1000 fills x 200u  paid / realAssets / netCredit: 198000 198000 200000'; 'K ... realAssets increase minus assets paid (early-recognised interest), total: 994  per fill: 0'; 'E single 1e15u ttm 365d  paid / realAssets / netCredit: 994100700000000 994100700020027 1000000000000000'.",
  "buildNote": "On this machine (1.5 GB cgroup) the full build and the integration test base were OOM-killed (solc SIGKILL), and importing lib/midnight HashLib hit stack-too-deep under its compilation restriction. So the harness deploys VaultV2Factory, Midnight, MidnightAdapterFactory and MidnightAdapterPriceRatifierV1 with deployCode (real artifacts built with the repo's foundry.toml) and copies hashPriceRatifierV1Offer locally. Other test files were moved aside in the scratch clone so they would not compile; nothing in src/ or lib/ was changed."
 },
 "lowInfo": [
  {
   "title": "Dust fills of 0 assets on an existing position recognise ~1 unit of interest early per fill (no compounding)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:540-547",
    "src/adapters/midnight/MidnightAdapter.sol:859"
   ],
   "detail": "When a 1-unit fill pays 0 assets, amortizedValue = old amortized + 0, so the stored rate floors to almost the same value, and realAssets gains about the discounted value of the extra unit (~0.994 unit). Measured: 994 units per 1000 fills on 1e12u/90d and on 1e15u/365d positions. The taker funds all of this by taking 1 unit of debt for 0 assets, so there is no profit for anyone and the impact is ~1e-9 USDC per fill. This is covered by the NatSpec rounding notes at :22 and :24."
  },
  {
   "title": "One-off rate-floor gain scales with position x ttm (~2e-11 relative)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:547"
   ],
   "detail": "Flooring netRate to whole WAD-per-second units overvalues a position by up to amortized*ttm/1e18 units. For 1e15 units (1e9 USDC) at 365 days this was 20027 units (0.02 USDC) right after the buy, and it does not grow with later fills. Documented (NatSpec :22)."
  },
  {
   "title": "First fill of 1 unit (0 assets) reverts with a division by zero instead of a named error",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:546-547"
   ],
   "detail": "A panic 0x12 shows up in the taker's Midnight.take. This is documented and causes no loss. A named error would make it easier to diagnose."
  }
 ],
 "covered": [
  "Real-stack measurement with a 6-decimal asset of netRate, realAssets and net credit for positions from 1 unit to 1e15 units and ttm of 1s, 7d, 90d and 365d",
  "Dust fills (1u, 200u, 1e6u) repeated 1000 times by an untrusted taker against a ratified adapter maker buy offer: per-fill and per-1000-fill error",
  "Check that realAssets <= stored netCredit (asserted in every scenario)",
  "Taker profit from splitting (none: the taker loses 0.8 unit per 200u fill)",
  "Accrual path to maturity after dust fills (monotone, ends exactly at net credit)",
  "Rate-rounds-to-zero / 0-asset fills (revert when there is no position; negligible early interest otherwise)",
  "Checked against the NatSpec accepted risks (MidnightAdapter.sol:20-24)"
 ],
 "notCovered": [
  "Shortfall spread with tiny interest (onSell lines 643-682): this needs an allocator/sentinel sale, so it was not measured. UNVERIFIED",
  "Maker sell / taker sell paths and forceDeallocate rounding with 6 decimals",
  "Ticks other than 4400 (tick 1 was not accessible in the harness)",
  "The prior audit PDFs were not read; this matters little because no candidate is reported",
  "The repository's full test suite was not run, because the build was OOM-killed on this machine (1.5 GB limit)"
 ]
}