Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 12 additions & 24 deletions src/reporters/OOReporter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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;
// 135k completion budget plus 15k headroom; see the callback gas budget in src/reporters/README.md.
uint256 internal constant CALLBACK_GAS_RESERVE = 150_000;

/*--------------------------------------------------------------
STORAGE
Expand Down Expand Up @@ -454,12 +456,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);
}
}
}
Expand Down Expand Up @@ -499,23 +503,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();
Expand Down Expand Up @@ -697,7 +684,8 @@ contract OOReporter is
emit RequestRerequestAllowed(requestId, requestTimestamp, trigger);
}

/// @dev Returns a registered request or reverts for unknown IDs.
/// @dev Returns the canonical request ID shared by requestId and any duplicate registrations, or reverts for
/// unregistered IDs.
function _canonicalRequestId(bytes32 requestId) private view returns (bytes32 canonicalRequestId) {
OOReporterStorage storage $ = _getStorage();
RequestData storage registration = $.requests[requestId];
Expand Down
80 changes: 65 additions & 15 deletions src/reporters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,17 @@ active unresolved request's current manual budget with `setRequestRerequestBudge
Shared lifecycle events use the canonical request ID (the first ID registered for the tuple), even when the caller
supplies a duplicate ID. This applies to `RequestInitialized`, `RequestRulesUpdated`, `RequestRewardUpdated`,
`RequestRerequested`, `RequestRerequestAllowed`, `AutomaticRerequestFailed`, and `RequestRerequestBudgetSet`.
`ResolutionCallbacksFailed` also identifies the canonical request whose callback batch reverted.

`RequestRegistered`, `RequestResolved`, and the Polymarket callback success/failure events identify individual external
request IDs. A duplicate does not receive a separate initialization or re-request event. Indexers should map each
`RequestRegistered` tuple to its canonical ID using `getRequestId(priceIdentifier, requestRules)` and follow that ID's
shared lifecycle. Shared lifecycle events do not include the caller-supplied alias.

`RequestResolved` records outcome availability, not successful delivery to a module. It has at-least-once semantics:
after a callback batch reverts, initializing a duplicate whose initialization flag was rolled back can emit it again.
Consumers should deduplicate resolutions by `(reporter address, requestId, requestTimestamp)`. A
`ResolutionCallbacksFailed` event means all callback effects and individual callback events in that batch were rolled
back; operators must check and recover reporting for every linked ID.
`RequestResolved` records outcome availability, not successful delivery to a module. Each ID is marked initialized
and emits its resolution event before its callback. A failed or skipped callback preserves those changes and earlier
successful reports. Operators can use the per-ID `ReportCallbackFailed` events to identify reports to retry through the
module's permissionless `report(requestId)` function. Reinitializing an already-processed ID does not retry its callback
or emit another resolution event. Indexers can correlate resolutions by `(reporter address, requestId, requestTimestamp)`.

## Bond And Liveness Events

Expand Down Expand Up @@ -201,23 +200,74 @@ 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.
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.

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)`
`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. The budget and
local real-contract validation are detailed below. 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)`
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 is immediately readable and can be
reported permissionlessly by the module; initialization provides the additional callback attempt 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
Expand Down
10 changes: 8 additions & 2 deletions src/reporters/integrations/PolymarketOOReporter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,18 @@ contract PolymarketOOReporter is OOReporter {
/// @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);
Expand Down
8 changes: 2 additions & 6 deletions src/reporters/interfaces/IOOReporter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,9 @@ interface IOOReporter {
uint256 newReward
);
/// @notice Emitted when a final raw UMA outcome is stored for a request.
/// @dev Emitted for every linked request ID before the isolated callback batch; this does not confirm delivery.
/// Recovery via duplicate initialization can re-emit this event after a reverted batch. Consumers should
/// deduplicate by (reporter address, requestId, requestTimestamp).
/// @dev Each linked request ID emits this event before attempting its own resolution callback. This records
/// outcome availability, not successful callback delivery; failed or skipped module reports are retried separately.
event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome);
/// @notice Emitted under the canonical request ID when the callback batch reverts after resolution events.
/// @dev All callback effects and per-ID callback events from the reverted batch are rolled back.
event ResolutionCallbacksFailed(bytes32 indexed requestId, uint256 indexed requestTimestamp);
/// @notice Emitted under the canonical request ID when a callback opens the shared manual re-request path.
event RequestRerequestAllowed(
bytes32 indexed requestId, uint256 indexed requestTimestamp, RerequestTrigger indexed trigger
Expand Down
51 changes: 0 additions & 51 deletions test/reporters/OOReporter.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -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")))));

Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -840,45 +831,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);
Expand Down Expand Up @@ -950,9 +902,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 {
Expand Down
Loading
Loading