diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2523863..92c0681 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -60,40 +60,6 @@ jobs: forge test -vvv --no-match-contract ".*Fork.*|ManagedOptimisticOracleV2UpgradeValidationTest" id: test - pm-v2-oo-reporter: - name: PM v2 OOReporter package - runs-on: ubuntu-latest - env: - FOUNDRY_PROFILE: default - defaults: - run: - working-directory: pm-v2-oo-reporter - steps: - - uses: actions/checkout@v4 - with: - submodules: recursive - - - name: Install Foundry - uses: foundry-rs/foundry-toolchain@v1 - with: - version: v1.7.1 - - - name: Show Forge version - run: | - forge --version - - - name: Run Forge fmt - run: | - forge fmt --check - - - name: Run Forge build - run: | - forge build - - - name: Run Forge tests - run: | - forge test - fork-tests: name: Fork Tests (Polygon) runs-on: ubuntu-latest diff --git a/.gitmodules b/.gitmodules index ff0d2a1..ba1c845 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,9 +13,6 @@ [submodule "lib/openzeppelin-foundry-upgrades"] path = lib/openzeppelin-foundry-upgrades url = https://github.com/OpenZeppelin/openzeppelin-foundry-upgrades -[submodule "pm-v2-oo-reporter/lib/openzeppelin-contracts-upgradeable"] - path = pm-v2-oo-reporter/lib/openzeppelin-contracts-upgradeable - url = https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable [submodule "lib/permit2"] path = lib/permit2 url = https://github.com/Uniswap/permit2.git diff --git a/README.md b/README.md index 8c7dde2..65fb5ca 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This repository contains UMA Managed Optimistic Oracle contracts. ## Packages - `src/optimistic-oracle-v2/` contains the Managed Optimistic Oracle V2 implementation and interfaces. -- `pm-v2-oo-reporter/` contains the isolated PM v2 OOReporter Foundry package for prediction market integrations that need a request-oriented Managed OO requester and raw outcome source. +- `src/reporters/` contains the shared OO reporter infrastructure and integration-specific reporter extensions. - `test/polymarket-v2/` contains versioned VNet and Amoy manifests plus the read-only-fork Polymarket v2 end-to-end validation. ## Foundry diff --git a/pm-v2-oo-reporter/.gitignore b/pm-v2-oo-reporter/.gitignore deleted file mode 100644 index 4f0940e..0000000 --- a/pm-v2-oo-reporter/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Foundry broadcast artifacts can contain production transaction metadata. -/broadcast/ diff --git a/pm-v2-oo-reporter/foundry.toml b/pm-v2-oo-reporter/foundry.toml deleted file mode 100644 index dabf7e4..0000000 --- a/pm-v2-oo-reporter/foundry.toml +++ /dev/null @@ -1,18 +0,0 @@ -[profile.default] -src = "src" -test = "test" -out = "out" -libs = ["lib"] -ast = true -build_info = true -extra_output = ["storageLayout"] -evm_version = "cancun" -optimizer = true -optimizer_runs = 200 -remappings = [ - "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/", - "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", -] - -[lint] -lint_on_build = false diff --git a/pm-v2-oo-reporter/lib/openzeppelin-contracts-upgradeable b/pm-v2-oo-reporter/lib/openzeppelin-contracts-upgradeable deleted file mode 160000 index 7bf4727..0000000 --- a/pm-v2-oo-reporter/lib/openzeppelin-contracts-upgradeable +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 7bf4727aacdbfaa0f36cbd664654d0c9e1dc52bf diff --git a/pm-v2-oo-reporter/test/PolymarketOOReporter.t.sol b/pm-v2-oo-reporter/test/PolymarketOOReporter.t.sol deleted file mode 100644 index 26d6d21..0000000 --- a/pm-v2-oo-reporter/test/PolymarketOOReporter.t.sol +++ /dev/null @@ -1,239 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.34; - -import {PolymarketOOReporter} from "src/PolymarketOOReporter.sol"; -import {IOOReporter, RequestData} from "src/interfaces/IOOReporter.sol"; -import {MockERC20} from "test/mocks/MockERC20.sol"; -import {MockOptimisticOracleV2} from "test/mocks/MockOptimisticOracleV2.sol"; - -interface PolymarketReporterVm { - function prank(address msgSender) external; - function expectEmit(address emitter) external; - function warp(uint256 newTimestamp) external; -} - -contract PolymarketReporterProxy { - bytes32 private constant IMPLEMENTATION_SLOT = bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1); - - constructor(address implementation, bytes memory data) { - bytes32 slot = IMPLEMENTATION_SLOT; - assembly { - sstore(slot, implementation) - } - - (bool success, bytes memory result) = implementation.delegatecall(data); - if (!success) { - assembly { - revert(add(result, 0x20), mload(result)) - } - } - } - - fallback() external payable { - bytes32 slot = IMPLEMENTATION_SLOT; - assembly { - let implementation := sload(slot) - calldatacopy(0, 0, calldatasize()) - let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) - returndatacopy(0, 0, returndatasize()) - switch result - case 0 { revert(0, returndatasize()) } - default { return(0, returndatasize()) } - } - } -} - -contract MockPolymarketOOReporterModule { - error ReportFailed(); - - IOOReporter public reporter; - bool public shouldRevert; - uint256 public reportCount; - bytes32 public lastRequestId; - address public lastReporter; - bool public observedResolved; - int256 public observedOutcome; - - function setReporter(IOOReporter newReporter) external { - reporter = newReporter; - } - - function setShouldRevert(bool newShouldRevert) external { - shouldRevert = newShouldRevert; - } - - function registerRequest( - bytes32 requestId, - bytes32 priceIdentifier, - bytes calldata requestRules, - uint64 minimumLiveness, - uint64 maximumLiveness - ) external { - reporter.registerRequest(requestId, priceIdentifier, requestRules, minimumLiveness, maximumLiveness); - } - - function report(bytes32 requestId) external { - if (shouldRevert) revert ReportFailed(); - - reportCount += 1; - lastRequestId = requestId; - lastReporter = msg.sender; - observedResolved = reporter.isRequestResolved(requestId); - observedOutcome = reporter.getRequestResolution(requestId); - } -} - -contract PolymarketOOReporterTest { - PolymarketReporterVm private constant vm = - PolymarketReporterVm(address(uint160(uint256(keccak256("hevm cheat code"))))); - - event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome); - event ReportCallbackSucceeded(bytes32 indexed requestId, address indexed reporterModule); - event ReportCallbackFailed(bytes32 indexed requestId, address indexed reporterModule); - - bytes32 private constant REQUEST_ID = keccak256("polymarket-request-id"); - bytes32 private constant BINARY_IDENTIFIER = "YES_OR_NO_QUERY"; - uint64 private constant LIVENESS = 2 hours; - uint64 private constant MAXIMUM_LIVENESS = 2 days; - uint256 private constant DEFAULT_REREQUEST_BUDGET = 1; - - address private owner = address(0x1001); - address private oracleInitializer = address(0x1002); - - PolymarketOOReporter private reporter; - MockPolymarketOOReporterModule private module; - MockOptimisticOracleV2 private optimisticOracle; - MockERC20 private usdc; - - function setUp() external { - optimisticOracle = new MockOptimisticOracleV2(); - usdc = new MockERC20(); - module = new MockPolymarketOOReporterModule(); - - PolymarketOOReporter implementation = new PolymarketOOReporter(); - bytes memory initData = abi.encodeCall( - IOOReporter.initialize, - ( - owner, - address(optimisticOracle), - address(usdc), - oracleInitializer, - address(module), - DEFAULT_REREQUEST_BUDGET - ) - ); - reporter = PolymarketOOReporter(address(new PolymarketReporterProxy(address(implementation), initData))); - module.setReporter(IOOReporter(address(reporter))); - } - - function test_settlementAutomaticallyReportsResolvedOutcome() external { - bytes memory requestRules = _registerAndInitialize(); - RequestData memory request = reporter.getRequest(REQUEST_ID); - - vm.expectEmit(address(reporter)); - emit RequestResolved(REQUEST_ID, request.requestTimestamp, 1 ether); - vm.expectEmit(address(reporter)); - emit ReportCallbackSucceeded(REQUEST_ID, address(module)); - - optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); - - _assertEq(module.reportCount(), 1, "report count mismatch"); - _assertEq(module.lastRequestId(), REQUEST_ID, "request id mismatch"); - _assertEq(module.lastReporter(), address(reporter), "report caller mismatch"); - _assertTrue(module.observedResolved(), "report should observe resolved state"); - _assertEq(module.observedOutcome(), 1 ether, "reported outcome mismatch"); - } - - function test_reportFailureDoesNotRevertSettlementAndCanBeRetried() external { - bytes memory requestRules = _registerAndInitialize(); - RequestData memory request = reporter.getRequest(REQUEST_ID); - module.setShouldRevert(true); - - vm.expectEmit(address(reporter)); - emit RequestResolved(REQUEST_ID, request.requestTimestamp, 1 ether); - vm.expectEmit(address(reporter)); - emit ReportCallbackFailed(REQUEST_ID, address(module)); - - optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); - - _assertTrue(reporter.isRequestResolved(REQUEST_ID), "reporter should remain resolved"); - _assertEq(reporter.getRequestResolution(REQUEST_ID), 1 ether, "stored outcome mismatch"); - bytes32 requestKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); - _assertTrue(optimisticOracle.getMockRequest(requestKey).settled, "oracle settlement should persist"); - - module.setShouldRevert(false); - module.report(REQUEST_ID); - _assertEq(module.reportCount(), 1, "permissionless retry should succeed"); - } - - function test_p4SettlementDoesNotReport() external { - bytes memory requestRules = _registerAndInitialize(); - RequestData memory request = reporter.getRequest(REQUEST_ID); - - vm.prank(owner); - reporter.setAutomaticRerequestsEnabled(false); - optimisticOracle.settle( - address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, reporter.P4_PRICE() - ); - - _assertEq(module.reportCount(), 0, "P4 should not report"); - _assertFalse(reporter.isRequestResolved(REQUEST_ID), "P4 should not resolve reporter request"); - _assertTrue(reporter.getRequest(REQUEST_ID).rerequestAllowed, "P4 should open rerequest gate"); - } - - function test_staleSettlementDoesNotReport() external { - bytes memory requestRules = _registerAndInitialize(); - RequestData memory initialRequest = reporter.getRequest(REQUEST_ID); - - vm.warp(block.timestamp + 1); - optimisticOracle.disputePrice( - address(reporter), BINARY_IDENTIFIER, initialRequest.requestTimestamp, requestRules - ); - RequestData memory activeRequest = reporter.getRequest(REQUEST_ID); - - optimisticOracle.settle( - address(reporter), BINARY_IDENTIFIER, initialRequest.requestTimestamp, requestRules, 1 ether - ); - - _assertEq(module.reportCount(), 0, "stale settlement should not report"); - _assertFalse(reporter.isRequestResolved(REQUEST_ID), "stale settlement should not resolve active request"); - _assertEq( - reporter.getRequest(REQUEST_ID).requestTimestamp, - activeRequest.requestTimestamp, - "stale settlement should not replace active timestamp" - ); - } - - function _registerAndInitialize() private returns (bytes memory requestRules) { - requestRules = bytes("Will ETH reach 10k?"); - module.registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); - - vm.prank(oracleInitializer); - reporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); - } - - function _assertTrue(bool condition, string memory message) private pure { - if (!condition) revert(message); - } - - function _assertFalse(bool condition, string memory message) private pure { - if (condition) revert(message); - } - - function _assertEq(uint256 actual, uint256 expected, string memory message) private pure { - if (actual != expected) revert(message); - } - - function _assertEq(int256 actual, int256 expected, string memory message) private pure { - if (actual != expected) revert(message); - } - - function _assertEq(bytes32 actual, bytes32 expected, string memory message) private pure { - if (actual != expected) revert(message); - } - - function _assertEq(address actual, address expected, string memory message) private pure { - if (actual != expected) revert(message); - } -} diff --git a/pm-v2-oo-reporter/script/DeployOOReporter.s.sol b/script/reporters/DeployOOReporter.s.sol similarity index 96% rename from pm-v2-oo-reporter/script/DeployOOReporter.s.sol rename to script/reporters/DeployOOReporter.s.sol index d785f0f..729bc5c 100644 --- a/pm-v2-oo-reporter/script/DeployOOReporter.s.sol +++ b/script/reporters/DeployOOReporter.s.sol @@ -1,12 +1,12 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {Script} from "forge-std/Script.sol"; import {console} from "forge-std/console.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; -import {OOReporter} from "../src/OOReporter.sol"; -import {IOOReporter} from "../src/interfaces/IOOReporter.sol"; +import {OOReporter} from "src/reporters/OOReporter.sol"; +import {IOOReporter} from "src/reporters/interfaces/IOOReporter.sol"; /// @title Deployment script for OOReporter /// @notice Deploys and initializes an OOReporter implementation and ERC1967 proxy. diff --git a/pm-v2-oo-reporter/script/DeployPolymarketOOReporter.s.sol b/script/reporters/DeployPolymarketOOReporter.s.sol similarity index 79% rename from pm-v2-oo-reporter/script/DeployPolymarketOOReporter.s.sol rename to script/reporters/DeployPolymarketOOReporter.s.sol index 3aaeab6..bf14a50 100644 --- a/pm-v2-oo-reporter/script/DeployPolymarketOOReporter.s.sol +++ b/script/reporters/DeployPolymarketOOReporter.s.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {DeployOOReporter} from "./DeployOOReporter.s.sol"; -import {PolymarketOOReporter} from "../src/PolymarketOOReporter.sol"; +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; /// @title Deployment script for PolymarketOOReporter /// @notice Deploys the callback-enabled implementation using DeployOOReporter's proxy initialization flow. diff --git a/pm-v2-oo-reporter/script/UpgradeOOReporter.s.sol b/script/reporters/UpgradeOOReporter.s.sol similarity index 97% rename from pm-v2-oo-reporter/script/UpgradeOOReporter.s.sol rename to script/reporters/UpgradeOOReporter.s.sol index 3a995fe..9cf5e77 100644 --- a/pm-v2-oo-reporter/script/UpgradeOOReporter.s.sol +++ b/script/reporters/UpgradeOOReporter.s.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {Script} from "forge-std/Script.sol"; import {Vm} from "forge-std/Vm.sol"; import {console} from "forge-std/console.sol"; -import {OOReporter} from "../src/OOReporter.sol"; -import {PolymarketOOReporter} from "../src/PolymarketOOReporter.sol"; -import {RequestData} from "../src/interfaces/IOOReporter.sol"; +import {OOReporter} from "src/reporters/OOReporter.sol"; +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; +import {RequestData} from "src/reporters/interfaces/IOOReporter.sol"; interface IUUPSUpgradeable { function upgradeToAndCall(address newImplementation, bytes calldata data) external payable; @@ -408,7 +408,7 @@ contract UpgradeOOReporter is Script { Vm.EthGetLogs memory requestLog, address expectedRequester, uint256 logIndex - ) private view returns (bytes32 requestId) { + ) internal view returns (bytes32 requestId) { if (requestLog.removed || requestLog.topics.length != 4 || requestLog.topics[0] != REQUEST_REGISTERED_TOPIC) { revert InvalidRegisteredRequestLog(logIndex); } @@ -418,14 +418,13 @@ contract UpgradeOOReporter is Script { bytes32 priceIdentifier = requestLog.topics[3]; (bytes memory requestRules, uint64 minimumLiveness, uint64 maximumLiveness) = abi.decode(requestLog.data, (bytes, uint64, uint64)); + // Registered aliases resolve to canonical state; the reverse lookup need not equal this log's request ID. RequestData memory request = reporter.getRequest(requestId); if ( !request.registered || requester != expectedRequester || request.requester != requester - || request.priceIdentifier != priceIdentifier - || keccak256(request.requestRules) != keccak256(requestRules) + || request.priceIdentifier != priceIdentifier || keccak256(request.requestRules) != keccak256(requestRules) || request.minimumLiveness != minimumLiveness || request.maximumLiveness != maximumLiveness - || reporter.getRequestId(priceIdentifier, requestRules) != requestId ) revert RegisteredRequestStateMismatch(requestId); } @@ -510,7 +509,7 @@ contract UpgradeOOReporter is Script { } function _snapshotReporterState(OOReporter reporter, Config memory config, bytes32[] memory requestIds) - private + internal view returns (ReporterState memory state) { @@ -550,7 +549,7 @@ contract UpgradeOOReporter is Script { ReporterState memory expectedState, bytes32[] memory requestIds, address finalImplementation - ) private view { + ) internal view { _expectAddress("final reporter implementation", finalImplementation, _getImplementation(address(reporter))); _expectAddress( "current Managed OO implementation", @@ -565,18 +564,16 @@ contract UpgradeOOReporter is Script { || reporter.defaultRerequestBudget() != expectedState.defaultRerequestBudget || reporter.automaticRerequestsEnabled() != expectedState.automaticRerequestsEnabled || reporter.isRequester(config.expectedRequester) != expectedState.requesterEnabled - || reporter.isOracleInitializer(config.expectedOracleInitializer) - != expectedState.oracleInitializerEnabled + || reporter.isOracleInitializer(config.expectedOracleInitializer) != expectedState.oracleInitializerEnabled || vm.load(address(reporter), INITIALIZABLE_STORAGE_SLOT) != expectedState.initializableStorage || PolymarketOOReporter(address(reporter)).pendingOwner() != address(0) ) revert PostUpgradeStateMismatch(); for (uint256 i = 0; i < requestIds.length; i++) { RequestData memory request = reporter.getRequest(requestIds[i]); - if ( - keccak256(abi.encode(request)) != expectedState.requestHashes[i] - || reporter.getRequestId(request.priceIdentifier, request.requestRules) != requestIds[i] - ) revert RequestStateChanged(requestIds[i]); + if (keccak256(abi.encode(request)) != expectedState.requestHashes[i]) { + revert RequestStateChanged(requestIds[i]); + } } _validateExternalWiring(config); diff --git a/pm-v2-oo-reporter/src/OOReporter.sol b/src/reporters/OOReporter.sol similarity index 84% rename from pm-v2-oo-reporter/src/OOReporter.sol rename to src/reporters/OOReporter.sol index 5887fe3..4c25fb3 100644 --- a/pm-v2-oo-reporter/src/OOReporter.sol +++ b/src/reporters/OOReporter.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; @@ -28,6 +28,8 @@ contract OOReporter is using SafeERC20 for IERC20; error OwnershipRenunciationDisabled(); + /// @notice Thrown when one Managed OO request already serves the maximum number of external request IDs. + error ReporterRequestIdLimitReached(); /*-------------------------------------------------------------- CONSTANTS @@ -39,6 +41,10 @@ contract OOReporter is uint256 public constant MAXIMUM_CUSTOM_LIVENESS = 5200 weeks; /// @notice UMA sentinel price for "too early" / unresolvable (P4). 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 @@ -62,6 +68,8 @@ contract OOReporter is uint256 defaultRerequestBudget; /// @notice Whether first-dispute and P4 automatic re-requests are enabled. bool automaticRerequestsEnabled; + /// @notice Polymarket request IDs sharing each `(priceIdentifier, requestRules)` Managed OO request. + mapping(bytes32 reporterRequestKey => bytes32[] requestIds) requestIdsByReporterRequestKey; } // keccak256(abi.encode(uint256(keccak256("uma.storage.OOReporter")) - 1)) & ~bytes32(uint256(0xff)) @@ -237,7 +245,17 @@ contract OOReporter is bytes32 reporterRequestKey = _reporterRequestKey(priceIdentifier, requestRules); bytes32 existingRequestId = requestIdsByReporterKey(reporterRequestKey); - if (existingRequestId != bytes32(0)) revert ReporterRequestKeyAlreadyRegistered(existingRequestId); + bytes32[] storage requestIds = $.requestIdsByReporterRequestKey[reporterRequestKey]; + // Backfill requests registered before this array was added so the canonical ID counts toward the cap. + if (existingRequestId != bytes32(0) && requestIds.length == 0) requestIds.push(existingRequestId); + if (requestIds.length >= MAX_REQUEST_IDS_PER_REPORTER_KEY) revert ReporterRequestIdLimitReached(); + if (existingRequestId != bytes32(0)) { + RequestData storage existingRequest = $.requests[existingRequestId]; + if ( + existingRequest.requester != msg.sender || existingRequest.minimumLiveness != minimumLiveness + || existingRequest.maximumLiveness != maximumLiveness + ) revert ReporterRequestKeyAlreadyRegistered(existingRequestId); + } request.registered = true; request.requester = msg.sender; @@ -245,25 +263,28 @@ contract OOReporter is request.requestRules = requestRules; request.minimumLiveness = minimumLiveness; request.maximumLiveness = maximumLiveness; - $.requestIdsByReporterKey[reporterRequestKey] = requestId; + requestIds.push(requestId); + if (existingRequestId == bytes32(0)) $.requestIdsByReporterKey[reporterRequestKey] = requestId; emit RequestRegistered(requestId, msg.sender, priceIdentifier, requestRules, minimumLiveness, maximumLiveness); } /// @inheritdoc IOOReporter function updateRequestRules(bytes32 requestId, bytes calldata updatedRules) external onlyRequester { - RequestData storage request = _requireRegistered(requestId); + bytes32 canonicalRequestId = _canonicalRequestId(requestId); + RequestData storage request = _getStorage().requests[canonicalRequestId]; if (request.resolved) revert RequestAlreadyResolved(); if (msg.sender != request.requester) revert CallerNotRequestRegistrar(); optimisticOracle().updateRequestRules(request.priceIdentifier, request.requestRules, updatedRules); - emit RequestRulesUpdated(requestId, block.timestamp, msg.sender, updatedRules); + emit RequestRulesUpdated(canonicalRequestId, block.timestamp, msg.sender, updatedRules); } /// @inheritdoc IOOReporter function setRequestReward(bytes32 requestId, uint256 newReward) external onlyOracleInitializer { - RequestData storage request = _requireRegistered(requestId); + bytes32 canonicalRequestId = _canonicalRequestId(requestId); + RequestData storage request = _getStorage().requests[canonicalRequestId]; if (!request.initialized) revert RequestNotInitialized(); if (request.resolved) revert RequestAlreadyResolved(); @@ -280,7 +301,7 @@ contract OOReporter is oracle.setReward(request.priceIdentifier, request.requestTimestamp, request.requestRules, newReward); emit RequestRewardUpdated( - requestId, request.requestTimestamp, msg.sender, address(currency), oldReward, newReward + canonicalRequestId, request.requestTimestamp, msg.sender, address(currency), oldReward, newReward ); } @@ -289,7 +310,20 @@ contract OOReporter is external onlyOracleInitializer { - RequestData storage request = _requireRegistered(requestId); + bytes32 canonicalRequestId = _canonicalRequestId(requestId); + OOReporterStorage storage $ = _getStorage(); + RequestData storage request = $.requests[canonicalRequestId]; + if (request.initialized && requestId != canonicalRequestId) { + RequestData storage registration = $.requests[requestId]; + if (registration.initialized) return; + + registration.initialized = true; + if (request.resolved) { + emit RequestResolved(requestId, request.requestTimestamp, request.outcome); + _onRequestResolved(requestId, registration.requester); + } + return; + } if (request.initialized) revert RequestAlreadyInitialized(); if (request.resolved) revert RequestAlreadyResolved(); _requireValidRequestLiveness(request, liveness); @@ -303,11 +337,12 @@ contract OOReporter is request.proposalBond = proposalBond; request.liveness = liveness; request.manualRerequestsRemaining = manualRerequestsRemaining; + if (requestId != canonicalRequestId) $.requests[requestId].initialized = true; _requestPrice(request.priceIdentifier, requestTimestamp, request.requestRules, reward, proposalBond, liveness); emit RequestInitialized( - requestId, + canonicalRequestId, requestTimestamp, msg.sender, request.priceIdentifier, @@ -325,7 +360,8 @@ contract OOReporter is external onlyOracleInitializer { - RequestData storage request = _requireRegistered(requestId); + bytes32 canonicalRequestId = _canonicalRequestId(requestId); + RequestData storage request = _getStorage().requests[canonicalRequestId]; if (!request.initialized) revert RequestNotInitialized(); if (request.resolved) revert RequestAlreadyResolved(); if (!request.rerequestAllowed) revert RequestRerequestNotAllowed(); @@ -336,12 +372,13 @@ contract OOReporter is request.manualRerequestsRemaining -= 1; - _emitRequestRerequested(requestId, request, previousRequestTimestamp, msg.sender, RerequestType.Manual); + _emitRequestRerequested(canonicalRequestId, request, previousRequestTimestamp, msg.sender, RerequestType.Manual); } /// @inheritdoc IOOReporter function setRequestRerequestBudget(bytes32 requestId, uint256 newManualRerequestsRemaining) external onlyOwner { - RequestData storage request = _requireRegistered(requestId); + bytes32 canonicalRequestId = _canonicalRequestId(requestId); + RequestData storage request = _getStorage().requests[canonicalRequestId]; if (!request.initialized) revert RequestNotInitialized(); if (request.resolved) revert RequestAlreadyResolved(); uint256 budgetCeiling = defaultRerequestBudget(); @@ -354,7 +391,7 @@ contract OOReporter is request.manualRerequestsRemaining = newManualRerequestsRemaining; - emit RequestRerequestBudgetSet(requestId, newManualRerequestsRemaining); + emit RequestRerequestBudgetSet(canonicalRequestId, newManualRerequestsRemaining); } /// @notice Managed OO dispute callback. Attempts one auto re-request, otherwise opens the manual gate. @@ -415,8 +452,19 @@ contract OOReporter is request.outcome = price; request.rerequestAllowed = false; - emit RequestResolved(requestId, timestamp, price); - _onRequestResolved(requestId, request.requester); + bytes32 reporterRequestKey = _reporterRequestKey(identifier, requestRules); + bytes32[] storage requestIds = _getStorage().requestIdsByReporterRequestKey[reporterRequestKey]; + // Backfill untouched pre-array requests before emitting events and invoking callbacks. + if (requestIds.length == 0) requestIds.push(requestId); + // 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); + } } } @@ -636,10 +684,19 @@ 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]; + if (!registration.registered) revert RequestNotRegistered(); + canonicalRequestId = + $.requestIdsByReporterKey[_reporterRequestKey(registration.priceIdentifier, registration.requestRules)]; + } + + /// @dev Returns the canonical request shared by requestId and any duplicate registrations. function _requireRegistered(bytes32 requestId) private view returns (RequestData storage request) { - request = _getStorage().requests[requestId]; - if (!request.registered) revert RequestNotRegistered(); + request = _getStorage().requests[_canonicalRequestId(requestId)]; } /// @dev Derives the callback lookup key from UMA request identity fields that are stable across re-requests. diff --git a/pm-v2-oo-reporter/README.md b/src/reporters/README.md similarity index 73% rename from pm-v2-oo-reporter/README.md rename to src/reporters/README.md index 5ddd554..b6a7c1e 100644 --- a/pm-v2-oo-reporter/README.md +++ b/src/reporters/README.md @@ -1,8 +1,8 @@ -# PM v2 OOReporter +# OO Reporters -UMA-owned Managed Optimistic Oracle requester and raw outcome source for prediction market request IDs. +UMA-owned Managed Optimistic Oracle requester and integration-specific reporter extensions. -This package is intended to pair with a market-side requester module. The market-side module registers request IDs here, +These contracts are intended to pair with a market-side requester module. The market-side module registers request IDs here, then either pulls raw UMA outcomes from `OOReporter` or receives an automatic `report(requestId)` callback from `PolymarketOOReporter`. Payout translation and finalization remain market-side responsibilities. @@ -38,10 +38,16 @@ per requester. Deploy the base `OOReporter` for pull-only integrations and the Polymarket variant when every enabled requester implements `IOOReporterModule.report(bytes32)`. -The reporter reserves each `(priceIdentifier, requestRules)` tuple globally across enabled requesters in the -deployment. This prevents two request IDs from pointing at the same UMA request identity. Independent integrations that -need the exact same UMA request identity should use separate reporter deployments; integrations with similar rules can -domain-separate request rules so their UMA request identities differ. +The reporter creates one Managed OO lifecycle for each `(priceIdentifier, requestRules)` tuple. The same requester can +register up to ten request IDs with the same tuple and liveness range. Those IDs share the original Managed OO request, +resolution, and automatic re-request state. Registrations from another requester, with a different liveness range, or +above the ten-ID limit are rejected. + +Sharing is intentional, including after settlement: registering another ID immediately exposes the canonical +request's current state and any stored outcome through that ID. It does not create a fresh oracle round, reward, bond, +or challenge window. Requesters must use the same tuple only for questions with the same resolution semantics. Rules +must distinguish any different observation period or numerical outcome-to-position mapping; the reporter does not +include market IDs, event IDs, or a new request timestamp in the association key or validate that external mappings agree. ## Responsibilities @@ -68,14 +74,23 @@ The prediction market integration owns: An enabled requester first calls `registerRequest(...)` with its external `requestId`, UMA price identifier, raw request rules, and liveness range. Registration requires an internally consistent range that overlaps the Managed OO bounds at that time. The minimum remains an onchain floor, while the maximum is stored, returned, and emitted as an offchain -initialization target rather than an onchain ceiling. The reporter reserves the `(priceIdentifier, requestRules)` tuple -globally within the deployment so two request IDs cannot point at the same UMA request identity. +initialization target rather than an onchain ceiling. Duplicate registrations from the same requester with the same +tuple and liveness range are associated with the original registration instead of creating another Managed OO request. An enabled UMA oracle initializer later calls `initializeRequest(requestId, reward, proposalBond, liveness)`. The selected liveness must be non-zero and at or above the registered minimum, but it may exceed the registered target maximum. The Managed OO independently enforces its current `minimumDisputeWindow` and technical maximum. Each initialized request receives the current `defaultRerequestBudget` as its manual re-request budget. +Calling `initializeRequest` for an associated duplicate request ID is an idempotent no-op after the shared Managed OO +request has been initialized but remains unresolved. If the duplicate is registered after the shared request resolves, +`isRequestResolved` and `getRequestResolution` expose the stored outcome as soon as registration completes. Its first +initialization additionally emits `RequestResolved` and invokes the resolution hook, which attempts `report(requestId)` +in `PolymarketOOReporter`; later initialization calls are no-ops. Initialization is not an approval checkpoint for reading +or reporting an inherited outcome: the Polymarket module's permissionless `report(requestId)` can use it once the module +has registered that ID, without another reporter initialization. A resolved shared request cannot be re-requested; a +question requiring a new oracle round must use distinct rules. + Automatic re-requests are enabled by default and can be disabled or re-enabled by the owner with `setAutomaticRerequestsEnabled(...)`. The current setting is evaluated when a dispute or P4 settlement callback arrives, not when the request was initialized or last re-requested. When enabled, the first dispute callback for a request @@ -94,9 +109,20 @@ replacement request. Automatic re-requests reuse the active reward, proposal bon the default budget for future initializations and P4 refreshes with `setDefaultRerequestBudget(...)`, and can adjust an active unresolved request's current manual budget with `setRequestRerequestBudget(...)`. -Lifecycle events that refer to a specific Managed OO request consistently lead with the external `requestId` and then -the active OO `requestTimestamp` before actor or outcome fields. This keeps initialization, re-request, -re-request-gate, rules-update, and resolution logs easy to correlate after a request has been replaced. +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`. + +`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. 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 @@ -170,19 +196,78 @@ compromise, operators should fund the reporter with a working reward float rathe ## Automatic Polymarket Reporting -After storing a non-P4 final outcome, `PolymarketOOReporter` calls `report(requestId)` on the module that registered the -request. The reporter commits its resolved state before making this external call, so the module can read the outcome -during `report`. +After storing a non-P4 final outcome, `PolymarketOOReporter` calls `report(requestId)` for every associated request ID on +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 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. -The 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)` -entry point can then be retried separately. P4 settlements, stale callbacks, unknown requests, and already-resolved -requests do not trigger reporting. +`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 @@ -194,8 +279,8 @@ Rules updates do not replace the original registered rules or create a new `(pri lookup alias. Consumers should use `requestId` as the stable reporter identity and read canonical update history from the Managed OO using the reporter address plus the original `(priceIdentifier, requestRules)` tuple. -The reporter additionally emits a `RequestRulesUpdated` event carrying the requester-facing `requestId` and updater -address for self-contained logs. +The reporter additionally emits a `RequestRulesUpdated` event carrying the canonical `requestId` and updater address, +even when the update was submitted through a duplicate ID. For a registered request, updates can be forwarded before or after Managed OO initialization. The reporter rejects rules updates after the request has resolved. @@ -208,35 +293,35 @@ Install this repository as a normal Foundry dependency: forge install UMAprotocol/managed-oracle ``` -With the standard dependency remapping: +With a dependency remapping for this repository: ```toml -managed-oracle/pm-v2-oo-reporter/=lib/managed-oracle/pm-v2-oo-reporter/src/ +managed-oracle/=lib/managed-oracle/ ``` Consumers can import the reporter from: ```solidity -import {OOReporter} from "managed-oracle/pm-v2-oo-reporter/OOReporter.sol"; -import {PolymarketOOReporter} from "managed-oracle/pm-v2-oo-reporter/PolymarketOOReporter.sol"; -import {IOOReporter} from "managed-oracle/pm-v2-oo-reporter/interfaces/IOOReporter.sol"; -import {IOOReporterModule} from "managed-oracle/pm-v2-oo-reporter/interfaces/IOOReporterModule.sol"; +import {OOReporter} from "managed-oracle/src/reporters/OOReporter.sol"; +import {PolymarketOOReporter} from "managed-oracle/src/reporters/integrations/PolymarketOOReporter.sol"; +import {IOOReporter} from "managed-oracle/src/reporters/interfaces/IOOReporter.sol"; +import {IOOReporterModule} from "managed-oracle/src/reporters/interfaces/IOOReporterModule.sol"; ``` Importing only `IOOReporter` does not require OpenZeppelin remappings. -Consumers that compile `OOReporter.sol` must provide compatible remappings for `@openzeppelin/contracts/` and `@openzeppelin/contracts-upgradeable/`; this package does so in `pm-v2-oo-reporter/foundry.toml` via its package-local `lib/openzeppelin-contracts-upgradeable` submodule. +Consumers that compile `OOReporter.sol` must provide compatible remappings for `@openzeppelin/contracts/` and `@openzeppelin/contracts-upgradeable/`; the repository root provides both dependencies and remappings. ## Deployment And Upgrades -Run every reporter script from this package directory so implementation bytecode uses its Solidity 0.8.34, optimizer, +Run every reporter script from the repository root so implementation bytecode uses the root Solidity 0.8.30, optimizer, and dependency settings. Choose the entrypoint explicitly: | Script | Use | | --- | --- | -| `script/DeployOOReporter.s.sol` | Fresh pull-only `OOReporter` implementation and initialized ERC1967 proxy. | -| `script/DeployPolymarketOOReporter.s.sol` | Fresh callback-enabled `PolymarketOOReporter` implementation and initialized ERC1967 proxy. | -| `script/UpgradeOOReporter.s.sol` | Upgrade an existing reporter proxy to `PolymarketOOReporter` without changing its Managed OO. | +| `script/reporters/DeployOOReporter.s.sol` | Fresh pull-only `OOReporter` implementation and initialized ERC1967 proxy. | +| `script/reporters/DeployPolymarketOOReporter.s.sol` | Fresh callback-enabled `PolymarketOOReporter` implementation and initialized ERC1967 proxy. | +| `script/reporters/UpgradeOOReporter.s.sol` | Upgrade an existing reporter proxy to `PolymarketOOReporter` without changing its Managed OO. | The fresh deployment scripts share the same initialization flow. The upgrade script preserves the reporter proxy and all reporter state, deploys or reuses only the final `PolymarketOOReporter` implementation, and calls @@ -306,14 +391,12 @@ verification flags. Production deployments should initialize the intended owner, explicitly. ```bash -cd pm-v2-oo-reporter - export DEPLOYER_ADDRESS="implementation and proxy deployer" export INITIAL_OWNER="reporter owner or Safe" export INITIAL_ORACLE_INITIALIZER="UMA initializer address" export INITIAL_REQUESTER="Polymarket OOReporterModule address" -forge script script/DeployPolymarketOOReporter.s.sol \ +forge script script/reporters/DeployPolymarketOOReporter.s.sol \ --rpc-url "$RPC_URL" \ --sender "$DEPLOYER_ADDRESS" \ --interactive \ @@ -324,7 +407,7 @@ forge script script/DeployPolymarketOOReporter.s.sol \ --etherscan-api-key "$ETHERSCAN_API_KEY" ``` -Use `script/DeployOOReporter.s.sol` instead only when downstream integrations will pull results and no automatic +Use `script/reporters/DeployOOReporter.s.sol` instead only when downstream integrations will pull results and no automatic `report(requestId)` callback is wanted. Foundry submits and verifies both the selected implementation and the `ERC1967Proxy`. @@ -364,8 +447,9 @@ its requester whitelist, and the downstream module wiring before deploying anyth | `EXPECTED_STATE_FINGERPRINT` | Required in verify mode. Copy the fingerprint printed by the final pre-upgrade run. | The script derives the complete request-ID list from `RequestRegistered` logs instead of accepting a hand-curated list. -For every event it validates the requester, identifier, rules, liveness range, and tuple lookup against current proxy -storage, then snapshots the full stored request for the post-upgrade comparison. Log queries are split into configurable +For every event it validates the requester, identifier, rules, and liveness range against `getRequest(requestId)`, then +snapshots that canonical request state for the post-upgrade comparison. A registered alias is valid even when the +tuple's canonical ID differs from the ID in the event. Log queries are split into configurable block ranges for RPC compatibility. The script also reconstructs requester and oracle-initializer allowlist state from events and requires the expected module and initializer to be the only enabled accounts. Active requests are safe because the Managed OO address does not change. Quiesce every reporter mutation from @@ -390,14 +474,12 @@ owner call. No signing material is read from an environment variable. For a direct EOA-owned upgrade, set `EXPECTED_OWNER` and `DEPLOYER_ADDRESS` to the same address and opt in explicitly: ```bash -cd pm-v2-oo-reporter - export EXECUTE_UPGRADE=true -forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ +forge script script/reporters/UpgradeOOReporter.s.sol:UpgradeOOReporter \ --rpc-url "$RPC_URL" -vvv -forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ +forge script script/reporters/UpgradeOOReporter.s.sol:UpgradeOOReporter \ --rpc-url "$RPC_URL" \ --sender "$DEPLOYER_ADDRESS" \ --interactive \ @@ -419,7 +501,7 @@ needs reporter ownership. export EXECUTE_UPGRADE=false # Deploy only the implementation with the external signer. -forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ +forge script script/reporters/UpgradeOOReporter.s.sol:UpgradeOOReporter \ --rpc-url "$RPC_URL" \ --sender "$DEPLOYER_ADDRESS" \ --interactive \ @@ -429,15 +511,15 @@ forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ # After setting FINAL_IMPLEMENTATION and EXPECTED_FINAL_IMPLEMENTATION_CODEHASH, # rerun read-only to produce the reviewed Safe payload and final state fingerprint. -forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ +forge script script/reporters/UpgradeOOReporter.s.sol:UpgradeOOReporter \ --rpc-url "$RPC_URL" -vvv ``` After either EOA or Safe execution, set `VERIFY_ONLY=true`, set `FINAL_IMPLEMENTATION`, its code hash, and `EXPECTED_STATE_FINGERPRINT` from the final pre-upgrade run, then run the script without `--broadcast`. This live, rerunnable verification checks the exact final implementation; unchanged Managed OO implementation, Initializable slot, -owner, reward currency, re-request configuration, requester and initializer access; byte-for-byte ABI encoding and tuple -lookup of every registered request; zero `pendingOwner`; Managed OO whitelist acceptance; and the module proxy, +owner, reward currency, re-request configuration, requester and initializer access; byte-for-byte ABI encoding of the +canonical state returned for every registered request ID; zero `pendingOwner`; Managed OO whitelist acceptance; and the module proxy, implementation, and reporter pointer. The immediate checks in Forge's broadcast simulation are not a substitute for this post-broadcast run. @@ -445,7 +527,7 @@ post-broadcast run. export VERIFY_ONLY=true export EXPECTED_STATE_FINGERPRINT="fingerprint from the final pre-upgrade run" -forge script script/UpgradeOOReporter.s.sol:UpgradeOOReporter \ +forge script script/reporters/UpgradeOOReporter.s.sol:UpgradeOOReporter \ --rpc-url "$RPC_URL" -vvv ``` @@ -582,13 +664,13 @@ using `cast send` directly. If a fresh deployment was broadcast without `--verify`, recover the exact addresses and proxy initialization calldata from its artifact. The following selects the callback-enabled variant; use `DeployOOReporter`, `OOReporter`, and -`src/OOReporter.sol:OOReporter` instead for the pull-only variant: +`src/reporters/OOReporter.sol:OOReporter` instead for the pull-only variant: ```bash CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL") DEPLOY_SCRIPT=DeployPolymarketOOReporter IMPLEMENTATION_NAME=PolymarketOOReporter -IMPLEMENTATION_SOURCE=src/PolymarketOOReporter.sol:PolymarketOOReporter +IMPLEMENTATION_SOURCE=src/reporters/integrations/PolymarketOOReporter.sol:PolymarketOOReporter BROADCAST_PATH="broadcast/${DEPLOY_SCRIPT}.s.sol/${CHAIN_ID}/run-latest.json" IMPLEMENTATION_ADDRESS=$(jq -r \ @@ -634,7 +716,7 @@ NEW_IMPLEMENTATION=$(jq -r \ "$UPGRADE_BROADCAST") forge verify-contract "$NEW_IMPLEMENTATION" \ - src/PolymarketOOReporter.sol:PolymarketOOReporter \ + src/reporters/integrations/PolymarketOOReporter.sol:PolymarketOOReporter \ --chain "$CHAIN_ID" \ --verifier etherscan \ --etherscan-api-key "$ETHERSCAN_API_KEY" \ @@ -680,8 +762,8 @@ verification of the new implementation only. See Tenderly's From the managed-oracle repository root: ```bash -cd pm-v2-oo-reporter && forge test +forge test --match-path 'test/reporters/*' ``` -The package enables the Solidity optimizer with 200 runs so both reporter implementations remain comfortably below +The root project enables the Solidity optimizer so both reporter implementations remain comfortably below the EIP-170 deployed bytecode limit. diff --git a/pm-v2-oo-reporter/src/PolymarketOOReporter.sol b/src/reporters/integrations/PolymarketOOReporter.sol similarity index 61% rename from pm-v2-oo-reporter/src/PolymarketOOReporter.sol rename to src/reporters/integrations/PolymarketOOReporter.sol index 1520b41..d334ca5 100644 --- a/pm-v2-oo-reporter/src/PolymarketOOReporter.sol +++ b/src/reporters/integrations/PolymarketOOReporter.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; -import {OOReporter} from "./OOReporter.sol"; -import {IOOReporterModule} from "./interfaces/IOOReporterModule.sol"; +import {OOReporter} from "../OOReporter.sol"; +import {IOOReporterModule} from "../interfaces/IOOReporterModule.sol"; /// @title PolymarketOOReporter /// @notice OOReporter variant that automatically relays final results to the registering Polymarket V2 module. @@ -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); diff --git a/pm-v2-oo-reporter/src/interfaces/IOOReporter.sol b/src/reporters/interfaces/IOOReporter.sol similarity index 88% rename from pm-v2-oo-reporter/src/interfaces/IOOReporter.sol rename to src/reporters/interfaces/IOOReporter.sol index bf6a3df..d6cc64b 100644 --- a/pm-v2-oo-reporter/src/interfaces/IOOReporter.sol +++ b/src/reporters/interfaces/IOOReporter.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; struct RequestData { /// @notice Timestamp of the active Managed OO request. @@ -96,7 +96,7 @@ interface IOOReporter { error RequestAlreadyInitialized(); /// @notice Thrown when registering a request ID that has already been registered. error RequestAlreadyRegistered(); - /// @notice Thrown when registering a duplicate OO request tuple for a different request ID. + /// @notice Thrown when a duplicate OO request tuple has a different requester or liveness range. error ReporterRequestKeyAlreadyRegistered(bytes32 existingRequestId); /// @notice Thrown when an operation targets a request that already has a final outcome. error RequestAlreadyResolved(); @@ -150,7 +150,7 @@ interface IOOReporter { uint64 minimumLiveness, uint64 maximumLiveness ); - /// @notice Emitted when an approved oracle initializer creates the first Managed OO request. + /// @notice Emitted under the canonical request ID when the first shared Managed OO request is created. /// @dev proposalBond and liveness are reporter-requested parameters. Effective proposal-time values can differ /// if Managed OO request-manager preconfigs apply. event RequestInitialized( @@ -165,11 +165,11 @@ interface IOOReporter { uint64 liveness, uint256 manualRerequestsRemaining ); - /// @notice Emitted when the registering requester posts updated request rules for offchain consumers. + /// @notice Emitted under the canonical request ID when the requester posts shared request rules updates. event RequestRulesUpdated( bytes32 indexed requestId, uint256 indexed timestamp, address indexed updater, bytes updatedRules ); - /// @notice Emitted when an approved oracle initializer updates the active Managed OO request reward. + /// @notice Emitted under the canonical request ID when the active shared Managed OO request reward changes. event RequestRewardUpdated( bytes32 indexed requestId, uint256 indexed requestTimestamp, @@ -179,16 +179,18 @@ interface IOOReporter { uint256 newReward ); /// @notice Emitted when a final raw UMA outcome is stored for a request. + /// @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 when a callback opens the oracle-initializer re-request path. + /// @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 ); - /// @notice Emitted when an automatic re-request fails and the callback falls back to the manual gate. + /// @notice Emitted under the canonical request ID when an automatic re-request fails and opens the manual gate. event AutomaticRerequestFailed( bytes32 indexed requestId, uint256 indexed requestTimestamp, RerequestType indexed rerequestType ); - /// @notice Emitted when the reporter creates a replacement Managed OO request. + /// @notice Emitted under the canonical request ID when the reporter creates a replacement Managed OO request. /// @dev proposalBond and liveness are reporter-requested parameters. Effective proposal-time values can differ /// if Managed OO request-manager preconfigs apply. event RequestRerequested( @@ -203,7 +205,8 @@ interface IOOReporter { uint64 liveness, uint256 manualRerequestsRemaining ); - /// @notice Emitted when the owner updates the remaining re-request budget for one request. + /// @notice Emitted under the canonical request ID when the shared remaining re-request budget changes. + /// @dev Emitted for owner updates and automatic refills to the default budget on P4 settlement. event RequestRerequestBudgetSet(bytes32 indexed requestId, uint256 manualRerequestsRemaining); /// @notice Emitted when the owner sweeps ERC20 or native token funds from the reporter. event FundsSwept(address indexed token, address indexed recipient, uint256 amount); @@ -266,13 +269,13 @@ interface IOOReporter { /// @return True if automatic re-requests are enabled. function automaticRerequestsEnabled() external view returns (bool); - /// @notice Registers a requester-defined request ID and its UMA request identity before OO initialization. - /// @dev The reporter reserves each price identifier and request rules pair globally across approved requesters. - /// Enabled requesters share one owner-managed request namespace; the contract does not isolate identical UMA - /// request identities per requester. Independent integrations that need the exact same UMA request identity should - /// use separate reporter deployments; integrations with similar rules can domain-separate request rules so their - /// UMA request identities differ. minimumLiveness is enforced as an onchain runtime floor, while maximumLiveness - /// remains a registration-time bound and offchain target that does not cap initialization or re-requests. + /// @notice Registers a requester-defined request ID and its UMA request identity. + /// @dev Up to ten request IDs with matching price identifier, request rules, requester, and liveness values share one + /// Managed OO lifecycle, including any existing final outcome, which is readable immediately upon registration. + /// No new oracle round or challenge window is created for a duplicate. Requesters must distinguish questions with + /// different resolution semantics in their rules, including observation periods and numerical position mappings. + /// minimumLiveness is enforced as an onchain runtime floor, while maximumLiveness remains a + /// registration-time bound and offchain target that does not cap initialization or re-requests. /// @param requestId Requester-defined request ID to bind to the UMA request identity. /// @param priceIdentifier UMA price identifier to request. /// @param requestRules Raw UMA request rules supplied by the requester. @@ -303,7 +306,11 @@ interface IOOReporter { /// @notice Creates the Managed OO request for a registered request. /// @dev Pays the reward from the reporter's reward-currency balance and, when the Managed OO allowance is below - /// the reward, tops it up to an unbounded approval for the trusted oracle instead of approving per request. + /// the reward, tops it up to an unbounded approval for the trusted oracle instead of approving per request. A + /// duplicate ID reuses the shared request; if registered after resolution, its first initialization triggers the + /// resolution hook immediately, while subsequent initializations are no-ops. + /// The shared outcome is already readable upon registration; initialization does not gate reads or permissionless + /// reporting by a requester module that has registered the duplicate. /// @param requestId Registered request ID. /// @param reward Reward offered to a successful OO proposer. /// @param proposalBond Bond requested from OO proposers/disputers, or zero to use the OO default. The effective @@ -333,11 +340,13 @@ interface IOOReporter { function setRequestRerequestBudget(bytes32 requestId, uint256 newManualRerequestsRemaining) external; /// @notice Returns whether Managed OO settlement has produced a final reporter outcome for requestId. + /// @dev A duplicate registered after canonical resolution returns true without another initialization. /// @param requestId Registered request ID. /// @return True if the reporter has stored a final outcome. function isRequestResolved(bytes32 requestId) external view returns (bool); /// @notice Returns the final raw UMA outcome for requestId after non-P4 trusted resolver settlement. + /// @dev A duplicate registered after canonical resolution immediately inherits the stored outcome. /// @param requestId Registered request ID. /// @return Final raw UMA outcome. function getRequestResolution(bytes32 requestId) external view returns (int256); diff --git a/pm-v2-oo-reporter/src/interfaces/IOOReporterModule.sol b/src/reporters/interfaces/IOOReporterModule.sol similarity index 94% rename from pm-v2-oo-reporter/src/interfaces/IOOReporterModule.sol rename to src/reporters/interfaces/IOOReporterModule.sol index b70097c..94ba299 100644 --- a/pm-v2-oo-reporter/src/interfaces/IOOReporterModule.sol +++ b/src/reporters/interfaces/IOOReporterModule.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; /// @title IOOReporterModule /// @notice Minimal Polymarket V2 reporter module surface used for automatic result reporting. diff --git a/pm-v2-oo-reporter/src/interfaces/IOptimisticOracleV2.sol b/src/reporters/interfaces/IOptimisticOracleV2.sol similarity index 99% rename from pm-v2-oo-reporter/src/interfaces/IOptimisticOracleV2.sol rename to src/reporters/interfaces/IOptimisticOracleV2.sol index 0af700c..e4756af 100644 --- a/pm-v2-oo-reporter/src/interfaces/IOptimisticOracleV2.sol +++ b/src/reporters/interfaces/IOptimisticOracleV2.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; diff --git a/pm-v2-oo-reporter/src/interfaces/IOptimisticRequester.sol b/src/reporters/interfaces/IOptimisticRequester.sol similarity index 98% rename from pm-v2-oo-reporter/src/interfaces/IOptimisticRequester.sol rename to src/reporters/interfaces/IOptimisticRequester.sol index 9318169..5b68768 100644 --- a/pm-v2-oo-reporter/src/interfaces/IOptimisticRequester.sol +++ b/src/reporters/interfaces/IOptimisticRequester.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; // Source: https://github.com/UMAprotocol/managed-oracle/blob/5fffebba9e3fecee6d6850dc4cc53f37647a6659/src/optimistic-oracle-v2/implementation/OptimisticOracleV2.sol#L31-L67 // Kept local to avoid importing the full OptimisticOracleV2 implementation and dependency graph for callback ABI only. diff --git a/pm-v2-oo-reporter/test/OOReporter.t.sol b/test/reporters/OOReporter.t.sol similarity index 87% rename from pm-v2-oo-reporter/test/OOReporter.t.sol rename to test/reporters/OOReporter.t.sol index d99f257..d7d3d45 100644 --- a/pm-v2-oo-reporter/test/OOReporter.t.sol +++ b/test/reporters/OOReporter.t.sol @@ -1,12 +1,13 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; -import {OOReporter} from "src/OOReporter.sol"; -import {IOOReporter, RequestData, RerequestTrigger, RerequestType} from "src/interfaces/IOOReporter.sol"; -import {MockERC20} from "test/mocks/MockERC20.sol"; -import {MockOptimisticOracleV2} from "test/mocks/MockOptimisticOracleV2.sol"; +import {OOReporter} from "src/reporters/OOReporter.sol"; +import {IOOReporter, RequestData, RerequestTrigger, RerequestType} from "src/reporters/interfaces/IOOReporter.sol"; +import {MockERC20} from "test/reporters/mocks/MockERC20.sol"; +import {MockOptimisticOracleV2} from "test/reporters/mocks/MockOptimisticOracleV2.sol"; interface Vm { + function getBlockTimestamp() external view returns (uint256); function prank(address msgSender) external; function startPrank(address msgSender) external; function stopPrank() external; @@ -188,15 +189,56 @@ contract OOReporterTest { ); } - function test_registerRequestRejectsDuplicateReporterTuple() external { + function test_registerRequestAssociatesDuplicateReporterTuple() external { bytes memory requestRules = _requestRules("primary"); _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); vm.prank(requester); + reporter.registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS); + + assertEq(reporter.getRequestId(BINARY_IDENTIFIER, requestRules), REQUEST_ID, "canonical request id changed"); + RequestData memory request = reporter.getRequest(SECOND_REQUEST_ID); + assertTrue(request.registered, "duplicate request should be registered"); + assertEq(request.priceIdentifier, BINARY_IDENTIFIER, "identifier mismatch"); + assertEq(request.requestRules, requestRules, "rules mismatch"); + } + + function test_registerRequestRejectsDuplicateReporterTupleFromDifferentRequester() external { + bytes memory requestRules = _requestRules("primary"); + _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); + + vm.prank(owner); + reporter.setRequesterEnabled(secondRequester, true); + vm.prank(secondRequester); vm.expectRevert(abi.encodeWithSelector(IOOReporter.ReporterRequestKeyAlreadyRegistered.selector, REQUEST_ID)); reporter.registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS); } + function test_registerRequestRejectsDuplicateReporterTupleWithDifferentLiveness() external { + bytes memory requestRules = _requestRules("primary"); + _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); + + vm.prank(requester); + vm.expectRevert(abi.encodeWithSelector(IOOReporter.ReporterRequestKeyAlreadyRegistered.selector, REQUEST_ID)); + reporter.registerRequest( + SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS + 1 + ); + } + + function test_registerRequestCapsDuplicateReporterTuple() external { + bytes memory requestRules = _requestRules("primary"); + for (uint256 i = 1; i <= 10; ++i) { + vm.prank(requester); + reporter.registerRequest(bytes32(i), BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS); + } + + vm.prank(requester); + vm.expectRevert(OOReporter.ReporterRequestIdLimitReached.selector); + reporter.registerRequest( + bytes32(uint256(11)), BINARY_IDENTIFIER, requestRules, MINIMUM_LIVENESS, MAXIMUM_LIVENESS + ); + } + function test_registerRequestAcceptsOORequestRulesLimit() external { assertEq(reporter.MAX_REQUEST_RULES(), 8139, "OO request rules limit mismatch"); @@ -298,7 +340,7 @@ contract OOReporterTest { assertEq(request.liveness, oracleMinimumLiveness, "selected liveness mismatch"); bytes32 requestKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); assertEq( optimisticOracle.getMockRequest(requestKey).customLiveness, oracleMinimumLiveness, "OO liveness mismatch" ); @@ -315,7 +357,7 @@ contract OOReporterTest { RequestData memory request = reporter.getRequest(REQUEST_ID); assertTrue(request.initialized, "request should be initialized"); assertEq(request.oracleInitializer, oracleInitializer, "initializer mismatch"); - assertEq(request.requestTimestamp, block.timestamp, "timestamp mismatch"); + assertEq(request.requestTimestamp, vm.getBlockTimestamp(), "timestamp mismatch"); assertEq(request.reward, REWARD, "reward mismatch"); assertEq(request.proposalBond, PROPOSAL_BOND, "bond mismatch"); assertEq(request.liveness, LIVENESS, "liveness mismatch"); @@ -328,7 +370,7 @@ contract OOReporterTest { assertTrue(reporter.automaticRerequestsEnabled(), "automatic re-requests should initialize enabled"); bytes32 requestKey = - optimisticOracle.requestKey(address(reporter), NUMERICAL_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), NUMERICAL_IDENTIFIER, vm.getBlockTimestamp(), requestRules); MockOptimisticOracleV2.MockRequest memory ooRequest = optimisticOracle.getMockRequest(requestKey); assertTrue(ooRequest.requested, "OO request should exist"); assertTrue(ooRequest.eventBased, "request should be event based"); @@ -341,7 +383,7 @@ contract OOReporterTest { assertEq(ooRequest.customLiveness, LIVENESS, "OO liveness mismatch"); bytes32 binaryKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); assertFalse(optimisticOracle.getMockRequest(binaryKey).requested, "binary request should not be created"); } @@ -364,6 +406,111 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); } + function test_initializeDuplicateRequestIdReusesCanonicalManagedOORequest() external { + bytes memory requestRules = _requestRules("primary"); + _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); + _registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules); + + vm.startPrank(oracleInitializer); + reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); + vm.stopPrank(); + + RequestData memory canonical = reporter.getRequest(REQUEST_ID); + RequestData memory duplicate = reporter.getRequest(SECOND_REQUEST_ID); + assertEq(keccak256(abi.encode(duplicate)), keccak256(abi.encode(canonical)), "lifecycle should be shared"); + + bytes32 requestKey = + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, canonical.requestTimestamp, requestRules); + assertTrue(optimisticOracle.getMockRequest(requestKey).requested, "canonical OO request should exist"); + } + + function test_duplicateOperationsEmitCanonicalLifecycleEvents() external { + bytes memory requestRules = _requestRules("primary"); + _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); + _registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules); + uint256 initialTimestamp = vm.getBlockTimestamp(); + + vm.expectEmit(address(reporter)); + emit IOOReporter.RequestInitialized( + REQUEST_ID, + initialTimestamp, + oracleInitializer, + BINARY_IDENTIFIER, + requestRules, + address(usdc), + 0, + PROPOSAL_BOND, + LIVENESS, + DEFAULT_REREQUEST_BUDGET + ); + vm.prank(oracleInitializer); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); + + bytes memory updatedRules = bytes("clarified rules"); + vm.expectEmit(address(reporter)); + emit RequestRulesUpdated(REQUEST_ID, initialTimestamp, requester, updatedRules); + vm.prank(requester); + reporter.updateRequestRules(SECOND_REQUEST_ID, updatedRules); + + usdc.mint(address(reporter), REWARD); + vm.expectEmit(address(reporter)); + emit RequestRewardUpdated(REQUEST_ID, initialTimestamp, oracleInitializer, address(usdc), 0, REWARD); + vm.prank(oracleInitializer); + reporter.setRequestReward(SECOND_REQUEST_ID, REWARD); + + vm.expectEmit(address(reporter)); + emit RequestRerequestBudgetSet(REQUEST_ID, 2); + vm.prank(owner); + reporter.setRequestRerequestBudget(SECOND_REQUEST_ID, 2); + + vm.warp(initialTimestamp + 1); + vm.expectEmit(address(reporter)); + emit RequestRerequested( + REQUEST_ID, + initialTimestamp + 1, + address(reporter), + RerequestType.AutomaticDispute, + initialTimestamp, + address(usdc), + REWARD, + PROPOSAL_BOND, + LIVENESS, + 2 + ); + optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, initialTimestamp, requestRules); + + vm.warp(initialTimestamp + 2); + vm.expectEmit(address(reporter)); + emit RequestRerequestAllowed(REQUEST_ID, initialTimestamp + 1, RerequestTrigger.Dispute); + optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, initialTimestamp + 1, requestRules); + + vm.expectEmit(address(reporter)); + emit RequestRerequested( + REQUEST_ID, + initialTimestamp + 2, + oracleInitializer, + RerequestType.Manual, + initialTimestamp + 1, + address(usdc), + REWARD, + PROPOSAL_BOND, + LIVENESS, + 1 + ); + vm.prank(oracleInitializer); + reporter.rerequest(SECOND_REQUEST_ID, REWARD, PROPOSAL_BOND, LIVENESS); + + RequestData memory canonical = reporter.getRequest(REQUEST_ID); + assertEq(canonical.requestTimestamp, initialTimestamp + 2, "shared request should advance"); + assertEq(canonical.manualRerequestsRemaining, 1, "shared budget should decrement"); + assertEq( + keccak256(abi.encode(reporter.getRequest(SECOND_REQUEST_ID))), + keccak256(abi.encode(canonical)), + "alias should share the event's canonical state" + ); + } + function test_initializeRequestRejectsZeroLiveness() external { _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, _requestRules("primary")); @@ -410,7 +557,7 @@ contract OOReporterTest { assertEq(request.maximumLiveness, STRICT_MAXIMUM_LIVENESS, "target maximum should remain stored"); bytes32 requestKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); assertEq( optimisticOracle.getMockRequest(requestKey).customLiveness, currentOracleMinimum, "OO liveness mismatch" ); @@ -586,12 +733,12 @@ contract OOReporterTest { _registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules); vm.expectEmit(address(reporter)); - emit RequestRulesUpdated(REQUEST_ID, block.timestamp, requester, firstUpdatedRules); + emit RequestRulesUpdated(REQUEST_ID, vm.getBlockTimestamp(), requester, firstUpdatedRules); vm.prank(requester); reporter.updateRequestRules(REQUEST_ID, firstUpdatedRules); - vm.warp(block.timestamp + 10); + vm.warp(vm.getBlockTimestamp() + 10); vm.prank(requester); reporter.updateRequestRules(REQUEST_ID, secondUpdatedRules); @@ -605,7 +752,7 @@ contract OOReporterTest { assertEq(forwarded.length, 2, "forwarded update count mismatch"); assertEq(forwarded[0].updatedRules, firstUpdatedRules, "first forwarded rules mismatch"); assertEq(forwarded[1].updatedRules, secondUpdatedRules, "second forwarded rules mismatch"); - assertEq(forwarded[1].timestamp, block.timestamp, "latest forwarded timestamp mismatch"); + assertEq(forwarded[1].timestamp, vm.getBlockTimestamp(), "latest forwarded timestamp mismatch"); } function test_updateRequestRulesRejectsUnknownAndWrongRequester() external { @@ -692,12 +839,12 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequested( REQUEST_ID, - block.timestamp, + vm.getBlockTimestamp(), address(reporter), RerequestType.AutomaticDispute, request.requestTimestamp, @@ -714,7 +861,7 @@ contract OOReporterTest { assertFalse(afterAuto.rerequestAllowed, "automatic re-request should not leave gate open"); assertFalse(afterAuto.resolved, "dispute should not resolve the request"); assertTrue(afterAuto.automaticDisputeRerequestUsed, "automatic dispute re-request should be marked used"); - assertEq(afterAuto.requestTimestamp, block.timestamp, "automatic dispute should advance timestamp"); + assertEq(afterAuto.requestTimestamp, vm.getBlockTimestamp(), "automatic dispute should advance timestamp"); assertEq(afterAuto.manualRerequestsRemaining, DEFAULT_REREQUEST_BUDGET, "dispute should not consume budget"); } @@ -733,12 +880,12 @@ contract OOReporterTest { ); assertEq(reporter.getRequest(REQUEST_ID).reward, REWARD, "manager change should leave reporter cache stale"); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); RequestData memory rerequested = reporter.getRequest(REQUEST_ID); bytes32 replacementKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); assertEq(rerequested.reward, managedReward, "dispute refund should refresh cached reward"); assertEq( optimisticOracle.getMockRequest(replacementKey).reward, @@ -752,7 +899,7 @@ contract OOReporterTest { ); } - function test_executeAutomaticRerequestRejectsNonSelfCaller() external { + function test_executeCallbackHelpersRejectNonSelfCaller() external { vm.expectRevert(IOOReporter.CallerNotSelf.selector); reporter.executeAutomaticRerequest(REQUEST_ID, RerequestType.AutomaticDispute); } @@ -767,7 +914,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); uint64 currentOracleMinimum = LIVENESS + 1; optimisticOracle.setMinimumDisputeWindow(currentOracleMinimum); @@ -784,7 +931,7 @@ contract OOReporterTest { ); bytes32 replacementKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); MockOptimisticOracleV2.MockRequest memory replacementRequest = optimisticOracle.getMockRequest(replacementKey); assertFalse(replacementRequest.requested, "failed automatic re-request should roll back replacement request"); @@ -809,11 +956,11 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); RequestData memory afterAuto = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequestAllowed(REQUEST_ID, afterAuto.requestTimestamp, RerequestTrigger.Dispute); @@ -865,7 +1012,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, REWARD, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.setDeferNextDisputeRefund(true); vm.expectEmit(address(reporter)); @@ -895,7 +1042,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequestAllowed(REQUEST_ID, request.requestTimestamp, RerequestTrigger.Dispute); @@ -914,7 +1061,7 @@ contract OOReporterTest { "disabled first dispute should not advance timestamp" ); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.prank(oracleInitializer); reporter.rerequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); @@ -922,12 +1069,12 @@ contract OOReporterTest { vm.prank(owner); reporter.setAutomaticRerequestsEnabled(true); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequested( REQUEST_ID, - block.timestamp, + vm.getBlockTimestamp(), address(reporter), RerequestType.AutomaticDispute, afterManual.requestTimestamp, @@ -943,7 +1090,7 @@ contract OOReporterTest { RequestData memory afterAuto = reporter.getRequest(REQUEST_ID); assertFalse(afterAuto.rerequestAllowed, "enabled later dispute should auto re-request"); assertTrue(afterAuto.automaticDisputeRerequestUsed, "enabled later dispute should consume automatic slot"); - assertEq(afterAuto.requestTimestamp, block.timestamp, "enabled later dispute should advance timestamp"); + assertEq(afterAuto.requestTimestamp, vm.getBlockTimestamp(), "enabled later dispute should advance timestamp"); assertEq( afterAuto.manualRerequestsRemaining, DEFAULT_REREQUEST_BUDGET - 1, @@ -963,7 +1110,7 @@ contract OOReporterTest { // Spend one manual re-request so we can prove P4 refills the manual budget to the default. RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); vm.prank(oracleInitializer); reporter.rerequest(REQUEST_ID, 0, MANUAL_PROPOSAL_BOND, MANUAL_LIVENESS); @@ -973,14 +1120,14 @@ contract OOReporterTest { vm.prank(owner); reporter.setAutomaticRerequestsEnabled(true); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequestBudgetSet(REQUEST_ID, DEFAULT_REREQUEST_BUDGET); vm.expectEmit(address(reporter)); emit RequestRerequested( REQUEST_ID, - block.timestamp, + vm.getBlockTimestamp(), address(reporter), RerequestType.AutomaticInvalidSettlement, afterManual.requestTimestamp, @@ -1002,7 +1149,7 @@ contract OOReporterTest { assertEq( afterP4.manualRerequestsRemaining, DEFAULT_REREQUEST_BUDGET, "P4 should refill the budget to the default" ); - assertEq(afterP4.requestTimestamp, block.timestamp, "P4 should auto re-request"); + assertEq(afterP4.requestTimestamp, vm.getBlockTimestamp(), "P4 should auto re-request"); assertEq(afterP4.proposalBond, MANUAL_PROPOSAL_BOND, "P4 should preserve latest manual bond"); assertEq(afterP4.liveness, MANUAL_LIVENESS, "P4 should preserve latest manual liveness"); @@ -1018,7 +1165,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.setMinimumDisputeWindow(uint256(LIVENESS) + 1); vm.expectEmit(address(reporter)); @@ -1037,7 +1184,7 @@ contract OOReporterTest { assertTrue(activeRequest.settled, "P4 settlement should persist when automatic re-request fails"); bytes32 replacementKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); MockOptimisticOracleV2.MockRequest memory replacementRequest = optimisticOracle.getMockRequest(replacementKey); assertFalse(replacementRequest.requested, "failed automatic P4 re-request should roll back replacement request"); } @@ -1053,7 +1200,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequestAllowed(REQUEST_ID, request.requestTimestamp, RerequestTrigger.InvalidSettlement); @@ -1108,7 +1255,7 @@ contract OOReporterTest { vm.prank(owner); reporter.setAutomaticRerequestsEnabled(false); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); vm.expectEmit(address(reporter)); emit RequestRerequestAllowed(REQUEST_ID, request.requestTimestamp, RerequestTrigger.InvalidSettlement); @@ -1136,11 +1283,11 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); RequestData memory afterAuto = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, afterAuto.requestTimestamp, requestRules); usdc.mint(address(reporter), REREQUEST_REWARD); @@ -1148,7 +1295,7 @@ contract OOReporterTest { vm.expectEmit(address(reporter)); emit RequestRerequested( REQUEST_ID, - block.timestamp, + vm.getBlockTimestamp(), oracleInitializer, RerequestType.Manual, afterAuto.requestTimestamp, @@ -1163,7 +1310,7 @@ contract OOReporterTest { reporter.rerequest(REQUEST_ID, REREQUEST_REWARD, MANUAL_PROPOSAL_BOND, MANUAL_LIVENESS); RequestData memory rerequested = reporter.getRequest(REQUEST_ID); - assertEq(rerequested.requestTimestamp, block.timestamp, "re-request timestamp mismatch"); + assertEq(rerequested.requestTimestamp, vm.getBlockTimestamp(), "re-request timestamp mismatch"); assertEq(rerequested.reward, REREQUEST_REWARD, "re-request reward mismatch"); assertEq(rerequested.proposalBond, MANUAL_PROPOSAL_BOND, "re-request bond mismatch"); assertEq(rerequested.liveness, MANUAL_LIVENESS, "re-request liveness mismatch"); @@ -1171,7 +1318,7 @@ contract OOReporterTest { assertFalse(rerequested.rerequestAllowed, "gate should close after re-request"); bytes32 requestKey = - optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, block.timestamp, requestRules); + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, vm.getBlockTimestamp(), requestRules); MockOptimisticOracleV2.MockRequest memory ooRequest = optimisticOracle.getMockRequest(requestKey); assertTrue(ooRequest.requested, "replacement request should exist"); assertEq(ooRequest.bond, MANUAL_PROPOSAL_BOND, "replacement request bond mismatch"); @@ -1193,7 +1340,7 @@ contract OOReporterTest { reporter.setAutomaticRerequestsEnabled(false); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); vm.prank(owner); @@ -1218,7 +1365,7 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, STRICT_MINIMUM_LIVENESS); RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); vm.prank(oracleInitializer); @@ -1253,7 +1400,7 @@ contract OOReporterTest { // Budget exhausted: gate is open again, but the re-request must revert. RequestData memory exhausted = reporter.getRequest(REQUEST_ID); assertEq(exhausted.manualRerequestsRemaining, 0, "budget should be exhausted"); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, exhausted.requestTimestamp, requestRules); vm.prank(oracleInitializer); @@ -1361,10 +1508,10 @@ contract OOReporterTest { function test_priceSettledRejectsUnauthorizedCallerAndIgnoresUnknownTuples() external { vm.prank(unauthorized); vm.expectRevert(IOOReporter.CallerNotOptimisticOracle.selector); - reporter.priceSettled(BINARY_IDENTIFIER, block.timestamp, _requestRules("primary"), 1 ether); + reporter.priceSettled(BINARY_IDENTIFIER, vm.getBlockTimestamp(), _requestRules("primary"), 1 ether); vm.prank(address(optimisticOracle)); - reporter.priceSettled(BINARY_IDENTIFIER, block.timestamp, _requestRules("unknown"), 1 ether); + reporter.priceSettled(BINARY_IDENTIFIER, vm.getBlockTimestamp(), _requestRules("unknown"), 1 ether); } function test_staleCallbacksDoNotMutateAfterRerequest() external { @@ -1375,13 +1522,13 @@ contract OOReporterTest { reporter.initializeRequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); RequestData memory firstRequest = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); // The first dispute automatically creates a replacement request and advances the active timestamp. optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, firstRequest.requestTimestamp, requestRules); RequestData memory activeRequest = reporter.getRequest(REQUEST_ID); - assertEq(activeRequest.requestTimestamp, block.timestamp, "active timestamp should advance"); + assertEq(activeRequest.requestTimestamp, vm.getBlockTimestamp(), "active timestamp should advance"); assertFalse(activeRequest.resolved, "active request should remain unresolved"); // A late settlement for the stale (replaced) request must not mutate the active request. @@ -1415,7 +1562,7 @@ contract OOReporterTest { function _disputeAndRerequest(bytes memory requestRules) internal { RequestData memory request = reporter.getRequest(REQUEST_ID); - vm.warp(block.timestamp + 1); + vm.warp(vm.getBlockTimestamp() + 1); optimisticOracle.disputePrice(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); vm.prank(oracleInitializer); reporter.rerequest(REQUEST_ID, 0, PROPOSAL_BOND, LIVENESS); diff --git a/test/reporters/PolymarketOOReporter.t.sol b/test/reporters/PolymarketOOReporter.t.sol new file mode 100644 index 0000000..a087e8d --- /dev/null +++ b/test/reporters/PolymarketOOReporter.t.sol @@ -0,0 +1,450 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.30; + +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; +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; + function expectEmit(address emitter) external; + function warp(uint256 newTimestamp) external; +} + +contract PolymarketReporterProxy { + bytes32 private constant IMPLEMENTATION_SLOT = bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1); + + constructor(address implementation, bytes memory data) { + bytes32 slot = IMPLEMENTATION_SLOT; + assembly { + sstore(slot, implementation) + } + + (bool success, bytes memory result) = implementation.delegatecall(data); + if (!success) { + assembly { + revert(add(result, 0x20), mload(result)) + } + } + } + + fallback() external payable { + bytes32 slot = IMPLEMENTATION_SLOT; + assembly { + let implementation := sload(slot) + calldatacopy(0, 0, calldatasize()) + let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) + returndatacopy(0, 0, returndatasize()) + switch result + case 0 { revert(0, returndatasize()) } + default { return(0, returndatasize()) } + } + } +} + +contract MockPolymarketOOReporterModule { + error ReportFailed(); + + IOOReporter public reporter; + bool public shouldRevert; + bytes32 public gasExhaustingRequestId; + uint256 public reportCount; + bytes32 public lastRequestId; + mapping(bytes32 requestId => bool reported) public reported; + address public lastReporter; + bool public observedResolved; + int256 public observedOutcome; + bytes32 private reentrantRequestId; + bytes32 private reentrantPriceIdentifier; + bytes private reentrantRequestRules; + uint64 private reentrantMinimumLiveness; + uint64 private reentrantMaximumLiveness; + + function setReporter(IOOReporter newReporter) external { + reporter = newReporter; + } + + function setShouldRevert(bool newShouldRevert) external { + shouldRevert = newShouldRevert; + } + + function setGasExhaustingRequestId(bytes32 requestId) external { + gasExhaustingRequestId = requestId; + } + + function setReentrantRegistration( + bytes32 requestId, + bytes32 priceIdentifier, + bytes calldata requestRules, + uint64 minimumLiveness, + uint64 maximumLiveness + ) external { + reentrantRequestId = requestId; + reentrantPriceIdentifier = priceIdentifier; + reentrantRequestRules = requestRules; + reentrantMinimumLiveness = minimumLiveness; + reentrantMaximumLiveness = maximumLiveness; + } + + function registerRequest( + bytes32 requestId, + bytes32 priceIdentifier, + bytes calldata requestRules, + uint64 minimumLiveness, + uint64 maximumLiveness + ) external { + reporter.registerRequest(requestId, priceIdentifier, requestRules, minimumLiveness, maximumLiveness); + } + + function report(bytes32 requestId) external { + if (shouldRevert) revert ReportFailed(); + + reportCount += 1; + lastRequestId = requestId; + reported[requestId] = true; + 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); + reporter.registerRequest( + requestIdToRegister, + reentrantPriceIdentifier, + reentrantRequestRules, + reentrantMinimumLiveness, + reentrantMaximumLiveness + ); + } + } +} + +contract PolymarketOOReporterTest { + PolymarketReporterVm private constant vm = + PolymarketReporterVm(address(uint160(uint256(keccak256("hevm cheat code"))))); + + event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome); + event ReportCallbackSucceeded(bytes32 indexed requestId, address indexed reporterModule); + event ReportCallbackFailed(bytes32 indexed requestId, address indexed reporterModule); + + bytes32 private constant REQUEST_ID = keccak256("polymarket-request-id"); + bytes32 private constant SECOND_REQUEST_ID = keccak256("second-polymarket-request-id"); + bytes32 private constant BINARY_IDENTIFIER = "YES_OR_NO_QUERY"; + uint64 private constant LIVENESS = 2 hours; + uint64 private constant MAXIMUM_LIVENESS = 2 days; + uint256 private constant DEFAULT_REREQUEST_BUDGET = 1; + + address private owner = address(0x1001); + address private oracleInitializer = address(0x1002); + + PolymarketOOReporter private reporter; + MockPolymarketOOReporterModule private module; + MockOptimisticOracleV2 private optimisticOracle; + MockERC20 private usdc; + + function setUp() external { + optimisticOracle = new MockOptimisticOracleV2(); + usdc = new MockERC20(); + module = new MockPolymarketOOReporterModule(); + + PolymarketOOReporter implementation = new PolymarketOOReporter(); + bytes memory initData = abi.encodeCall( + IOOReporter.initialize, + ( + owner, + address(optimisticOracle), + address(usdc), + oracleInitializer, + address(module), + DEFAULT_REREQUEST_BUDGET + ) + ); + reporter = PolymarketOOReporter(address(new PolymarketReporterProxy(address(implementation), initData))); + module.setReporter(IOOReporter(address(reporter))); + } + + function test_settlementAutomaticallyReportsResolvedOutcome() external { + bytes memory requestRules = _registerAndInitialize(); + RequestData memory request = reporter.getRequest(REQUEST_ID); + + vm.expectEmit(address(reporter)); + emit RequestResolved(REQUEST_ID, request.requestTimestamp, 1 ether); + vm.expectEmit(address(reporter)); + emit ReportCallbackSucceeded(REQUEST_ID, address(module)); + + optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); + + _assertEq(module.reportCount(), 1, "report count mismatch"); + _assertEq(module.lastRequestId(), REQUEST_ID, "request id mismatch"); + _assertEq(module.lastReporter(), address(reporter), "report caller mismatch"); + _assertTrue(module.observedResolved(), "report should observe resolved state"); + _assertEq(module.observedOutcome(), 1 ether, "reported outcome mismatch"); + } + + function test_settlementAutomaticallyReportsAllDuplicateRequestIds() external { + bytes memory requestRules = bytes("Will ETH reach 10k?"); + module.registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + module.registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + + vm.prank(oracleInitializer); + reporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); + + RequestData memory request = reporter.getRequest(REQUEST_ID); + optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); + vm.prank(oracleInitializer); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, 0, LIVENESS); + + _assertEq(module.reportCount(), 2, "report count mismatch"); + _assertTrue(module.reported(REQUEST_ID), "canonical request was not reported"); + _assertTrue(module.reported(SECOND_REQUEST_ID), "duplicate request was not reported"); + _assertTrue(reporter.isRequestResolved(SECOND_REQUEST_ID), "duplicate request should resolve"); + _assertEq(reporter.getRequestResolution(SECOND_REQUEST_ID), 1 ether, "duplicate outcome mismatch"); + } + + function test_initializeLateDuplicateImmediatelyReportsResolvedOutcomeOnce() external { + bytes memory requestRules = _registerAndInitialize(); + RequestData memory request = reporter.getRequest(REQUEST_ID); + optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); + + module.registerRequest(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + + _assertTrue(reporter.isRequestResolved(SECOND_REQUEST_ID), "late duplicate should resolve upon registration"); + _assertEq( + reporter.getRequestResolution(SECOND_REQUEST_ID), + 1 ether, + "outcome should be readable before initialization" + ); + + vm.expectEmit(address(reporter)); + emit RequestResolved(SECOND_REQUEST_ID, request.requestTimestamp, 1 ether); + vm.expectEmit(address(reporter)); + emit ReportCallbackSucceeded(SECOND_REQUEST_ID, address(module)); + vm.prank(oracleInitializer); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, 0, LIVENESS); + vm.prank(oracleInitializer); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, 0, LIVENESS); + + _assertEq(module.reportCount(), 2, "late duplicate should be reported once"); + _assertTrue(module.reported(SECOND_REQUEST_ID), "late duplicate was not reported"); + _assertEq(module.lastRequestId(), SECOND_REQUEST_ID, "late duplicate request id mismatch"); + _assertTrue(module.observedResolved(), "late report should observe resolved state"); + _assertEq(module.observedOutcome(), 1 ether, "late report outcome mismatch"); + } + + function test_reentrantRegistrationWaitsForLateInitialization() external { + bytes memory requestRules = bytes("Will ETH reach 10k?"); + module.registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + module.setReentrantRegistration(SECOND_REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + + vm.prank(oracleInitializer); + reporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); + RequestData memory request = reporter.getRequest(REQUEST_ID); + optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); + + _assertEq(module.reportCount(), 1, "reentrant duplicate should not join active fan-out"); + _assertFalse(module.reported(SECOND_REQUEST_ID), "reentrant duplicate should wait for initialization"); + + vm.expectEmit(address(reporter)); + emit RequestResolved(SECOND_REQUEST_ID, request.requestTimestamp, 1 ether); + vm.expectEmit(address(reporter)); + emit ReportCallbackSucceeded(SECOND_REQUEST_ID, address(module)); + vm.prank(oracleInitializer); + reporter.initializeRequest(SECOND_REQUEST_ID, 0, 0, LIVENESS); + + _assertEq(module.reportCount(), 2, "late duplicate should report after initialization"); + _assertTrue(module.reported(SECOND_REQUEST_ID), "late duplicate was not reported"); + } + + function test_reportFailureDoesNotRevertSettlementAndCanBeRetried() external { + bytes memory requestRules = _registerAndInitialize(); + RequestData memory request = reporter.getRequest(REQUEST_ID); + module.setShouldRevert(true); + + vm.expectEmit(address(reporter)); + emit RequestResolved(REQUEST_ID, request.requestTimestamp, 1 ether); + vm.expectEmit(address(reporter)); + emit ReportCallbackFailed(REQUEST_ID, address(module)); + + optimisticOracle.settle(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether); + + _assertTrue(reporter.isRequestResolved(REQUEST_ID), "reporter should remain resolved"); + _assertEq(reporter.getRequestResolution(REQUEST_ID), 1 ether, "stored outcome mismatch"); + bytes32 requestKey = + optimisticOracle.requestKey(address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules); + _assertTrue(optimisticOracle.getMockRequest(requestKey).settled, "oracle settlement should persist"); + + module.setShouldRevert(false); + module.report(REQUEST_ID); + _assertEq(module.reportCount(), 1, "permissionless retry should succeed"); + } + + function test_largeFanoutFallsBackToIndividualReportsWhenSettlementGasIsConstrained() external { + uint256 linkedRequestCount = 10; + bytes memory requestRules = bytes("Will ETH reach 10k?"); + for (uint256 i = 1; i <= linkedRequestCount; ++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))); + + for (uint256 i = 1; i <= linkedRequestCount; ++i) { + vm.expectEmit(address(reporter)); + emit RequestResolved(bytes32(i), request.requestTimestamp, 1 ether); + } + + bytes memory settleCall = abi.encodeCall( + MockOptimisticOracleV2.settle, + (address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, 1 ether) + ); + // This cap covers settlement bookkeeping and resolution events, but not the complete callback fan-out. + (bool success,) = address(optimisticOracle).call{gas: 500_000}(settleCall); + + _assertTrue(success, "oracle settlement should survive fan-out exhaustion"); + 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); + _assertTrue(optimisticOracle.getMockRequest(requestKey).settled, "oracle settlement should persist"); + + for (uint256 i = 1; i <= linkedRequestCount; ++i) { + bytes32 requestId = bytes32(i); + 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); + + vm.prank(owner); + reporter.setAutomaticRerequestsEnabled(false); + optimisticOracle.settle( + address(reporter), BINARY_IDENTIFIER, request.requestTimestamp, requestRules, reporter.P4_PRICE() + ); + + _assertEq(module.reportCount(), 0, "P4 should not report"); + _assertFalse(reporter.isRequestResolved(REQUEST_ID), "P4 should not resolve reporter request"); + _assertTrue(reporter.getRequest(REQUEST_ID).rerequestAllowed, "P4 should open rerequest gate"); + } + + function test_staleSettlementDoesNotReport() external { + bytes memory requestRules = _registerAndInitialize(); + RequestData memory initialRequest = reporter.getRequest(REQUEST_ID); + + vm.warp(block.timestamp + 1); + optimisticOracle.disputePrice( + address(reporter), BINARY_IDENTIFIER, initialRequest.requestTimestamp, requestRules + ); + RequestData memory activeRequest = reporter.getRequest(REQUEST_ID); + + optimisticOracle.settle( + address(reporter), BINARY_IDENTIFIER, initialRequest.requestTimestamp, requestRules, 1 ether + ); + + _assertEq(module.reportCount(), 0, "stale settlement should not report"); + _assertFalse(reporter.isRequestResolved(REQUEST_ID), "stale settlement should not resolve active request"); + _assertEq( + reporter.getRequest(REQUEST_ID).requestTimestamp, + activeRequest.requestTimestamp, + "stale settlement should not replace active timestamp" + ); + } + + function _registerAndInitialize() private returns (bytes memory requestRules) { + requestRules = bytes("Will ETH reach 10k?"); + module.registerRequest(REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + + vm.prank(oracleInitializer); + reporter.initializeRequest(REQUEST_ID, 0, 0, LIVENESS); + } + + function _assertTrue(bool condition, string memory message) private pure { + if (!condition) revert(message); + } + + function _assertFalse(bool condition, string memory message) private pure { + if (condition) revert(message); + } + + function _assertEq(uint256 actual, uint256 expected, string memory message) private pure { + if (actual != expected) revert(message); + } + + function _assertEq(int256 actual, int256 expected, string memory message) private pure { + if (actual != expected) revert(message); + } + + function _assertEq(bytes32 actual, bytes32 expected, string memory message) private pure { + if (actual != expected) revert(message); + } + + function _assertEq(address actual, address expected, string memory message) private pure { + if (actual != expected) revert(message); + } +} 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)); + } + } +} diff --git a/pm-v2-oo-reporter/test/PolymarketOOReporterUpgrade.t.sol b/test/reporters/PolymarketOOReporterUpgrade.t.sol similarity index 55% rename from pm-v2-oo-reporter/test/PolymarketOOReporterUpgrade.t.sol rename to test/reporters/PolymarketOOReporterUpgrade.t.sol index e2fc66a..8b52d0e 100644 --- a/pm-v2-oo-reporter/test/PolymarketOOReporterUpgrade.t.sol +++ b/test/reporters/PolymarketOOReporterUpgrade.t.sol @@ -1,20 +1,25 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {Test} from "forge-std/Test.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; -import {PolymarketOOReporter} from "src/PolymarketOOReporter.sol"; -import {IOOReporter} from "src/interfaces/IOOReporter.sol"; -import {LegacyOOReporter, LegacyRequestData} from "test/mocks/LegacyOOReporter.sol"; -import {MockERC20} from "test/mocks/MockERC20.sol"; -import {MockOptimisticOracleV2} from "test/mocks/MockOptimisticOracleV2.sol"; +import {OOReporter} from "src/reporters/OOReporter.sol"; +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; +import {IOOReporter, RequestData} from "src/reporters/interfaces/IOOReporter.sol"; +import {LegacyOOReporter, LegacyRequestData} from "test/reporters/mocks/LegacyOOReporter.sol"; +import {MockERC20} from "test/reporters/mocks/MockERC20.sol"; +import {MockOptimisticOracleV2} from "test/reporters/mocks/MockOptimisticOracleV2.sol"; interface IUUPSUpgrade { function upgradeToAndCall(address newImplementation, bytes calldata data) external payable; } contract UpgradeOwner { + function acceptOwnership(OOReporter reporter) external { + reporter.acceptOwnership(); + } + function execute(address target, bytes calldata data) external { (bool success, bytes memory returnData) = target.call(data); if (!success) { @@ -57,6 +62,8 @@ contract UpgradeReporterModule { } contract PolymarketOOReporterUpgradeTest is Test { + event RequestResolved(bytes32 indexed requestId, uint256 indexed requestTimestamp, int256 outcome); + bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 private constant RESOLVED_REQUEST_ID = keccak256("resolved-before-upgrade"); bytes32 private constant PENDING_REQUEST_ID = keccak256("pending-during-upgrade"); @@ -69,7 +76,7 @@ contract PolymarketOOReporterUpgradeTest is Test { address private oracleInitializer = address(0x1002); address private unauthorized = address(0x1003); - LegacyOOReporter private legacyReporter; + OOReporter private baseReporter; UpgradeReporterModule private module; MockOptimisticOracleV2 private optimisticOracle; MockERC20 private usdc; @@ -79,9 +86,9 @@ contract PolymarketOOReporterUpgradeTest is Test { usdc = new MockERC20(); module = new UpgradeReporterModule(); - LegacyOOReporter implementation = new LegacyOOReporter(); + OOReporter implementation = new OOReporter(); bytes memory initData = abi.encodeCall( - LegacyOOReporter.initialize, + IOOReporter.initialize, ( owner, address(optimisticOracle), @@ -91,30 +98,30 @@ contract PolymarketOOReporterUpgradeTest is Test { DEFAULT_REREQUEST_BUDGET ) ); - legacyReporter = LegacyOOReporter(address(new ERC1967Proxy(address(implementation), initData))); - module.setReporter(IOOReporter(address(legacyReporter))); + baseReporter = OOReporter(address(new ERC1967Proxy(address(implementation), initData))); + module.setReporter(IOOReporter(address(baseReporter))); } function test_upgradePreservesStateAndEnablesCallback() external { bytes memory resolvedRules = bytes("resolved before upgrade"); _registerAndInitialize(RESOLVED_REQUEST_ID, resolvedRules); - LegacyRequestData memory resolvedBefore = legacyReporter.getRequest(RESOLVED_REQUEST_ID); + RequestData memory resolvedBefore = baseReporter.getRequest(RESOLVED_REQUEST_ID); optimisticOracle.settle( - address(legacyReporter), BINARY_IDENTIFIER, resolvedBefore.requestTimestamp, resolvedRules, 1 ether + address(baseReporter), BINARY_IDENTIFIER, resolvedBefore.requestTimestamp, resolvedRules, 1 ether ); - resolvedBefore = legacyReporter.getRequest(RESOLVED_REQUEST_ID); - assertTrue(resolvedBefore.resolved, "legacy request should resolve"); - assertEq(module.reportCount(), 0, "legacy implementation should not report"); + resolvedBefore = baseReporter.getRequest(RESOLVED_REQUEST_ID); + assertTrue(resolvedBefore.resolved, "base request should resolve"); + assertEq(module.reportCount(), 0, "base implementation should not report"); bytes memory pendingRules = bytes("pending during upgrade"); _registerAndInitialize(PENDING_REQUEST_ID, pendingRules); - LegacyRequestData memory pendingBefore = legacyReporter.getRequest(PENDING_REQUEST_ID); + RequestData memory pendingBefore = baseReporter.getRequest(PENDING_REQUEST_ID); PolymarketOOReporter implementation = new PolymarketOOReporter(); vm.prank(owner); - IUUPSUpgrade(address(legacyReporter)).upgradeToAndCall(address(implementation), bytes("")); + IUUPSUpgrade(address(baseReporter)).upgradeToAndCall(address(implementation), bytes("")); - PolymarketOOReporter upgraded = PolymarketOOReporter(address(legacyReporter)); + PolymarketOOReporter upgraded = PolymarketOOReporter(address(baseReporter)); assertEq(upgraded.owner(), owner, "owner changed"); assertEq(upgraded.pendingOwner(), address(0), "pending owner should start empty"); assertEq(address(upgraded.optimisticOracle()), address(optimisticOracle), "oracle changed"); @@ -138,6 +145,8 @@ contract PolymarketOOReporterUpgradeTest is Test { ); assertEq(upgraded.getRequestId(BINARY_IDENTIFIER, pendingRules), PENDING_REQUEST_ID, "pending lookup changed"); + vm.expectEmit(address(upgraded)); + emit RequestResolved(PENDING_REQUEST_ID, pendingBefore.requestTimestamp, 1 ether); optimisticOracle.settle( address(upgraded), BINARY_IDENTIFIER, pendingBefore.requestTimestamp, pendingRules, 1 ether ); @@ -149,40 +158,104 @@ contract PolymarketOOReporterUpgradeTest is Test { assertEq(module.observedOutcome(), 1 ether, "callback outcome mismatch"); } + function test_upgradeFromLegacyPreservesSettlementCallback() external { + (LegacyOOReporter legacyReporter, UpgradeReporterModule legacyModule) = _deployLegacyReporter(); + bytes memory requestRules = bytes("pending legacy request"); + legacyModule.registerRequest(PENDING_REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + vm.prank(oracleInitializer); + legacyReporter.initializeRequest(PENDING_REQUEST_ID, 0, 0, LIVENESS); + LegacyRequestData memory pendingBefore = legacyReporter.getRequest(PENDING_REQUEST_ID); + + PolymarketOOReporter implementation = new PolymarketOOReporter(); + vm.prank(owner); + IUUPSUpgrade(address(legacyReporter)).upgradeToAndCall(address(implementation), bytes("")); + PolymarketOOReporter upgraded = PolymarketOOReporter(address(legacyReporter)); + + vm.expectEmit(address(upgraded)); + emit RequestResolved(PENDING_REQUEST_ID, pendingBefore.requestTimestamp, 1 ether); + optimisticOracle.settle( + address(upgraded), BINARY_IDENTIFIER, pendingBefore.requestTimestamp, requestRules, 1 ether + ); + + assertEq(legacyModule.reportCount(), 1, "legacy callback not invoked"); + assertEq(legacyModule.lastRequestId(), PENDING_REQUEST_ID, "legacy callback request id mismatch"); + assertEq(legacyModule.lastReporter(), address(upgraded), "legacy callback reporter mismatch"); + assertTrue(legacyModule.observedResolved(), "legacy callback observed unresolved request"); + assertEq(legacyModule.observedOutcome(), 1 ether, "legacy callback outcome mismatch"); + } + + function test_upgradeFromLegacyCountsCanonicalRequestTowardLimit() external { + (LegacyOOReporter legacyReporter, UpgradeReporterModule legacyModule) = _deployLegacyReporter(); + bytes memory requestRules = bytes("legacy request with duplicates"); + legacyModule.registerRequest(PENDING_REQUEST_ID, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + + PolymarketOOReporter implementation = new PolymarketOOReporter(); + vm.prank(owner); + IUUPSUpgrade(address(legacyReporter)).upgradeToAndCall(address(implementation), bytes("")); + + for (uint256 i = 2; i <= 10; ++i) { + legacyModule.registerRequest(bytes32(i), BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + } + vm.expectRevert(OOReporter.ReporterRequestIdLimitReached.selector); + legacyModule.registerRequest(bytes32(uint256(11)), BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); + } + function test_upgradeRejectsNonOwner() external { PolymarketOOReporter implementation = new PolymarketOOReporter(); - bytes32 implementationBefore = vm.load(address(legacyReporter), IMPLEMENTATION_SLOT); + bytes32 implementationBefore = vm.load(address(baseReporter), IMPLEMENTATION_SLOT); vm.prank(unauthorized); vm.expectRevert(abi.encodeWithSelector(bytes4(keccak256("OwnableUnauthorizedAccount(address)")), unauthorized)); - IUUPSUpgrade(address(legacyReporter)).upgradeToAndCall(address(implementation), bytes("")); + IUUPSUpgrade(address(baseReporter)).upgradeToAndCall(address(implementation), bytes("")); - assertEq(vm.load(address(legacyReporter), IMPLEMENTATION_SLOT), implementationBefore, "implementation changed"); - assertEq(legacyReporter.owner(), owner, "owner changed"); + assertEq(vm.load(address(baseReporter), IMPLEMENTATION_SLOT), implementationBefore, "implementation changed"); + assertEq(baseReporter.owner(), owner, "owner changed"); } function test_upgradeSupportsPredeployedImplementationAndContractOwner() external { UpgradeOwner upgradeOwner = new UpgradeOwner(); vm.prank(owner); - legacyReporter.transferOwnership(address(upgradeOwner)); + baseReporter.transferOwnership(address(upgradeOwner)); + upgradeOwner.acceptOwnership(baseReporter); PolymarketOOReporter implementation = new PolymarketOOReporter(); bytes memory upgradeCall = abi.encodeCall(IUUPSUpgrade.upgradeToAndCall, (address(implementation), bytes(""))); - upgradeOwner.execute(address(legacyReporter), upgradeCall); + upgradeOwner.execute(address(baseReporter), upgradeCall); assertEq( - address(uint160(uint256(vm.load(address(legacyReporter), IMPLEMENTATION_SLOT)))), + address(uint160(uint256(vm.load(address(baseReporter), IMPLEMENTATION_SLOT)))), address(implementation), "implementation mismatch" ); - assertEq(legacyReporter.owner(), address(upgradeOwner), "contract owner changed"); - assertEq(address(legacyReporter.optimisticOracle()), address(optimisticOracle), "oracle changed"); - assertEq(address(legacyReporter.rewardCurrency()), address(usdc), "currency changed"); + assertEq(baseReporter.owner(), address(upgradeOwner), "contract owner changed"); + assertEq(address(baseReporter.optimisticOracle()), address(optimisticOracle), "oracle changed"); + assertEq(address(baseReporter.rewardCurrency()), address(usdc), "currency changed"); } function _registerAndInitialize(bytes32 requestId, bytes memory requestRules) private { module.registerRequest(requestId, BINARY_IDENTIFIER, requestRules, 0, MAXIMUM_LIVENESS); vm.prank(oracleInitializer); - legacyReporter.initializeRequest(requestId, 0, 0, LIVENESS); + baseReporter.initializeRequest(requestId, 0, 0, LIVENESS); + } + + function _deployLegacyReporter() + private + returns (LegacyOOReporter legacyReporter, UpgradeReporterModule legacyModule) + { + legacyModule = new UpgradeReporterModule(); + LegacyOOReporter implementation = new LegacyOOReporter(); + bytes memory initData = abi.encodeCall( + LegacyOOReporter.initialize, + ( + owner, + address(optimisticOracle), + address(usdc), + oracleInitializer, + address(legacyModule), + DEFAULT_REREQUEST_BUDGET + ) + ); + legacyReporter = LegacyOOReporter(address(new ERC1967Proxy(address(implementation), initData))); + legacyModule.setReporter(IOOReporter(address(legacyReporter))); } } diff --git a/test/reporters/UpgradeOOReporterScript.t.sol b/test/reporters/UpgradeOOReporterScript.t.sol new file mode 100644 index 0000000..2f9a76d --- /dev/null +++ b/test/reporters/UpgradeOOReporterScript.t.sol @@ -0,0 +1,124 @@ +// 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 {OOReporter} from "src/reporters/OOReporter.sol"; +import {IOOReporter} from "src/reporters/interfaces/IOOReporter.sol"; +import {PolymarketOOReporter} from "src/reporters/integrations/PolymarketOOReporter.sol"; +import {UpgradeOOReporter} from "script/reporters/UpgradeOOReporter.s.sol"; +import {MockERC20} from "test/reporters/mocks/MockERC20.sol"; +import {MockOptimisticOracleV2} from "test/reporters/mocks/MockOptimisticOracleV2.sol"; +import {AddressWhitelist} from "src/common/implementation/AddressWhitelist.sol"; + +contract UpgradeScriptOracle is MockOptimisticOracleV2 { + address public immutable requesterWhitelist; + + constructor(address whitelist) { + requesterWhitelist = whitelist; + } +} + +contract UpgradeOOReporterHarness is UpgradeOOReporter { + function validateRegistration(OOReporter reporter, Vm.EthGetLogs memory requestLog, address requester) + external + view + returns (bytes32) + { + return _validateRegisteredRequest(reporter, requestLog, requester, 0); + } + + function snapshot(OOReporter reporter, Config memory config, bytes32[] memory requestIds) + external + view + returns (ReporterState memory) + { + return _snapshotReporterState(reporter, config, requestIds); + } + + function validatePostUpgrade( + OOReporter reporter, + Config memory config, + ReporterState memory expectedState, + bytes32[] memory requestIds, + address implementation + ) external view { + _validatePostUpgrade(reporter, config, expectedState, requestIds, implementation); + } +} + +contract UpgradeOOReporterScriptTest is Test { + OOReporter public ooReporter; + + function test_registrationValidationAcceptsAliasesAcrossUpgradeAndRejectsMismatchedLogs() public { + AddressWhitelist whitelist = new AddressWhitelist(); + UpgradeScriptOracle oracle = new UpgradeScriptOracle(address(whitelist)); + MockERC20 currency = new MockERC20(); + OOReporter reporter = OOReporter( + address( + new ERC1967Proxy( + address(new PolymarketOOReporter()), + abi.encodeCall( + IOOReporter.initialize, + (address(this), address(oracle), address(currency), address(this), address(this), 5) + ) + ) + ) + ); + ooReporter = reporter; + whitelist.addToWhitelist(address(reporter)); + UpgradeOOReporterHarness script = new UpgradeOOReporterHarness(); + bytes32 canonicalId = keccak256("canonical"); + bytes32 aliasId = keccak256("alias"); + bytes32 identifier = "YES_OR_NO_QUERY"; + bytes memory rules = bytes("shared rules"); + + vm.recordLogs(); + reporter.registerRequest(canonicalId, identifier, rules, 0, 2 days); + reporter.registerRequest(aliasId, identifier, rules, 0, 2 days); + Vm.Log[] memory logs = vm.getRecordedLogs(); + assertEq(logs.length, 2); + assertEq(reporter.getRequestId(identifier, rules), canonicalId); + + UpgradeOOReporter.Config memory config; + config.proxy = address(reporter); + config.expectedCurrentOptimisticOracle = address(oracle); + config.expectedMooRequesterWhitelist = address(whitelist); + config.expectedRequester = address(this); + config.expectedOracleInitializer = address(this); + bytes32[] memory requestIds = new bytes32[](2); + requestIds[0] = canonicalId; + requestIds[1] = aliasId; + UpgradeOOReporter.ReporterState memory stateBefore = script.snapshot(reporter, config, requestIds); + address finalImplementation = address(new PolymarketOOReporter()); + + for (uint256 pass; pass < 2; ++pass) { + if (pass == 1) { + reporter.upgradeToAndCall(finalImplementation, ""); + script.validatePostUpgrade(reporter, config, stateBefore, requestIds, finalImplementation); + } + for (uint256 i; i < logs.length; ++i) { + Vm.EthGetLogs memory requestLog; + requestLog.emitter = logs[i].emitter; + requestLog.topics = logs[i].topics; + requestLog.data = logs[i].data; + assertEq( + script.validateRegistration(reporter, requestLog, address(this)), i == 0 ? canonicalId : aliasId + ); + + requestLog.data = abi.encode(bytes("different rules"), uint64(0), uint64(2 days)); + vm.expectRevert( + abi.encodeWithSelector( + UpgradeOOReporter.RegisteredRequestStateMismatch.selector, requestLog.topics[1] + ) + ); + script.validateRegistration(reporter, requestLog, address(this)); + } + } + + reporter.initializeRequest(aliasId, 0, 0, 2 hours); + vm.expectRevert(abi.encodeWithSelector(UpgradeOOReporter.RequestStateChanged.selector, canonicalId)); + script.validatePostUpgrade(reporter, config, stateBefore, requestIds, finalImplementation); + } +} diff --git a/pm-v2-oo-reporter/test/mocks/LegacyOOReporter.sol b/test/reporters/mocks/LegacyOOReporter.sol similarity index 97% rename from pm-v2-oo-reporter/test/mocks/LegacyOOReporter.sol rename to test/reporters/mocks/LegacyOOReporter.sol index 00bc414..5008a8d 100644 --- a/pm-v2-oo-reporter/test/mocks/LegacyOOReporter.sol +++ b/test/reporters/mocks/LegacyOOReporter.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {MulticallUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import {IOptimisticOracleV2} from "src/interfaces/IOptimisticOracleV2.sol"; -import {IOptimisticRequester} from "src/interfaces/IOptimisticRequester.sol"; +import {IOptimisticOracleV2} from "src/reporters/interfaces/IOptimisticOracleV2.sol"; +import {IOptimisticRequester} from "src/reporters/interfaces/IOptimisticRequester.sol"; /// @dev Frozen pre-callback request layout. Do not replace with the current production struct. struct LegacyRequestData { diff --git a/pm-v2-oo-reporter/test/mocks/MockERC20.sol b/test/reporters/mocks/MockERC20.sol similarity index 98% rename from pm-v2-oo-reporter/test/mocks/MockERC20.sol rename to test/reporters/mocks/MockERC20.sol index e94605a..1e2ff16 100644 --- a/pm-v2-oo-reporter/test/mocks/MockERC20.sol +++ b/test/reporters/mocks/MockERC20.sol @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; diff --git a/pm-v2-oo-reporter/test/mocks/MockOptimisticOracleV2.sol b/test/reporters/mocks/MockOptimisticOracleV2.sol similarity index 97% rename from pm-v2-oo-reporter/test/mocks/MockOptimisticOracleV2.sol rename to test/reporters/mocks/MockOptimisticOracleV2.sol index 39c6ca3..33d5b02 100644 --- a/pm-v2-oo-reporter/test/mocks/MockOptimisticOracleV2.sol +++ b/test/reporters/mocks/MockOptimisticOracleV2.sol @@ -1,11 +1,11 @@ // SPDX-License-Identifier: MIT -pragma solidity 0.8.34; +pragma solidity 0.8.30; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import {IOptimisticOracleV2} from "src/interfaces/IOptimisticOracleV2.sol"; -import {IOptimisticRequester} from "src/interfaces/IOptimisticRequester.sol"; -import {IOOReporter} from "src/interfaces/IOOReporter.sol"; +import {IOptimisticOracleV2} from "src/reporters/interfaces/IOptimisticOracleV2.sol"; +import {IOptimisticRequester} from "src/reporters/interfaces/IOptimisticRequester.sol"; +import {IOOReporter} from "src/reporters/interfaces/IOOReporter.sol"; contract MockOptimisticOracleV2 is IOptimisticOracleV2 { struct MockRequest {