From aa7fc2c642ca6de074cfc1c0c677f60a817b86c3 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Fri, 11 Sep 2026 11:04:48 +0100 Subject: [PATCH 1/3] fix: reserve gas for reporter callback completion --- src/reporters/OOReporter.sol | 31 ++------ src/reporters/README.md | 24 +++--- .../integrations/PolymarketOOReporter.sol | 13 +++- src/reporters/interfaces/IOOReporter.sol | 4 +- test/reporters/OOReporter.t.sol | 51 ------------- test/reporters/PolymarketOOReporter.t.sol | 73 +++++++++++++++++-- 6 files changed, 102 insertions(+), 94 deletions(-) diff --git a/src/reporters/OOReporter.sol b/src/reporters/OOReporter.sol index 225fd8b..a02c2e7 100644 --- a/src/reporters/OOReporter.sol +++ b/src/reporters/OOReporter.sol @@ -450,12 +450,14 @@ contract OOReporter is bytes32[] storage requestIds = _getStorage().requestIdsByReporterRequestKey[reporterRequestKey]; // Backfill untouched pre-array requests before emitting events and invoking callbacks. if (requestIds.length == 0) requestIds.push(requestId); - for (uint256 i = 0; i < requestIds.length; ++i) { - emit RequestResolved(requestIds[i], timestamp, price); - } - try this.executeResolutionCallbacks(reporterRequestKey) {} - catch { - emit ResolutionCallbacksFailed(requestId, timestamp); + // A callback may register another ID; leave it for late initialization. + uint256 requestIdsLength = requestIds.length; + for (uint256 i = 0; i < requestIdsLength; ++i) { + bytes32 linkedRequestId = requestIds[i]; + RequestData storage registration = _getStorage().requests[linkedRequestId]; + registration.initialized = true; + emit RequestResolved(linkedRequestId, timestamp, price); + _onRequestResolved(linkedRequestId, registration.requester); } } } @@ -495,23 +497,6 @@ contract OOReporter is _executeAutomaticRerequest(requestId, request, rerequestType); } - /// @dev Isolates the bounded callback fan-out so an out-of-gas failure cannot revert settlement state or - /// already-emitted resolution events. - /// @param reporterRequestKey Key for the linked request IDs whose callbacks should be executed. - function executeResolutionCallbacks(bytes32 reporterRequestKey) external { - if (msg.sender != address(this)) revert CallerNotSelf(); - - OOReporterStorage storage $ = _getStorage(); - bytes32[] storage requestIds = $.requestIdsByReporterRequestKey[reporterRequestKey]; - uint256 requestIdsLength = requestIds.length; - for (uint256 i = 0; i < requestIdsLength; ++i) { - bytes32 linkedRequestId = requestIds[i]; - RequestData storage registration = $.requests[linkedRequestId]; - registration.initialized = true; - _onRequestResolved(linkedRequestId, registration.requester); - } - } - /// @inheritdoc IOOReporter function claimDeferredPayout(address repaymentAddress) external onlyOwner { if (repaymentAddress == address(0)) revert AddressCannotBeZero(); diff --git a/src/reporters/README.md b/src/reporters/README.md index b29075d..f557aef 100644 --- a/src/reporters/README.md +++ b/src/reporters/README.md @@ -179,16 +179,20 @@ After storing a non-P4 final outcome, `PolymarketOOReporter` calls `report(reque the module that registered it. The reporter commits its shared resolved state before making these external calls, so the module can read the outcome using any associated request ID during `report`. -The reporter first emits `RequestResolved` for every associated request ID, then runs the callback fan-out in an external -self-call wrapped in `try/catch`. Both loops are bounded by the ten-ID registration limit. If the callback fan-out -reverts, including because it runs out of gas, the stored resolution, all resolution events, and Managed OO settlement -remain successful and the reporter emits `ResolutionCallbacksFailed(requestId, requestTimestamp)`. Earlier callbacks -from that reverted fan-out are rolled back, so operators must call each module's permissionless `report(requestId)` -individually off-chain. - -Each callback is wrapped in `try/catch`. If the call returns without reverting, the reporter emits -`ReportCallbackSucceeded(requestId, reporterModule)`. If the module reverts, Managed OO settlement still succeeds and -the reporter emits `ReportCallbackFailed(requestId, reporterModule)`. The module's permissionless `report(requestId)` +The reporter uses one loop, bounded by the ten-ID registration limit, to emit each ID's `RequestResolved` event and +then attempt its callback. The loop length is captured before any callback, so reentrant registrations wait for late +initialization. There is no outer callback self-call or batch catch; successful callbacks persist if a later one fails. + +Before each external `report` call, the Polymarket integration subtracts a proposed 150,000 gas reserve from `gasleft()`. +If no callback budget remains, it emits `ReportCallbackFailed` and returns to the loop, which continues emitting all +remaining resolution events. The reserve must cover the remaining registration writes, resolution/failure events, +loop overhead, gas spent between measuring and forwarding gas, and the enclosing settlement return path. This value +is a review candidate, not a general proof: it assumes sufficient transaction gas and must be validated against the +production call path and gas schedule. The base reporter's internal hook is trusted; derived integrations must bound +and catch their own external calls. + +Each attempted callback is wrapped in `try/catch`. A successful call emits `ReportCallbackSucceeded`; a reverted or +skipped call emits `ReportCallbackFailed`. The module's permissionless `report(requestId)` entry point can then be retried separately. P4 settlements and stale, unknown, or repeated settlement callbacks do not trigger reporting. A newly registered ID for an already-resolved shared request follows the initialization behavior described above. diff --git a/src/reporters/integrations/PolymarketOOReporter.sol b/src/reporters/integrations/PolymarketOOReporter.sol index e3f85d3..031addc 100644 --- a/src/reporters/integrations/PolymarketOOReporter.sol +++ b/src/reporters/integrations/PolymarketOOReporter.sol @@ -8,15 +8,24 @@ import {IOOReporterModule} from "../interfaces/IOOReporterModule.sol"; /// @notice OOReporter variant that automatically relays final results to the registering Polymarket V2 module. /// @custom:security-contact bugs@umaproject.org contract PolymarketOOReporter is OOReporter { + // Proposed reserve for the remaining ten-ID loop, events, call overhead, and settlement return path. + uint256 private constant CALLBACK_GAS_RESERVE = 150_000; + /// @notice Emitted when automatic reporting returns without reverting. event ReportCallbackSucceeded(bytes32 indexed requestId, address indexed reporterModule); - /// @notice Emitted when automatic reporting fails and the permissionless report must be retried. + /// @notice Emitted when automatic reporting fails or is skipped for gas and must be retried permissionlessly. event ReportCallbackFailed(bytes32 indexed requestId, address indexed reporterModule); /// @dev Keeps Managed OO settlement nonblocking when the downstream Polymarket report reverts. function _onRequestResolved(bytes32 requestId, address requester) internal override { - try IOOReporterModule(requester).report(requestId) { + uint256 gasRemaining = gasleft(); + if (gasRemaining <= CALLBACK_GAS_RESERVE) { + emit ReportCallbackFailed(requestId, requester); + return; + } + + try IOOReporterModule(requester).report{gas: gasRemaining - CALLBACK_GAS_RESERVE}(requestId) { emit ReportCallbackSucceeded(requestId, requester); } catch { emit ReportCallbackFailed(requestId, requester); diff --git a/src/reporters/interfaces/IOOReporter.sol b/src/reporters/interfaces/IOOReporter.sol index 496a488..a96134c 100644 --- a/src/reporters/interfaces/IOOReporter.sol +++ b/src/reporters/interfaces/IOOReporter.sol @@ -179,10 +179,8 @@ interface IOOReporter { uint256 newReward ); /// @notice Emitted when a final raw UMA outcome is stored for a request. - /// @dev Events for every linked request ID are emitted before the isolated callback batch. + /// @dev Each linked request ID emits this event before attempting its own resolution callback. event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome); - /// @notice Emitted when the isolated request-ID callback fan-out reverts after all resolution events are emitted. - event ResolutionCallbacksFailed(bytes32 indexed requestId, uint256 indexed requestTimestamp); /// @notice Emitted when a callback opens the oracle-initializer re-request path. event RequestRerequestAllowed( bytes32 indexed requestId, uint256 indexed requestTimestamp, RerequestTrigger indexed trigger diff --git a/test/reporters/OOReporter.t.sol b/test/reporters/OOReporter.t.sol index 2182891..adaed5a 100644 --- a/test/reporters/OOReporter.t.sol +++ b/test/reporters/OOReporter.t.sol @@ -58,14 +58,6 @@ contract SimpleProxy { } } -contract OutOfGasCallbackOOReporter is OOReporter { - function _onRequestResolved(bytes32, address) internal view override { - assembly { - if gt(gas(), 0) { invalid() } - } - } -} - contract OOReporterTest { Vm internal constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); @@ -100,7 +92,6 @@ contract OOReporterTest { uint256 manualRerequestsRemaining ); event RequestRerequestBudgetSet(bytes32 indexed requestId, uint256 manualRerequestsRemaining); - event ResolutionCallbacksFailed(bytes32 indexed requestId, uint256 indexed requestTimestamp); event DefaultRerequestBudgetSet(uint256 defaultRerequestBudget); event AutomaticRerequestsEnabledSet(bool enabled); @@ -754,45 +745,6 @@ contract OOReporterTest { ); } - function test_priceSettledKeepsResolutionWhenCallbackFanoutRunsOutOfGas() external { - OutOfGasCallbackOOReporter implementation = new OutOfGasCallbackOOReporter(); - bytes memory initData = abi.encodeCall( - IOOReporter.initialize, - (owner, address(optimisticOracle), address(usdc), oracleInitializer, requester, DEFAULT_REREQUEST_BUDGET) - ); - OutOfGasCallbackOOReporter callbackReporter = - OutOfGasCallbackOOReporter(address(new SimpleProxy(address(implementation), initData))); - bytes memory requestRules = _requestRules("out-of-gas callback"); - - vm.prank(requester); - callbackReporter.registerRequest( - REQUEST_ID, BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS - ); - vm.prank(requester); - callbackReporter.registerRequest( - SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS - ); - vm.prank(oracleInitializer); - callbackReporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); - RequestData memory request = callbackReporter.getRequest(REQUEST_ID); - - vm.expectEmit(address(callbackReporter)); - emit RequestResolved(REQUEST_ID, request.requestTimestamp, 1 ether); - vm.expectEmit(address(callbackReporter)); - emit RequestResolved(SECOND_REQUEST_ID, request.requestTimestamp, 1 ether); - vm.expectEmit(address(callbackReporter)); - emit ResolutionCallbacksFailed(REQUEST_ID, request.requestTimestamp); - optimisticOracle.settle( - address(callbackReporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether - ); - - assertTrue(callbackReporter.isRequestResolved(REQUEST_ID), "resolution should survive callback failure"); - assertTrue( - callbackReporter.isRequestResolved(SECOND_REQUEST_ID), "alias resolution should survive callback failure" - ); - assertEq(callbackReporter.getRequestResolution(REQUEST_ID), 1 ether, "resolved outcome mismatch"); - } - function test_priceDisputedAutomaticallyRerequestsOnceWithoutConsumingBudget() external { bytes memory requestRules = _requestRules("primary"); _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); @@ -864,9 +816,6 @@ contract OOReporterTest { function test_executeCallbackHelpersRejectNonSelfCaller() external { vm.expectRevert(IOOReporter.CallerNotSelf.selector); reporter.executeAutomaticRerequest(REQUEST_ID, RerequestType.AutomaticDispute); - - vm.expectRevert(IOOReporter.CallerNotSelf.selector); - reporter.executeResolutionCallbacks(bytes32(0)); } function test_priceDisputedAllowsManualRecoveryAboveRegisteredMaximumAfterConfigurationDrift() external { diff --git a/test/reporters/PolymarketOOReporter.t.sol b/test/reporters/PolymarketOOReporter.t.sol index d524ef2..70f764f 100644 --- a/test/reporters/PolymarketOOReporter.t.sol +++ b/test/reporters/PolymarketOOReporter.t.sol @@ -5,6 +5,7 @@ import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOORepor import {IOOReporter, RequestData} from "src/reporters/interfaces/IOOReporter.sol"; import {MockERC20} from "test/reporters/mocks/MockERC20.sol"; import {MockOptimisticOracleV2} from "test/reporters/mocks/MockOptimisticOracleV2.sol"; +import {Vm} from "forge-std/Vm.sol"; interface PolymarketReporterVm { function prank(address msgSender) external; @@ -48,6 +49,7 @@ contract MockPolymarketOOReporterModule { IOOReporter public reporter; bool public shouldRevert; + bytes32 public gasExhaustingRequestId; uint256 public reportCount; bytes32 public lastRequestId; mapping(bytes32 requestId => bool reported) public reported; @@ -68,6 +70,10 @@ contract MockPolymarketOOReporterModule { shouldRevert = newShouldRevert; } + function setGasExhaustingRequestId(bytes32 requestId) external { + gasExhaustingRequestId = requestId; + } + function setReentrantRegistration( bytes32 requestId, bytes32 priceIdentifier, @@ -101,6 +107,11 @@ contract MockPolymarketOOReporterModule { lastReporter = msg.sender; observedResolved = reporter.isRequestResolved(requestId); observedOutcome = reporter.getRequestResolution(requestId); + if (requestId == gasExhaustingRequestId) { + assembly { + for {} 1 {} {} + } + } bytes32 requestIdToRegister = reentrantRequestId; if (requestIdToRegister != bytes32(0)) { reentrantRequestId = bytes32(0); @@ -120,7 +131,6 @@ contract PolymarketOOReporterTest { PolymarketReporterVm(address(uint160(uint256(keccak256("hevm cheat code"))))); event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome); - event ResolutionCallbacksFailed(bytes32 indexed requestId, uint256 indexed requestTimestamp); event ReportCallbackSucceeded(bytes32 indexed requestId, address indexed reporterModule); event ReportCallbackFailed(bytes32 indexed requestId, address indexed reporterModule); @@ -283,8 +293,6 @@ contract PolymarketOOReporterTest { vm.expectEmit(address(reporter)); emit RequestResolved(bytes32(i), request.requestTimestamp, 1 ether); } - vm.expectEmit(address(reporter)); - emit ResolutionCallbacksFailed(bytes32(uint256(1)), request.requestTimestamp); bytes memory settleCall = abi.encodeCall( MockOptimisticOracleV2.settle, @@ -294,7 +302,8 @@ contract PolymarketOOReporterTest { (bool success,) = address(optimisticOracle).call{gas: 500_000}(settleCall); _assertTrue(success, "oracle settlement should survive fan-out exhaustion"); - _assertEq(module.reportCount(), 0, "failed fan-out should roll back all reports"); + uint256 automaticReports = module.reportCount(); + _assertTrue(automaticReports > 0 && automaticReports < linkedRequestCount, "expected partial delivery"); _assertTrue(reporter.isRequestResolved(bytes32(linkedRequestCount)), "linked request should remain resolved"); bytes32 requestKey = optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); @@ -302,12 +311,66 @@ contract PolymarketOOReporterTest { for (uint256 i = 1; i <= linkedRequestCount; ++i) { bytes32 requestId = bytes32(i); - module.report(requestId); + if (!module.reported(requestId)) module.report(requestId); _assertTrue(module.reported(requestId), "individual report should succeed"); } _assertEq(module.reportCount(), linkedRequestCount, "individual report count mismatch"); } + function test_callbackGasExhaustionPreservesEventsAndEarlierReports(uint8 failureIndex) external { + uint256 failedId = uint256(failureIndex) % 10 + 1; + bytes memory requestRules = bytes("Will ETH reach 10k?"); + for (uint256 i = 1; i <= 10; ++i) { + module.registerRequest(bytes32(i), BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + } + vm.prank(oracleInitializer); + reporter.initializeRequest(bytes32(uint256(1)), 0, 0, LIVENESS); + RequestData memory request = reporter.getRequest(bytes32(uint256(1))); + module.setGasExhaustingRequestId(bytes32(failedId)); + + Vm recorder = Vm(address(vm)); + recorder.cool(address(reporter)); + recorder.cool(address(module)); + recorder.cool(address(optimisticOracle)); + recorder.recordLogs(); + bytes memory settleCall = abi.encodeCall( + MockOptimisticOracleV2.settle, + (address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether) + ); + (bool success,) = address(optimisticOracle).call{gas: 2_000_000}(settleCall); + _assertTrue(success, "callback exhaustion must not revert settlement"); + + Vm.Log[] memory logs = recorder.getRecordedLogs(); + uint256 resolutions; + uint256 failures; + for (uint256 i; i < logs.length; ++i) { + if (logs[i].emitter != address(reporter)) continue; + if (logs[i].topics[0] == keccak256("RequestResolved(bytes32,uint256,int256)")) { + ++resolutions; + _assertEq(logs[i].topics[1], bytes32(resolutions), "resolution ID or order mismatch"); + } else if (logs[i].topics[0] == keccak256("ReportCallbackFailed(bytes32,address)")) { + ++failures; + } + } + _assertEq(resolutions, 10, "every resolution event must survive"); + _assertEq(module.reportCount(), failedId - 1, "earlier reports must survive"); + _assertEq(failures, 11 - failedId, "failed and skipped callbacks must be observable"); + bytes32 requestKey = + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); + _assertTrue(optimisticOracle.getMockRequest(requestKey).settled, "oracle settlement must survive"); + + module.setGasExhaustingRequestId(bytes32(0)); + for (uint256 i = 1; i <= 10; ++i) { + _assertTrue(reporter.isRequestResolved(bytes32(i)), "linked resolution must survive"); + _assertEq(reporter.getRequestResolution(bytes32(i)), 1 ether, "linked outcome mismatch"); + if (i >= failedId) { + _assertFalse(module.reported(bytes32(i)), "failed or skipped report must not persist"); + module.report(bytes32(i)); + } + } + _assertEq(module.reportCount(), 10, "remaining reports must be retryable"); + } + function test_p4SettlementDoesNotReport() external { bytes memory requestRules = _registerAndInitialize(); RequestData memory request = reporter.getRequest(REQUEST_ID); From 69efc8d637c9562353b2d0a68550bfc8203a4410 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 14 Sep 2026 09:46:48 +0100 Subject: [PATCH 2/3] fix: define callback gas reserve in base reporter --- src/reporters/OOReporter.sol | 2 ++ src/reporters/README.md | 3 ++- src/reporters/integrations/PolymarketOOReporter.sol | 3 --- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/reporters/OOReporter.sol b/src/reporters/OOReporter.sol index a02c2e7..96e6e90 100644 --- a/src/reporters/OOReporter.sol +++ b/src/reporters/OOReporter.sol @@ -43,6 +43,8 @@ contract OOReporter is int256 public constant P4_PRICE = type(int256).min; /// @notice Maximum Polymarket request IDs that can share one Managed OO request. uint256 private constant MAX_REQUEST_IDS_PER_REPORTER_KEY = 10; + // Shared reserve for the remaining ten-ID loop, events, call overhead, and settlement return path. + uint256 internal constant CALLBACK_GAS_RESERVE = 150_000; /*-------------------------------------------------------------- STORAGE diff --git a/src/reporters/README.md b/src/reporters/README.md index f557aef..0c73dff 100644 --- a/src/reporters/README.md +++ b/src/reporters/README.md @@ -183,7 +183,8 @@ The reporter uses one loop, bounded by the ten-ID registration limit, to emit ea then attempt its callback. The loop length is captured before any callback, so reentrant registrations wait for late initialization. There is no outer callback self-call or batch catch; successful callbacks persist if a later one fails. -Before each external `report` call, the Polymarket integration subtracts a proposed 150,000 gas reserve from `gasleft()`. +`OOReporter` defines the shared `CALLBACK_GAS_RESERVE` constant, currently proposed at 150,000 gas, for derived integrations. +Before each external `report` call, the Polymarket integration subtracts that inherited reserve from `gasleft()`. If no callback budget remains, it emits `ReportCallbackFailed` and returns to the loop, which continues emitting all remaining resolution events. The reserve must cover the remaining registration writes, resolution/failure events, loop overhead, gas spent between measuring and forwarding gas, and the enclosing settlement return path. This value diff --git a/src/reporters/integrations/PolymarketOOReporter.sol b/src/reporters/integrations/PolymarketOOReporter.sol index 031addc..d334ca5 100644 --- a/src/reporters/integrations/PolymarketOOReporter.sol +++ b/src/reporters/integrations/PolymarketOOReporter.sol @@ -8,9 +8,6 @@ import {IOOReporterModule} from "../interfaces/IOOReporterModule.sol"; /// @notice OOReporter variant that automatically relays final results to the registering Polymarket V2 module. /// @custom:security-contact bugs@umaproject.org contract PolymarketOOReporter is OOReporter { - // Proposed reserve for the remaining ten-ID loop, events, call overhead, and settlement return path. - uint256 private constant CALLBACK_GAS_RESERVE = 150_000; - /// @notice Emitted when automatic reporting returns without reverting. event ReportCallbackSucceeded(bytes32 indexed requestId, address indexed reporterModule); From cd2afc6a99e3a40e49865caf5139b3fbafd881c8 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Tue, 15 Sep 2026 10:02:59 +0100 Subject: [PATCH 3/3] test: validate callback reserve through real oracle settlement --- src/reporters/OOReporter.sol | 2 +- src/reporters/README.md | 56 ++++- .../PolymarketOOReporterSettlement.t.sol | 191 ++++++++++++++++++ 3 files changed, 243 insertions(+), 6 deletions(-) create mode 100644 test/reporters/PolymarketOOReporterSettlement.t.sol diff --git a/src/reporters/OOReporter.sol b/src/reporters/OOReporter.sol index 96e6e90..7a9f598 100644 --- a/src/reporters/OOReporter.sol +++ b/src/reporters/OOReporter.sol @@ -43,7 +43,7 @@ contract OOReporter is int256 public constant P4_PRICE = type(int256).min; /// @notice Maximum Polymarket request IDs that can share one Managed OO request. uint256 private constant MAX_REQUEST_IDS_PER_REPORTER_KEY = 10; - // Shared reserve for the remaining ten-ID loop, events, call overhead, and settlement return path. + // 135k completion budget plus 15k headroom; see the callback gas budget in src/reporters/README.md. uint256 internal constant CALLBACK_GAS_RESERVE = 150_000; /*-------------------------------------------------------------- diff --git a/src/reporters/README.md b/src/reporters/README.md index 0c73dff..255434b 100644 --- a/src/reporters/README.md +++ b/src/reporters/README.md @@ -183,14 +183,13 @@ The reporter uses one loop, bounded by the ten-ID registration limit, to emit ea then attempt its callback. The loop length is captured before any callback, so reentrant registrations wait for late initialization. There is no outer callback self-call or batch catch; successful callbacks persist if a later one fails. -`OOReporter` defines the shared `CALLBACK_GAS_RESERVE` constant, currently proposed at 150,000 gas, for derived integrations. +`OOReporter` defines the shared `CALLBACK_GAS_RESERVE` constant at 150,000 gas for derived integrations. Before each external `report` call, the Polymarket integration subtracts that inherited reserve from `gasleft()`. If no callback budget remains, it emits `ReportCallbackFailed` and returns to the loop, which continues emitting all remaining resolution events. The reserve must cover the remaining registration writes, resolution/failure events, -loop overhead, gas spent between measuring and forwarding gas, and the enclosing settlement return path. This value -is a review candidate, not a general proof: it assumes sufficient transaction gas and must be validated against the -production call path and gas schedule. The base reporter's internal hook is trusted; derived integrations must bound -and catch their own external calls. +loop overhead, gas spent between measuring and forwarding gas, and the enclosing settlement return path. The budget and +local real-contract validation are detailed below; audit sign-off remains pending. The base reporter's internal hook is +trusted; derived integrations must use the reserve and catch their own external calls. Each attempted callback is wrapped in `try/catch`. A successful call emits `ReportCallbackSucceeded`; a reverted or skipped call emits `ReportCallbackFailed`. The module's permissionless `report(requestId)` @@ -201,6 +200,53 @@ described above. The reporter never calls market-side `finalize()`. Any reporting liveness, threshold, payout translation, and finalization logic remains enforced by the Polymarket V2 contracts. +### Callback gas budget + +The reserve uses the repository's Solidity 0.8.30, optimizer runs 1, via-IR, and `evm_version = "prague"` configuration. +The budget uses [EIP-2929](https://eips.ethereum.org/EIPS/eip-2929) cold storage/account costs and +[EIP-2200](https://eips.ethereum.org/EIPS/eip-2200) storage metering. It does not credit gas refunds or the extra gas +retained by enclosing proxy/oracle frames under [EIP-150](https://eips.ethereum.org/EIPS/eip-150). + +The worst remaining loop has nine untouched duplicate registrations after the first callback exhausts its allowance. +Each iteration reads the ID, packed registration flags, and requester, sets `initialized`, emits `RequestResolved`, +and emits `ReportCallbackFailed` without another external call. A registration already has a nonzero flags slot, so +the flag update is a nonzero-to-nonzero write: three cold reads cost 6,300 and the warmed write costs 2,900 gas. The +two events cost 3,256 gas together; a 13,500 per-iteration allowance also covers hashing, arithmetic and control flow. + +| Work charged to the reserve | Conservative gas budget | +| --- | ---: | +| Measurement-to-CALL setup, including a cold callback target | 3,500 | +| Failed callback catch/event and final loop exit | 2,000 | +| Nine remaining iterations, 13,500 each | 121,500 | +| Both proxy returns, oracle guard restoration/modifier reset and ABI return | 8,000 | +| Completion budget | **135,000** | +| Additional headroom | **15,000** | +| `CALLBACK_GAS_RESERVE` | **150,000** | + +Opcode profiling of the first-position failure with short rules measured 13,063 gas per skipped iteration and +119,205 from callback return through reporter completion (including its catch and loop exit). Measurement-to-CALL +overhead was 375 with a warm target; the budget additionally allows the 2,500 cold-account surcharge. The oracle's +post-callback guard/modifier/ABI work used 3,583 gas; the two proxy returns used 63 combined. These are gross execution +costs, without subtracting refunds. The rounded budget totals 135,000; the configured reserve adds 15,000 headroom. + +`test/reporters/PolymarketOOReporterSettlement.t.sol` exercises the actual `ManagedOptimisticOracleV2.settle` implementation +and `PolymarketOOReporter`, each behind an OpenZeppelin `ERC1967Proxy`. Only external configuration/token dependencies and +the downstream reporter module are test fixtures. It uses maximum-length nonzero rules (8,139 bytes), ten linked IDs, +uninitialized aliases and cold oracle/reporter/module/token storage. At each of the ten positions, the module writes its +report state and then executes `INVALID`, consuming the whole callback allowance and reverting that callback's writes. +The test checks the oracle payout/return value and settled state, all ten resolution events, earlier successful reports, +failure/skip events and permissionless recovery. Calling the real oracle getter afterward also checks that its guard reset. + +Each oracle-proxy call is capped at 8,000,000 execution gas so earlier maximum-rules reports can finish before the selected +failing callback. A production transaction must additionally cover intrinsic/calldata gas; this cap is not a minimum gas +recommendation. During validation, a temporary 135,000 reserve passed all ten positions; 110,000 reverted settlement. +The committed 150,000 reserve passes. The regression also fails against the original callback-batch implementation. + +Run `forge test --offline --match-contract PolymarketOOReporterSettlementTest -vv` to reproduce the integration test. +This validates the configured local EVM schedule, not a live-chain transaction. Sufficient transaction gas is still +required before callbacks begin. Revalidate the budget if the ten-ID cap, loop, integration hook, compiler settings, +proxy/settlement return path or chain gas schedule changes. + ## Rules Updates Only the requester that registered a `requestId` can update rules for that request. The reporter does not store update diff --git a/test/reporters/PolymarketOOReporterSettlement.t.sol b/test/reporters/PolymarketOOReporterSettlement.t.sol new file mode 100644 index 0000000..2362742 --- /dev/null +++ b/test/reporters/PolymarketOOReporterSettlement.t.sol @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import {Test} from "forge-std/Test.sol"; +import {Vm} from "forge-std/Vm.sol"; +import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; +import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {ManagedOptimisticOracleV2} from "src/optimistic-oracle-v2/implementation/ManagedOptimisticOracleV2.sol"; +import {OptimisticOracleV2Interface} from "src/optimistic-oracle-v2/interfaces/OptimisticOracleV2Interface.sol"; +import {AddressWhitelist} from "src/common/implementation/AddressWhitelist.sol"; +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; +import {IOOReporter} from "src/reporters/interfaces/IOOReporter.sol"; +import {OracleInterfaces} from "@uma/contracts/data-verification-mechanism/implementation/Constants.sol"; +import {MockFinder} from "test/mocks/MockFinder.sol"; +import {MockStore} from "test/mocks/MockStore.sol"; +import {MockIdentifierWhitelist} from "test/mocks/MockIdentifierWhitelist.sol"; + +contract GasExhaustingReporterModule { + IOOReporter public reporter; + bytes32 public failingId; + mapping(bytes32 => bool) public reported; + + function configure(IOOReporter reporter_, bytes32 failingId_) external { + reporter = reporter_; + failingId = failingId_; + } + + function report(bytes32 requestId) external { + require(reporter.isRequestResolved(requestId), "unresolved"); + require(reporter.getRequestResolution(requestId) == 1 ether, "wrong outcome"); + reported[requestId] = true; + if (requestId == failingId) { + // Exceptional halt consumes the full forwarded allowance and rolls back this callback's writes. + assembly { + invalid() + } + } + } +} + +contract PolymarketOOReporterSettlementTest is Test { + bytes32 private constant IDENTIFIER = "YES_OR_NO_QUERY"; + uint64 private constant LIVENESS = 2 hours; + uint256 private constant SETTLEMENT_GAS = 8_000_000; + uint256 private constant BOND = 1 ether; + bytes private rules; + address private resolver = address(0x1001); + address private proposer = address(0x1002); + ManagedOptimisticOracleV2 private oracle; + PolymarketOOReporter private reporter; + GasExhaustingReporterModule private module; + ERC20Mock private currency; + address private oracleImplementation; + address private reporterImplementation; + uint256 private requestTimestamp; + + function setUp() public { + bytes memory maximumRules = new bytes(8139); + for (uint256 i; i < maximumRules.length; ++i) { + maximumRules[i] = 0x61; + } + rules = maximumRules; + MockFinder finder = new MockFinder(); + MockStore store = new MockStore(); + MockIdentifierWhitelist identifiers = new MockIdentifierWhitelist(); + AddressWhitelist collateral = new AddressWhitelist(); + AddressWhitelist requesters = new AddressWhitelist(); + AddressWhitelist proposers = new AddressWhitelist(); + currency = new ERC20Mock(); + collateral.addToWhitelist(address(currency)); + identifiers.addSupportedIdentifier(IDENTIFIER); + proposers.addToWhitelist(proposer); + finder.changeImplementationAddress(OracleInterfaces.CollateralWhitelist, address(collateral)); + finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, address(identifiers)); + finder.changeImplementationAddress(OracleInterfaces.Store, address(store)); + + ManagedOptimisticOracleV2.CurrencyBondRange[] memory ranges = + new ManagedOptimisticOracleV2.CurrencyBondRange[](1); + ranges[0] = ManagedOptimisticOracleV2.CurrencyBondRange( + IERC20(address(currency)), ManagedOptimisticOracleV2.BondRange(uint128(BOND), uint128(BOND)) + ); + oracleImplementation = address(new ManagedOptimisticOracleV2()); + oracle = ManagedOptimisticOracleV2( + address( + new ERC1967Proxy( + oracleImplementation, + abi.encodeCall( + ManagedOptimisticOracleV2.initialize, + ( + LIVENESS, + address(finder), + address(proposers), + address(requesters), + ranges, + address(this), + address(this) + ) + ) + ) + ) + ); + oracle.initializeV2(5 minutes, address(this)); + oracle.addResolver(resolver); + + module = new GasExhaustingReporterModule(); + reporterImplementation = address(new PolymarketOOReporter()); + reporter = PolymarketOOReporter( + address( + new ERC1967Proxy( + reporterImplementation, + abi.encodeCall( + IOOReporter.initialize, + (address(this), address(oracle), address(currency), address(this), address(module), 1) + ) + ) + ) + ); + module.configure(IOOReporter(address(reporter)), bytes32(0)); + requesters.addToWhitelist(address(reporter)); + for (uint256 i = 1; i <= 10; ++i) { + vm.prank(address(module)); + reporter.registerRequest(bytes32(i), IDENTIFIER, rules, 0, LIVENESS); + } + reporter.initializeRequest(bytes32(uint256(1)), 0, BOND, LIVENESS); + requestTimestamp = reporter.getRequest(bytes32(uint256(1))).requestTimestamp; + currency.mint(proposer, BOND); + vm.startPrank(proposer); + currency.approve(address(oracle), BOND); + oracle.proposePrice(address(reporter), IDENTIFIER, requestTimestamp, rules, 1 ether); + vm.stopPrank(); + vm.warp(vm.getBlockTimestamp() + LIVENESS + 1); + } + + function test_realSettlementSurvivesGasExhaustionAtEveryPosition() public { + for (uint256 failedId = 1; failedId <= 10; ++failedId) { + uint256 snapshot = vm.snapshotState(); + module.configure(IOOReporter(address(reporter)), bytes32(failedId)); + bytes memory data = abi.encodeCall( + ManagedOptimisticOracleV2.settle, (address(reporter), IDENTIFIER, requestTimestamp, rules) + ); + vm.cool(address(oracle)); + vm.cool(oracleImplementation); + vm.cool(address(reporter)); + vm.cool(reporterImplementation); + vm.cool(address(module)); + vm.cool(address(currency)); + vm.recordLogs(); + vm.prank(resolver); + (bool success, bytes memory result) = address(oracle).call{gas: SETTLEMENT_GAS}(data); + assertTrue(success, "real settlement reverted"); + assertEq(abi.decode(result, (uint256)), BOND, "wrong settlement return value"); + Vm.Log[] memory logs = vm.getRecordedLogs(); + uint256 resolutions; + uint256 successes; + uint256 failures; + for (uint256 i; i < logs.length; ++i) { + if (logs[i].emitter != address(reporter)) continue; + if (logs[i].topics[0] == keccak256("RequestResolved(bytes32,uint256,int256)")) { + ++resolutions; + assertEq(logs[i].topics[1], bytes32(resolutions)); + assertEq(uint256(logs[i].topics[2]), requestTimestamp); + assertEq(abi.decode(logs[i].data, (int256)), 1 ether); + } else if (logs[i].topics[0] == keccak256("ReportCallbackSucceeded(bytes32,address)")) { + ++successes; + } else if (logs[i].topics[0] == keccak256("ReportCallbackFailed(bytes32,address)")) { + ++failures; + } + } + assertEq(resolutions, 10, "missing resolution events"); + assertEq(successes, failedId - 1, "earlier callbacks rolled back"); + assertEq(failures, 11 - failedId, "missing failed or skipped callbacks"); + OptimisticOracleV2Interface.Request memory settled = + oracle.getRequest(address(reporter), IDENTIFIER, requestTimestamp, rules); + assertTrue(settled.settled, "oracle state rolled back"); + assertEq(settled.resolvedPrice, 1 ether); + assertEq(currency.balanceOf(proposer), BOND, "settlement payout rolled back"); + module.configure(IOOReporter(address(reporter)), bytes32(0)); + for (uint256 i = 1; i <= 10; ++i) { + assertTrue(reporter.isRequestResolved(bytes32(i))); + assertEq(module.reported(bytes32(i)), i < failedId, "incorrect callback persistence"); + if (i >= failedId) { + vm.prank(address(0xBEEF)); + module.report(bytes32(i)); + assertTrue(module.reported(bytes32(i)), "permissionless recovery failed"); + } + } + assertTrue(vm.revertToStateAndDelete(snapshot)); + } + } +}