{"lead": "maker-offers: the adapter as maker; fill-time checks of offers ratified by its sub-ratifiers and taken by an outsider through Midnight", "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286", "hasCandidates": false, "candidates": [], "lowInfo": [{"title": "Stale ratified roots revive when a sub-ratifier is disabled then re-enabled", "class": "Informational", "verified": true, "refs": ["src/adapters/midnight/MidnightAdapter.sol:348", "src/adapters/midnight/MidnightAdapter.sol:504", "src/adapters/midnight/ratifiers/MidnightAdapterPriceRatifierV1.sol:107"], "detail": "setIsSubRatifier(false) only flips isSubRatifier; roots stay ratified in the sub-ratifier. testSubRatifierToggleRevivesOffer: the live buy offer reverts with SubRatifierFailed while disabled, then after setIsSubRatifier(true) the same offer and proof fill (netCredit 1000e18). Not an outsider-caused fault (needs an allocator toggle) and close to the documented behaviour that approved roots persist after allocator removal, but the NatSpec does not say that disabling a sub-ratifier is not a way to cancel offers. Suggest documenting it, or scoping ratification to a per-sub-ratifier epoch."}, {"title": "A 1-unit first fill on a fresh market reverts with a raw panic (division by zero)", "class": "Informational", "verified": true, "refs": ["src/adapters/midnight/MidnightAdapter.sol:544", "src/adapters/midnight/MidnightAdapter.sol:547"], "detail": "testFirstDustFillPanics: on a market the adapter has no position in, a 1-unit fill at tick 4400 gives buyerAssets = 0, so amortizedValue is 0 and mulDivDown(WAD, amortizedValue * ttm) panics with 0x12 instead of a named error. Partly acknowledged by the comment at line 546. Only the taker's own transaction fails, so there is no vault impact. A named revert would be clearer."}, {"title": "Zero-unit fills are accepted and change no adapter state", "class": "Informational", "verified": true, "refs": ["src/adapters/midnight/MidnightAdapter.sol:510"], "detail": "testZeroAndDustFills: take(units=0) succeeds before and after a position exists; netCredit, netRate and consumed are unchanged (only Take/Buy events are emitted). Ten 1-unit fills after a 500e18 fill added 10 units of credit and left the rate at 9812017633. No impact found."}], "covered": ["Built with forge build src lib/midnight/src/Midnight.sol; ran the real-Midnight integration suite plus test/poc/MakerOffersPoC.t.sol (subclass of MidnightAdapterIntegrationTest): 20 passed, 0 failed (9 inherited integration tests, 11 new).", "testMaxTtmDecreaseBlocksLiveBuy: live buy offer reverts BuyTtmTooHigh after decreaseMaxTtm(1 day). PASS.", "testMinNetBuyRateIncreaseBlocksLiveBuy: reverts NetBuyRateTooLow after increaseMinNetBuyRate; a better-priced offer (tick 3000) still fills. PASS.", "testMaxNetSellRateDecreaseBlocksLiveSell: live sell offer reverts NetSellRateTooHigh after decreaseMaxNetSellRate(0). PASS.", "testForceSellableOnLiveOffers: buy reverts UnauthorizedBuy; sell reverts ForceSellPriceTooLow at minForceSellPrice 0.999e18 and fills at 0.99e18. PASS.", "testForceRemoveBlocksLiveOffers: live buy and sell both revert ForceRemoved. PASS.", "testSubRatifierToggleRevivesOffer: see lowInfo. PASS.", "testAllocatorRemovedOfferStillLive: after the allocator is removed an already ratified offer still fills (netCredit 1000e18); documented behaviour. PASS.", "testPostMaturity: after maturity a credit-holding taker's buy fill reverts BuyPostMaturity; a debt-increasing taker is stopped by Midnight first; a live sell offer at price<1 reverts NetSellRateTooHigh. PASS.", "testPartialFillsMatchSingleFill: one 3000e18 fill vs 3x1000e18 fills give identical netCredit 3000e18, netRate 9812017633 and realAssets 2982302100000912588776; a further 1 unit reverts and consumed stays 3000e18. PASS.", "testZeroAndDustFills and testFirstDustFillPanics: see lowInfo. PASS.", "testLoopBuySellSameTaker: one taker looped 20x (sell offer 3 units, buy offer 3 units) and 5x (7000e18 units) at the same tick; vault totalAssets stayed 100000e18, adapter netCredit stayed 10000e18, and the taker balance fell by 20 wei (1000000009941007000000000000000 -> 1000000009941006999999999999980). No profit. PASS.", "Read in full: MidnightAdapter.sol, both ratifiers, Midnight.take."], "notCovered": ["MidnightAdapterRateRatifierV1 fills were not run; only the price ratifier. Its isRatified is read-only code that reads block.timestamp at fill time.", "Crossing buy/sell offers at different ticks or rates (profit loop) were not run beyond the same-tick loop; that needs allocator-ratified crossing prices, which is trusted behaviour.", "setConsumed and shared groups between a buy and a sell offer were not tested.", "Fills with a fee-charging Midnight market (settlement or continuous fee), losses/bad debt interaction with live offers, enter-gated markets, and no independent re-run from a clean clone (UNVERIFIED by a second agent).", "No candidate found, so no Cantina severity classification was made."], "testSource": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {MidnightAdapterIntegrationTest} from \"../integration/MidnightAdapterIntegrationTest.sol\";\nimport {IMidnightAdapterBase} from \"../../src/adapters/midnight/interfaces/IMidnightAdapter.sol\";\nimport {IVaultV2} from \"../../src/interfaces/IVaultV2.sol\";\nimport {SafeERC20Lib} from \"../../src/libraries/SafeERC20Lib.sol\";\nimport {WAD} from \"../../src/libraries/ConstantsLib.sol\";\nimport {IMidnight, Market, Offer} from \"../../lib/midnight/src/interfaces/IMidnight.sol\";\nimport {HashLib} from \"../../lib/midnight/src/ratifiers/libraries/HashLib.sol\";\nimport {IdLib} from \"../../lib/midnight/src/libraries/IdLib.sol\";\nimport {TickLib} from \"../../lib/midnight/src/libraries/TickLib.sol\";\nimport {console} from \"forge-std/console.sol\";\nimport {stdError} from \"forge-std/StdError.sol\";\n\n/// @dev Fill-time checks of the adapter as maker. Each test builds ratified offers, changes one parameter, then fills as an outsider.\ncontract MakerOffersPoC is MidnightAdapterIntegrationTest {\n    Market internal m;\n    bytes32 internal mid;\n    uint256 internal constant U = 1000e18;\n\n    modifier init() {\n        _init();\n        _;\n    }\n\n    function _init() internal {\n        m = _market(7 days);\n        mid = IdLib.toId(m);\n        // outsider borrower with plenty of collateral and loan token\n        deal(address(collateralToken), borrower, 1e30);\n        deal(address(underlyingToken), borrower, 1e30);\n        vm.startPrank(borrower);\n        collateralToken.approve(address(midnight), type(uint256).max);\n        midnight.supplyCollateral(m, 0, 1e30, borrower);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        vm.stopPrank();\n    }\n\n    function _offer(bool buy, bytes32 group, uint256 units, uint256 expiry) internal view returns (Offer memory) {\n        return Offer({\n            market: m,\n            buy: buy,\n            maker: address(adapter),\n            start: block.timestamp,\n            expiry: expiry,\n            tick: TICK,\n            group: group,\n            callback: address(adapter),\n            callbackData: buy ? abi.encode(address(0), \"\") : bytes(\"\"),\n            receiverIfMakerIsSeller: buy ? address(0) : address(adapter),\n            ratifier: address(adapter),\n            reduceOnly: !buy,\n            maxUnits: uint128(units),\n            maxAssets: 0,\n            continuousFeeCap: type(uint256).max\n        });\n    }\n\n    function _ratify(Offer memory o) internal returns (bytes memory data, bytes32 root) {\n        root = HashLib.hashPriceRatifierV1Offer(o, address(0));\n        vm.prank(allocator);\n        priceSubRatifier.setIsRootRatified(address(adapter), root, true, allocator);\n        data = _data(root);\n    }\n\n    function _data(bytes32 root) internal view returns (bytes memory) {\n        bytes32[] memory proof = new bytes32[](0);\n        return abi.encode(address(priceSubRatifier), abi.encode(root, uint256(0), proof, address(0)));\n    }\n\n    function _fillBuy(Offer memory o, bytes memory d, uint256 u) internal {\n        vm.prank(borrower);\n        midnight.take(o, d, u, borrower, borrower, address(0), \"\");\n    }\n\n    function _fillSell(Offer memory o, bytes memory d, uint256 u) internal {\n        vm.prank(borrower);\n        midnight.take(o, d, u, borrower, address(0), address(0), \"\");\n    }\n\n    function _md() internal view returns (uint128 nc, uint64 rate) {\n        (nc, rate,,,,,) = IMidnightAdapterStaticTypingView(address(adapter)).marketData(mid);\n    }\n\n    function _seedBuy(uint256 units) internal returns (Offer memory o, bytes memory d) {\n        o = _offer(true, keccak256(\"seed\"), units, m.maturity);\n        (d,) = _ratify(o);\n        _fillBuy(o, d, units);\n    }\n\n    // 1. maxTtm decreased after ratification: live buy offer must stop filling\n    function testMaxTtmDecreaseBlocksLiveBuy() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        vm.prank(curator);\n        adapter.decreaseMaxTtm(1 days);\n        vm.expectRevert(IMidnightAdapterBase.BuyTtmTooHigh.selector);\n        _fillBuy(o, d, U);\n        console.log(\"maxTtm=1d: buy with ttm 7d reverted BuyTtmTooHigh\");\n    }\n\n    // 2. minNetBuyRate increased\n    function testMinNetBuyRateIncreaseBlocksLiveBuy() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        vm.prank(curator);\n        adapter.increaseMinNetBuyRate(1e18 / uint256(365 days));\n        vm.expectRevert(IMidnightAdapterBase.NetBuyRateTooLow.selector);\n        _fillBuy(o, d, U);\n        // boundary: a rate just below the offer's implied rate fills.\n        // cannot decrease without timelock: use a fresh offer at a better price instead\n        Offer memory o2 = _offer(true, keccak256(\"b\"), U, m.maturity);\n        o2.tick = 3000;\n        (bytes memory d2,) = _ratify(o2);\n        _fillBuy(o2, d2, U);\n        (uint128 nc, uint64 r) = _md();\n        console.log(\"better-priced offer (tick 3000) fills; netCredit\", nc, \"netRate\", r);\n    }\n\n    // 3. maxNetSellRate decreased\n    function testMaxNetSellRateDecreaseBlocksLiveSell() public init {\n        _seedBuy(2 * U);\n        Offer memory s = _offer(false, keccak256(\"s\"), U, m.maturity);\n        (bytes memory d,) = _ratify(s);\n        vm.prank(curator);\n        adapter.decreaseMaxNetSellRate(0);\n        vm.expectRevert(IMidnightAdapterBase.NetSellRateTooHigh.selector);\n        _fillSell(s, d, U);\n    }\n\n    // 4. forceSellable: buys blocked; sells then bounded by minForceSellPrice (default 0)\n    function testForceSellableOnLiveOffers() public init {\n        (Offer memory b, bytes memory bd) = _seedBuy(2 * U);\n        Offer memory b2 = _offer(true, keccak256(\"b2\"), U, m.maturity);\n        (bytes memory d2,) = _ratify(b2);\n        Offer memory s = _offer(false, keccak256(\"s\"), U, m.maturity);\n        (bytes memory sd,) = _ratify(s);\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.setForceSellable, (mid)));\n        vm.expectRevert(IMidnightAdapterBase.UnauthorizedBuy.selector);\n        _fillBuy(b2, d2, U);\n        // set a floor above the offer price -> sell reverts\n        vm.prank(curator);\n        adapter.setMinForceSellPrice(mid, 0.999e18);\n        vm.expectRevert(IMidnightAdapterBase.ForceSellPriceTooLow.selector);\n        _fillSell(s, sd, U);\n        vm.prank(curator);\n        adapter.setMinForceSellPrice(mid, 0.99e18);\n        _fillSell(s, sd, U);\n        b;\n        bd;\n        console.log(\"forceSellable: buy blocked, sell gated by minForceSellPrice\");\n    }\n\n    // 5. forceRemove: both sides revert\n    function testForceRemoveBlocksLiveOffers() public init {\n        _seedBuy(2 * U);\n        Offer memory b2 = _offer(true, keccak256(\"b2\"), U, m.maturity);\n        (bytes memory d2,) = _ratify(b2);\n        Offer memory s = _offer(false, keccak256(\"s\"), U, m.maturity);\n        (bytes memory sd,) = _ratify(s);\n        _submitAndSet(address(adapter), abi.encodeCall(IMidnightAdapterBase.forceRemove, (mid)));\n        vm.expectRevert(IMidnightAdapterBase.ForceRemoved.selector);\n        _fillBuy(b2, d2, U);\n        vm.expectRevert(IMidnightAdapterBase.ForceRemoved.selector);\n        _fillSell(s, sd, U);\n        console.log(\"forceRemoved market: live buy and sell both revert; adapter credit left in midnight:\");\n        (, uint128 cr,,,,) = midnight.position(mid, address(adapter));\n        console.log(cr);\n    }\n\n    // 6. sub-ratifier disabled then re-enabled: stale offer becomes live again\n    function testSubRatifierToggleRevivesOffer() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(priceSubRatifier), false);\n        vm.expectRevert(IMidnightAdapterBase.SubRatifierFailed.selector);\n        _fillBuy(o, d, U);\n        vm.prank(allocator);\n        adapter.setIsSubRatifier(address(priceSubRatifier), true);\n        _fillBuy(o, d, U);\n        (uint128 nc,) = _md();\n        console.log(\"after disable+enable, old offer filled: netCredit\", nc);\n        assertEq(nc, U);\n    }\n\n    // 7. allocator removed: ratified root still fills (documented)\n    function testAllocatorRemovedOfferStillLive() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        _submitAndSet(address(vault), abi.encodeCall(IVaultV2.setIsAllocator, (allocator, false)));\n        _fillBuy(o, d, U);\n        (uint128 nc,) = _md();\n        console.log(\"allocator removed, offer still filled: netCredit\", nc);\n    }\n\n    // 8. after maturity: buy reverts, sell at price<1 reverts\n    function testPostMaturity() public init {\n        _seedBuy(2 * U);\n        Offer memory b2 = _offer(true, keccak256(\"b2\"), U, m.maturity + 30 days);\n        (bytes memory d2,) = _ratify(b2);\n        Offer memory s = _offer(false, keccak256(\"s\"), U, m.maturity + 30 days);\n        (bytes memory sd,) = _ratify(s);\n        // lender buys credit from the adapter before maturity so that it can sell it back after maturity without new debt\n        deal(address(underlyingToken), lender, 10 * U);\n        vm.startPrank(lender);\n        SafeERC20Lib.safeApprove(address(underlyingToken), address(midnight), type(uint256).max);\n        midnight.take(s, sd, U, lender, address(0), address(0), \"\");\n        vm.stopPrank();\n        Offer memory s2 = _offer(false, keccak256(\"s2\"), U, m.maturity + 30 days);\n        (bytes memory sd2,) = _ratify(s2);\n        vm.warp(m.maturity + 1);\n        // borrower (would add debt): Midnight rejects first\n        vm.expectRevert();\n        _fillBuy(b2, d2, U);\n        // lender (credit holder): reaches onBuy\n        vm.prank(lender);\n        vm.expectRevert(IMidnightAdapterBase.BuyPostMaturity.selector);\n        midnight.take(b2, d2, U, lender, lender, address(0), \"\");\n        vm.expectRevert(IMidnightAdapterBase.NetSellRateTooHigh.selector);\n        vm.prank(lender);\n        midnight.take(s2, sd2, U, lender, address(0), address(0), \"\");\n    }\n\n    // 9. partial/repeated fills vs one fill\n    function testPartialFillsMatchSingleFill() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), 3 * U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        uint256 snap = vm.snapshotState();\n        _fillBuy(o, d, 3 * U);\n        (uint128 ncA, uint64 rA) = _md();\n        uint256 raA = adapter.realAssets();\n        vm.revertToState(snap);\n        _fillBuy(o, d, U);\n        _fillBuy(o, d, U);\n        _fillBuy(o, d, U);\n        (uint128 ncB, uint64 rB) = _md();\n        uint256 raB = adapter.realAssets();\n        console.log(\"single: nc/rate/realAssets\", ncA, rA, raA);\n        console.log(\"3 pieces: nc/rate/realAssets\", ncB, rB, raB);\n        assertEq(ncA, ncB);\n        // exceeding maxUnits\n        vm.expectRevert();\n        _fillBuy(o, d, 1);\n        assertEq(midnight.consumed(address(adapter), o.group), 3 * U);\n    }\n\n    // 10. zero-unit fills and 1-unit dust fills\n    function testZeroAndDustFills() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        _fillBuy(o, d, 0); // first-ever zero fill\n        _fillBuy(o, d, U / 2);\n        (uint128 nc, uint64 r) = _md();\n        console.log(\"after zero fill nc/rate\", nc, r);\n        assertEq(nc, U / 2);\n        for (uint256 i; i < 10; i++) {\n            _fillBuy(o, d, 1);\n        }\n        (nc, r) = _md();\n        console.log(\"after 10x 1-unit dust fills: nc/rate\", nc, r);\n        console.log(\"consumed\", midnight.consumed(address(adapter), o.group));\n        console.log(\"adapter realAssets\", adapter.realAssets());\n        _fillBuy(o, d, 0);\n        (nc, r) = _md();\n        console.log(\"after another zero fill nc/rate\", nc, r);\n    }\n\n    // 10b. 1-unit first fill on a fresh market: buyerAssets rounds to 0 and onBuy divides by zero\n    function testFirstDustFillPanics() public init {\n        Offer memory o = _offer(true, keccak256(\"a\"), U, m.maturity);\n        (bytes memory d,) = _ratify(o);\n        vm.expectRevert(stdError.divisionError);\n        _fillBuy(o, d, 1);\n        console.log(\"first 1-unit fill on a fresh market reverts with division by zero (MidnightAdapter.sol:547)\");\n    }\n\n    // 11. buy then sell by the same taker in a loop at the same tick: taker profit?\n    function testLoopBuySellSameTaker() public init {\n        (Offer memory b0,) = _seedBuy(10 * U);\n        b0;\n        Offer memory b = _offer(true, keccak256(\"lb\"), 1e30, m.maturity);\n        (bytes memory bd,) = _ratify(b);\n        Offer memory s = _offer(false, keccak256(\"ls\"), 1e30, m.maturity);\n        (bytes memory sd,) = _ratify(s);\n        vault.accrueInterest();\n        uint256 ta0 = vault.totalAssets();\n        uint256 bal0 = underlyingToken.balanceOf(borrower);\n        uint256 nc0;\n        (nc0,) = _md();\n        uint256 n = 20;\n        // taker buys credit from adapter (sell offer) then sells it back (buy offer): 1 unit dust and 1e18-unit rounds\n        for (uint256 i; i < n; i++) {\n            _fillSell(s, sd, 3);\n            _fillBuy(b, bd, 3);\n        }\n        for (uint256 i; i < 5; i++) {\n            _fillSell(s, sd, 7 * U);\n            _fillBuy(b, bd, 7 * U);\n        }\n        vault.accrueInterest();\n        uint256 ta1 = vault.totalAssets();\n        uint256 bal1 = underlyingToken.balanceOf(borrower);\n        (uint128 nc1,) = _md();\n        console.log(\"vault totalAssets before/after\", ta0, ta1);\n        console.log(\"taker balance before/after\", bal0, bal1);\n        console.log(\"adapter nc before/after\", nc0, nc1);\n        assertGe(ta1, ta0, \"vault lost\");\n        assertLe(bal1, bal0, \"taker gained\");\n    }\n}\n\ninterface IMidnightAdapterStaticTypingView {\n    function marketData(bytes32 marketId)\n        external\n        view\n        returns (uint128, uint64, uint40, uint8, bool, bool, uint256);\n}\n", "testCommand": "forge test --match-path test/poc/MakerOffersPoC.t.sol -vv", "testOutput": "Compiler run successful!\nRan 20 tests for test/poc/MakerOffersPoC.t.sol:MakerOffersPoC\n[PASS] testAllocatorRemovedOfferStillLive() (gas: 1733275)\nLogs:\n  allocator removed, offer still filled: netCredit 1000000000000000000000\n[PASS] testFirstDustFillPanics() (gas: 1395600)\nLogs:\n  first 1-unit fill on a fresh market reverts with division by zero (MidnightAdapter.sol:547)\n[PASS] testForceDeallocate() (gas: 1751917)\n[PASS] testForceRemoveBlocksLiveOffers() (gas: 2309175)\nLogs:\n  forceRemoved market: live buy and sell both revert; adapter credit left in midnight:\n  0\n[PASS] testForceSell() (gas: 1654022)\n[PASS] testForceSellableOnLiveOffers() (gas: 2581623)\nLogs:\n  forceSellable: buy blocked, sell gated by minForceSellPrice\n[PASS] testLoopBuySellSameTaker() (gas: 14372365)\nLogs:\n  vault totalAssets before/after 100000000000000000000000 100000000000000000000000\n  taker balance before/after 1000000009941007000000000000000 1000000009941006999999999999980\n  adapter nc before/after 10000000000000000000000 10000000000000000000000\n[PASS] testMakerBuy() (gas: 1130965)\n[PASS] testMakerSell() (gas: 1922757)\n[PASS] testMaxNetSellRateDecreaseBlocksLiveSell() (gas: 1940836)\n[PASS] testMaxTtmDecreaseBlocksLiveBuy() (gas: 1402759)\nLogs:\n  maxTtm=1d: buy with ttm 7d reverted BuyTtmTooHigh\n[PASS] testMinNetBuyRateIncreaseBlocksLiveBuy() (gas: 1955085)\nLogs:\n  better-priced offer (tick 3000) fills; netCredit 1000000000000000000000 netRate 10570814876714\n[PASS] testPartialFillsMatchSingleFill() (gas: 2805531)\nLogs:\n  single: nc/rate/realAssets 3000000000000000000000 9812017633 2982302100000912588776\n  3 pieces: nc/rate/realAssets 3000000000000000000000 9812017633 2982302100000912588776\n[PASS] testPostMaturity() (gas: 2932365)\n[PASS] testRepayWithdrawRedeem() (gas: 1782025)\n[PASS] testSubRatifierToggleRevivesOffer() (gas: 1791177)\nLogs:\n  after disable+enable, old offer filled: netCredit 1000000000000000000000\n[PASS] testTakerBuy() (gas: 1167552)\n[PASS] testTakerSell() (gas: 1960260)\n[PASS] testWrapperGateForceDeallocateAfterRevocation() (gas: 17209715)\n[PASS] testZeroAndDustFills() (gas: 4822177)\nLogs:\n  after zero fill nc/rate 500000000000000000000 9812017633\n  after 10x 1-unit dust fills: nc/rate 500000000000000000010 9812017633\n  consumed 500000000000000000010\n  adapter realAssets 497050350000152098139\n  after another zero fill nc/rate 500000000000000000010 9812017633\nSuite result: ok. 20 passed; 0 failed; 0 skipped; finished in 40.11ms (80.65ms CPU time)\nRan 1 test suite in 41.48ms (40.11ms CPU time): 20 tests passed, 0 failed, 0 skipped (20 total tests)"}