From 32e23e49a82dd95ad7621bb2517d33e4587b043d Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Mon, 31 Aug 2026 14:56:36 +0200 Subject: [PATCH 1/6] managed-oracle: add partial-success SignedProposer batching (#72) --- script/README.md | 40 ++ src/common/implementation/TryMulticall.sol | 59 ++ .../implementation/SignedProposer.sol | 14 +- test/SignedProposer.t.sol | 564 ++++++++++++++++++ test/SignedProposerPermit2.t.sol | 315 +++++++++- test/SignedProposerTryMulticall.Fork.t.sol | 177 ++++++ test/mocks/MaliciousSignedProposerOracle.sol | 10 + 7 files changed, 1172 insertions(+), 7 deletions(-) create mode 100644 src/common/implementation/TryMulticall.sol create mode 100644 test/SignedProposerTryMulticall.Fork.t.sol diff --git a/script/README.md b/script/README.md index 92bb76b..ca5c3e3 100644 --- a/script/README.md +++ b/script/README.md @@ -325,6 +325,46 @@ forge script script/DeploySignedProposer.s.sol --rpc-url "YOUR_RPC_URL" --broadc The script only deploys the contract. The admin configures delegated proposers and any required whitelist ownership separately. +### Partial-success proposal batches + +Delegated proposers can submit ABI-encoded `SignedProposer.propose` calls through +`tryMulticall(bytes[])`. There is no contract-level batch-size or per-child gas limit; transaction +calldata, client transaction-pool policy, and available block gas provide the practical bounds. +Each valid child executes by self-delegatecall with the original relayer as `msg.sender`. A child +revert does not roll back successful siblings if the outer call retains enough gas to finish. Under +EIP-150, a gas-exhausting child can return `false` while preserving 1/64 of the caller's gas, so the +outer call may continue; however, later children can then be gas-starved and also return `false`. +If the remaining outer gas is insufficient to finish the loop or encode the result, the entire +batch reverts and rolls back earlier successes. + +Polygon Bor rejects transactions larger than 128 KiB. With the maximum valid OOv2 ancillary data +of 8,139 non-zero bytes, each encoded `propose` child is 8,804 bytes: 14 children produce 124,612 +bytes of outer calldata and execute within the 53,902,641 gas limit at pinned block `81,683,818`, +while 15 children produce 133,508 bytes before the signed transaction envelope and are rejected. +Smaller ancillary data permits larger batches, subject to the same transaction-size and gas bounds. + +The function returns a `bool[]` aligned with the submitted calls. A failed child also emits: + +```solidity +event ProposalCallFailed( + uint256 indexed index, + bytes32 indexed callHash, + bytes4 errorSelector, + bytes32 revertDataHash +); +``` + +`callHash` is `keccak256(calls[index])`, `errorSelector` is the first four revert-data bytes (or +zero when unavailable), and `revertDataHash` hashes the complete revert data. Full proposal +calldata, signatures, and revert data are never logged. Successful children continue to emit the +existing `ProposalExecuted` and oracle `ProposePrice` events. Consumers should use those events as +the authoritative success evidence. A `false` result and `ProposalCallFailed` mean only that the +execution attempt did not complete successfully; they do not prove the proposal itself is invalid. +In particular, empty failure metadata is ambiguous between an empty revert and out-of-gas. + +OpenZeppelin `multicall(bytes[])` remains available and atomic for compatibility. `tryMulticall` +does not change worker behavior; worker integration must be performed separately. + ### Verification ```bash diff --git a/src/common/implementation/TryMulticall.sol b/src/common/implementation/TryMulticall.sol new file mode 100644 index 0000000..f7cd4eb --- /dev/null +++ b/src/common/implementation/TryMulticall.sol @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: AGPL-3.0-only +pragma solidity ^0.8.27; + +/** + * @title TryMulticall + * @notice Executes allowed self-delegatecalls without reverting successful siblings. + */ +abstract contract TryMulticall { + bool private _tryMulticallEntered; + + /// @notice Emitted when a child execution attempt returns unsuccessfully. + /// @dev Empty failure metadata can mean either an empty revert or an out-of-gas child. This event does not prove + /// the submitted operation itself is invalid; callers may retry it with a different gas allocation. + event ProposalCallFailed( + uint256 indexed index, bytes32 indexed callHash, bytes4 errorSelector, bytes32 revertDataHash + ); + + error TryMulticallReentrantCall(); + error TryMulticallInvalidSelector(uint256 index, bytes4 selector); + + /** + * @notice Executes allowed calls independently and returns their execution-attempt success values. + * @dev Self-delegatecall preserves the original caller. Ordinary failures emit only bounded metadata. There is no + * child gas or revert-data cap. Under EIP-150, an out-of-gas child can return `false` while leaving the outer call + * enough gas to continue, but later children may receive too little gas and also return `false`. If the remaining + * outer gas cannot finish the loop or encode the result, the full batch reverts. A `false` value therefore means + * only that the corresponding execution attempt failed; it does not prove the submitted operation is invalid. + */ + function tryMulticall(bytes[] calldata calls) external returns (bool[] memory successes) { + _checkTryMulticallCaller(); + if (_tryMulticallEntered) revert TryMulticallReentrantCall(); + + uint256 callsLength = calls.length; + bytes4 allowedSelector = _tryMulticallSelector(); + for (uint256 i; i < callsLength; ++i) { + bytes calldata callData = calls[i]; + bytes4 selector = callData.length >= 4 ? bytes4(callData[:4]) : bytes4(0); + if (selector != allowedSelector) revert TryMulticallInvalidSelector(i, selector); + } + + successes = new bool[](callsLength); + _tryMulticallEntered = true; + for (uint256 i; i < callsLength; ++i) { + bytes calldata callData = calls[i]; + (bool success, bytes memory revertData) = address(this).delegatecall(callData); + successes[i] = success; + + if (!success) { + bytes4 errorSelector = revertData.length >= 4 ? bytes4(revertData) : bytes4(0); + emit ProposalCallFailed(i, keccak256(callData), errorSelector, keccak256(revertData)); + } + } + _tryMulticallEntered = false; + } + + function _checkTryMulticallCaller() internal view virtual; + + function _tryMulticallSelector() internal view virtual returns (bytes4); +} diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 764fa4f..7920288 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -11,6 +11,7 @@ import {SignedProposerOracleInterface} from "../interfaces/SignedProposerOracleI import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; import {AddressWhitelist} from "../../common/implementation/AddressWhitelist.sol"; import {AddressWhitelistInterface} from "../../common/interfaces/AddressWhitelistInterface.sol"; +import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; /** * @title SignedProposer @@ -31,10 +32,10 @@ import {AddressWhitelistInterface} from "../../common/interfaces/AddressWhitelis * the signer-approved Permit2 amount for that proposal. * * The contract is permissioned: - * - `DELEGATED_PROPOSER_ROLE` — may call `propose`. + * - `DELEGATED_PROPOSER_ROLE` — may call `propose` and `tryMulticall`. * - `WHITELIST_ADMIN_ROLE` — may directly add/remove entries on whitelists owned by this contract. */ -contract SignedProposer is AccessControl, Multicall, ReentrancyGuard { +contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMulticall { using SafeERC20 for IERC20; // ─── Structs ────────────────────────────────────────────────────────────────── @@ -89,7 +90,6 @@ contract SignedProposer is AccessControl, Multicall, ReentrancyGuard { error PermitTokenMismatch(address requestCurrency, address permitToken); error CannotRemoveSelfFromWhitelist(); error NewOwnerNotWhitelisted(address newOwner); - // ─── Constructor ────────────────────────────────────────────────────────────── constructor(ISignatureTransfer _permit2, address admin) { @@ -142,6 +142,14 @@ contract SignedProposer is AccessControl, Multicall, ReentrancyGuard { // ─── Internals ──────────────────────────────────────────────────────────────── + function _checkTryMulticallCaller() internal view override { + _checkRole(DELEGATED_PROPOSER_ROLE); + } + + function _tryMulticallSelector() internal pure override returns (bytes4) { + return SignedProposer.propose.selector; + } + function _getRequestCurrency(Proposal calldata proposal) internal view returns (IERC20) { OptimisticOracleV2Interface.Request memory request = OptimisticOracleV2Interface(proposal.oracle).getRequest( proposal.requester, proposal.identifier, proposal.timestamp, proposal.ancillaryData diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index e43dc09..570ccf7 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -4,6 +4,7 @@ pragma solidity ^0.8.27; import {Test} from "forge-std/Test.sol"; import {SignedProposer} from "src/optimistic-oracle-v2/implementation/SignedProposer.sol"; +import {TryMulticall} from "src/common/implementation/TryMulticall.sol"; import {ManagedOptimisticOracleV2} from "src/optimistic-oracle-v2/implementation/ManagedOptimisticOracleV2.sol"; import {OptimisticOracleV2Interface} from "src/optimistic-oracle-v2/interfaces/OptimisticOracleV2Interface.sol"; import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; @@ -43,6 +44,21 @@ contract ShortTransferERC20Mock is ERC20Mock { } contract SignedProposerTest is Test { + event ProposalExecuted( + address indexed proposer, + address indexed oracle, + address indexed requester, + bytes32 identifier, + uint256 timestamp, + int256 proposedPrice, + uint256 totalBond, + uint256 payment + ); + + event ProposalCallFailed( + uint256 indexed index, bytes32 indexed callHash, bytes4 errorSelector, bytes32 revertDataHash + ); + SignedProposer internal signedProposer; ManagedOptimisticOracleV2 internal moo; MockPermit2 internal mockPermit2; @@ -74,6 +90,9 @@ contract SignedProposerTest is Test { uint256 internal constant BOND = 100 ether; uint256 internal constant FINAL_FEE = 10 ether; uint256 internal constant TOTAL_BOND = BOND + FINAL_FEE; + uint256 internal constant FULL_BATCH_REVERT_GAS = 1_000_000; + uint256 internal constant GAS_STARVATION_CONTINUATION_GAS = 8_000_000; + uint256 internal constant LATER_CHILD_RECOVERY_GAS = 30_000_000; bytes32 internal constant DELEGATED_PROPOSER_ROLE = keccak256("DELEGATED_PROPOSER_ROLE"); bytes32 internal constant WHITELIST_ADMIN_ROLE = keccak256("WHITELIST_ADMIN_ROLE"); @@ -241,6 +260,66 @@ contract SignedProposerTest is Test { ); } + function _encodeProposalCall( + SignedProposer.Proposal memory proposal, + address proposalOwner, + ISignatureTransfer.PermitTransferFrom memory permit, + bytes memory signature, + uint256 payment + ) internal pure returns (bytes memory) { + return abi.encodeCall(SignedProposer.propose, (proposal, proposalOwner, permit, signature, payment)); + } + + function _revertSelector(bytes memory revertData) internal pure returns (bytes4 selector) { + if (revertData.length >= 4) { + assembly ("memory-safe") { + selector := mload(add(revertData, 0x20)) + } + } + } + + function _buildRevertingProposal(bool exhaustGas, uint256 revertDataSize, uint256 timestamp, int256 price) + internal + returns (SignedProposer.Proposal memory proposal) + { + RevertingSignedProposerOracle revertingOracle = + new RevertingSignedProposerOracle(IERC20(address(currency)), exhaustGas, revertDataSize); + proposal = SignedProposer.Proposal({ + oracle: address(revertingOracle), + requester: requester, + identifier: IDENTIFIER, + timestamp: timestamp, + ancillaryData: ANCILLARY, + proposedPrice: price, + maxPayment: 0 + }); + } + + function _gasExhaustingThenValidCalls() internal returns (bytes[] memory calls, uint256 validTimestamp) { + validTimestamp = block.timestamp; + _makeRequest(validTimestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND); + + SignedProposer.Proposal memory gasExhaustingProposal = _buildRevertingProposal(true, 0, validTimestamp, 1 ether); + SignedProposer.Proposal memory validProposal = _buildProposal(validTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + calls = new bytes[](2); + calls[0] = _encodeProposalCall(gasExhaustingProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(validProposal, proposer, permit, "", 0); + } + + function _tryMulticallWithGas(bytes[] memory calls, uint256 gasLimit) + internal + returns (bool outerSuccess, bool[] memory successes) + { + vm.prank(relayer); + bytes memory returnData; + (outerSuccess, returnData) = + address(signedProposer).call{gas: gasLimit}(abi.encodeCall(TryMulticall.tryMulticall, (calls))); + if (outerSuccess) successes = abi.decode(returnData, (bool[])); + } + // ─── Propose tests ────────────────────────────────────────────────────────── function test_propose() public { @@ -371,6 +450,419 @@ contract SignedProposerTest is Test { ); } + // ─── Partial-success batch tests ──────────────────────────────────────────── + + function test_tryMulticall_allSuccess_preservesProposalEventsAndAccounting() public { + vm.warp(block.timestamp + 2); + uint256 firstTimestamp = block.timestamp - 1; + uint256 secondTimestamp = block.timestamp; + _makeRequest(firstTimestamp, 0); + _makeRequest(secondTimestamp, 0); + _setBond(); + + uint256 payment = 5 ether; + uint256 excess = 7 ether; + SignedProposer.Proposal memory firstProposal = _buildProposal(firstTimestamp, 1 ether, payment); + SignedProposer.Proposal memory secondProposal = _buildProposal(secondTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory firstPermit = + _buildPermit(TOTAL_BOND + payment + excess, 0, block.timestamp + 1 hours); + ISignatureTransfer.PermitTransferFrom memory secondPermit = + _buildPermit(TOTAL_BOND, 1, block.timestamp + 1 hours); + _fundAndApproveProposer(TOTAL_BOND * 2 + payment + excess); + uint256 proposerBalanceBefore = currency.balanceOf(proposer); + + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(firstProposal, proposer, firstPermit, "", payment); + calls[1] = _encodeProposalCall(secondProposal, proposer, secondPermit, "", 0); + + vm.expectEmit(true, true, false, true, address(moo)); + emit OptimisticOracleV2Interface.ProposePrice( + requester, + proposer, + IDENTIFIER, + firstTimestamp, + ANCILLARY, + 1 ether, + block.timestamp + LEGACY_DEFAULT_LIVENESS, + address(currency) + ); + vm.expectEmit(true, true, true, true, address(signedProposer)); + emit ProposalExecuted( + proposer, address(moo), requester, IDENTIFIER, firstTimestamp, 1 ether, TOTAL_BOND, payment + ); + vm.expectEmit(true, true, false, true, address(moo)); + emit OptimisticOracleV2Interface.ProposePrice( + requester, + proposer, + IDENTIFIER, + secondTimestamp, + ANCILLARY, + 2 ether, + block.timestamp + LEGACY_DEFAULT_LIVENESS, + address(currency) + ); + vm.expectEmit(true, true, true, true, address(signedProposer)); + emit ProposalExecuted(proposer, address(moo), requester, IDENTIFIER, secondTimestamp, 2 ether, TOTAL_BOND, 0); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertEq(successes.length, 2); + assertTrue(successes[0]); + assertTrue(successes[1]); + assertEq(proposerBalanceBefore - currency.balanceOf(proposer), TOTAL_BOND * 2 + payment); + assertEq(currency.balanceOf(address(signedProposer)), payment); + } + + function test_tryMulticall_mixedFailure_continuesToLaterProposalAndEmitsExactFailure() public { + vm.warp(block.timestamp + 2); + uint256 firstTimestamp = block.timestamp - 1; + uint256 secondTimestamp = block.timestamp; + _makeRequest(firstTimestamp, 0); + _makeRequest(secondTimestamp, 0); + _setBond(); + + SignedProposer.Proposal memory firstProposal = _buildProposal(firstTimestamp, 1 ether); + SignedProposer.Proposal memory failedProposal = _buildProposal(firstTimestamp, 9 ether, 0); + SignedProposer.Proposal memory secondProposal = _buildProposal(secondTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + _fundAndApproveProposer(TOTAL_BOND * 2); + + bytes[] memory calls = new bytes[](3); + calls[0] = _encodeProposalCall(firstProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(failedProposal, proposer, permit, "", 1); + calls[2] = _encodeProposalCall(secondProposal, proposer, permit, "", 0); + bytes memory revertData = abi.encodeWithSelector(SignedProposer.PaymentExceedsMaxPayment.selector); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed( + 1, keccak256(calls[1]), SignedProposer.PaymentExceedsMaxPayment.selector, keccak256(revertData) + ); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(moo.getRequest(requester, IDENTIFIER, firstTimestamp, ANCILLARY).proposedPrice, 1 ether); + assertEq(moo.getRequest(requester, IDENTIFIER, secondTimestamp, ANCILLARY).proposedPrice, 2 ether); + } + + function test_tryMulticall_allFailure_returnsPerCallResultsAndEvents() public { + SignedProposer.Proposal memory proposal = _buildProposal(block.timestamp, 1 ether, 0); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(0, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](9); + bytes memory revertData = abi.encodeWithSelector(SignedProposer.PaymentExceedsMaxPayment.selector); + + for (uint256 i; i < calls.length; ++i) { + calls[i] = _encodeProposalCall(proposal, proposer, permit, "", i + 1); + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed( + i, keccak256(calls[i]), SignedProposer.PaymentExceedsMaxPayment.selector, keccak256(revertData) + ); + } + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + for (uint256 i; i < successes.length; ++i) { + assertFalse(successes[i]); + } + } + + function test_tryMulticall_lateProposalCollision_doesNotBlockLaterProposal() public { + vm.warp(block.timestamp + 2); + uint256 collisionTimestamp = block.timestamp - 1; + uint256 freshTimestamp = block.timestamp; + _makeRequest(collisionTimestamp, 0); + _makeRequest(freshTimestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND * 3); + + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + SignedProposer.Proposal memory collisionProposal = _buildProposal(collisionTimestamp, 1 ether); + SignedProposer.Proposal memory freshProposal = _buildProposal(freshTimestamp, 2 ether); + + vm.prank(relayer); + signedProposer.propose(collisionProposal, proposer, permit, "", 0); + + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(collisionProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(freshProposal, proposer, permit, "", 0); + + vm.prank(relayer); + (bool directSuccess, bytes memory collisionRevertData) = address(signedProposer).call(calls[0]); + assertFalse(directSuccess); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed( + 0, keccak256(calls[0]), _revertSelector(collisionRevertData), keccak256(collisionRevertData) + ); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertFalse(successes[0]); + assertTrue(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, freshTimestamp, ANCILLARY).proposedPrice, 2 ether); + } + + function test_revert_tryMulticall_rejectsSelectorBeforeAnyExecution() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND); + + SignedProposer.Proposal memory proposal = _buildProposal(timestamp, 1 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(proposal, proposer, permit, "", 0); + calls[1] = abi.encodeCall(SignedProposer.withdrawPayments, (IERC20(address(currency)), relayer, 0)); + + vm.expectRevert( + abi.encodeWithSelector( + TryMulticall.TryMulticallInvalidSelector.selector, 1, SignedProposer.withdrawPayments.selector + ) + ); + vm.prank(relayer); + signedProposer.tryMulticall(calls); + + assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposer, address(0)); + assertEq(currency.balanceOf(proposer), TOTAL_BOND); + } + + function test_revert_tryMulticall_rejectsShortCalldata() public { + bytes[] memory calls = new bytes[](1); + calls[0] = hex"123456"; + + vm.expectRevert(abi.encodeWithSelector(TryMulticall.TryMulticallInvalidSelector.selector, 0, bytes4(0))); + vm.prank(relayer); + signedProposer.tryMulticall(calls); + } + + function test_revert_tryMulticall_notDelegatedProposer() public { + bytes[] memory calls = new bytes[](0); + address nobody = makeAddr("nobody"); + + vm.expectRevert( + abi.encodeWithSelector( + IAccessControl.AccessControlUnauthorizedAccount.selector, nobody, DELEGATED_PROPOSER_ROLE + ) + ); + vm.prank(nobody); + signedProposer.tryMulticall(calls); + } + + function test_multicall_remainsAtomic() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND * 2); + uint256 balanceBefore = currency.balanceOf(proposer); + + SignedProposer.Proposal memory proposal = _buildProposal(timestamp, 1 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(proposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(proposal, proposer, permit, "", 0); + + vm.expectRevert(); + vm.prank(relayer); + signedProposer.multicall(calls); + + assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposer, address(0)); + assertEq(currency.balanceOf(proposer), balanceBefore); + } + + function test_tryMulticall_blocksNestedBatchWithoutBlockingOuterProposal() public { + ReentrantTryMulticallRequester callbackRequester = + new ReentrantTryMulticallRequester(moo, signedProposer, IERC20(address(currency))); + requester = address(callbackRequester); + requesterWhitelist.addToWhitelist(requester); + vm.prank(admin); + signedProposer.addDelegatedProposer(requester); + + uint256 timestamp = block.timestamp; + callbackRequester.requestWithProposalCallback(IDENTIFIER, timestamp, ANCILLARY); + _setBond(); + SignedProposer.Proposal memory proposal = _buildProposal(timestamp, 1 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + _fundAndApproveProposer(TOTAL_BOND); + + bytes[] memory calls = new bytes[](1); + calls[0] = _encodeProposalCall(proposal, proposer, permit, "", 0); + callbackRequester.setNestedCalls(calls); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertTrue(successes[0]); + assertTrue(callbackRequester.attemptedNestedBatch()); + assertFalse(callbackRequester.nestedBatchSucceeded()); + assertEq( + callbackRequester.nestedRevertData(), + abi.encodeWithSelector(TryMulticall.TryMulticallReentrantCall.selector) + ); + } + + function test_tryMulticall_gasExhaustingChildCanRevertEntireBatch() public { + (bytes[] memory calls, uint256 validTimestamp) = _gasExhaustingThenValidCalls(); + (bool outerSuccess,) = _tryMulticallWithGas(calls, FULL_BATCH_REVERT_GAS); + + assertFalse(outerSuccess); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposer, address(0)); + } + + function test_tryMulticall_gasExhaustingChildCanStarveLaterChildWithoutRevertingOuterBatch() public { + (bytes[] memory calls, uint256 validTimestamp) = _gasExhaustingThenValidCalls(); + bytes32 emptyRevertDataHash = keccak256(bytes("")); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0), emptyRevertDataHash); + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(1, keccak256(calls[1]), bytes4(0), emptyRevertDataHash); + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, GAS_STARVATION_CONTINUATION_GAS); + + assertTrue(outerSuccess); + assertFalse(successes[0]); + assertFalse(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposer, address(0)); + assertEq(currency.balanceOf(proposer), TOTAL_BOND); + } + + function test_tryMulticall_gasExhaustingChildCanLeaveEnoughGasForLaterChild() public { + (bytes[] memory calls, uint256 validTimestamp) = _gasExhaustingThenValidCalls(); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0), keccak256(bytes(""))); + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, LATER_CHILD_RECOVERY_GAS); + + assertTrue(outerSuccess); + assertFalse(successes[0]); + assertTrue(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposedPrice, 2 ether); + assertEq(currency.balanceOf(proposer), 0); + } + + function test_tryMulticall_emptyRevertAndGasStarvationShareFailureMetadata() public { + uint256 validTimestamp = block.timestamp; + _makeRequest(validTimestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND); + + SignedProposer.Proposal memory emptyRevertProposal = _buildRevertingProposal(false, 0, validTimestamp, 1 ether); + SignedProposer.Proposal memory validProposal = _buildProposal(validTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(emptyRevertProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(validProposal, proposer, permit, "", 0); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0), keccak256(bytes(""))); + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, GAS_STARVATION_CONTINUATION_GAS); + + assertTrue(outerSuccess); + assertFalse(successes[0]); + assertTrue(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposedPrice, 2 ether); + } + + function test_tryMulticall_gasExhaustingLastChildPreservesEarlierSuccess() public { + (bytes[] memory originalCalls, uint256 validTimestamp) = _gasExhaustingThenValidCalls(); + bytes[] memory calls = new bytes[](2); + calls[0] = originalCalls[1]; + calls[1] = originalCalls[0]; + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, LATER_CHILD_RECOVERY_GAS); + + assertTrue(outerSuccess); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposedPrice, 2 ether); + assertEq(currency.balanceOf(proposer), 0); + } + + function test_tryMulticall_outerOutOfGasRollsBackEarlierSuccessfulChild() public { + (bytes[] memory originalCalls, uint256 validTimestamp) = _gasExhaustingThenValidCalls(); + bytes[] memory calls = new bytes[](3); + calls[0] = originalCalls[1]; + calls[1] = originalCalls[0]; + calls[2] = originalCalls[0]; + + (bool outerSuccess,) = _tryMulticallWithGas(calls, FULL_BATCH_REVERT_GAS); + + assertFalse(outerSuccess); + assertEq(moo.getRequest(requester, IDENTIFIER, validTimestamp, ANCILLARY).proposer, address(0)); + assertEq(currency.balanceOf(proposer), TOTAL_BOND); + } + + function test_tryMulticall_gasExhaustingMiddleChildPreservesBothSuccessfulSiblings() public { + vm.warp(block.timestamp + 2); + uint256 firstTimestamp = block.timestamp - 1; + uint256 secondTimestamp = block.timestamp; + _makeRequest(firstTimestamp, 0); + _makeRequest(secondTimestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND * 2); + + SignedProposer.Proposal memory firstProposal = _buildProposal(firstTimestamp, 1 ether); + SignedProposer.Proposal memory gasExhaustingProposal = _buildRevertingProposal(true, 0, firstTimestamp, 9 ether); + SignedProposer.Proposal memory secondProposal = _buildProposal(secondTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](3); + calls[0] = _encodeProposalCall(firstProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(gasExhaustingProposal, proposer, permit, "", 0); + calls[2] = _encodeProposalCall(secondProposal, proposer, permit, "", 0); + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, LATER_CHILD_RECOVERY_GAS); + + assertTrue(outerSuccess); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(moo.getRequest(requester, IDENTIFIER, firstTimestamp, ANCILLARY).proposedPrice, 1 ether); + assertEq(moo.getRequest(requester, IDENTIFIER, secondTimestamp, ANCILLARY).proposedPrice, 2 ether); + assertEq(currency.balanceOf(proposer), 0); + } + + function test_tryMulticall_hashesCompleteLargeRevertData() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND); + + uint256 revertDataSize = 512 * 1024; + RevertingSignedProposerOracle revertingOracle = + new RevertingSignedProposerOracle(IERC20(address(currency)), false, revertDataSize); + SignedProposer.Proposal memory failedProposal = SignedProposer.Proposal({ + oracle: address(revertingOracle), + requester: requester, + identifier: IDENTIFIER, + timestamp: timestamp, + ancillaryData: ANCILLARY, + proposedPrice: 1 ether, + maxPayment: 0 + }); + SignedProposer.Proposal memory validProposal = _buildProposal(timestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(failedProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(validProposal, proposer, permit, "", 0); + + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0), keccak256(new bytes(revertDataSize))); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertFalse(successes[0]); + assertTrue(successes[1]); + } + // ─── Delegated proposer role tests ─────────────────────────────────────────── function test_revert_propose_notDelegatedProposer() public { @@ -1003,3 +1495,75 @@ contract ReentrantSignedProposerRequester { } } } + +contract ReentrantTryMulticallRequester { + ManagedOptimisticOracleV2 internal immutable oracle; + SignedProposer internal immutable signedProposer; + IERC20 internal immutable currency; + + bytes[] internal nestedCalls; + + bool public attemptedNestedBatch; + bool public nestedBatchSucceeded; + bytes public nestedRevertData; + + constructor(ManagedOptimisticOracleV2 _oracle, SignedProposer _signedProposer, IERC20 _currency) { + oracle = _oracle; + signedProposer = _signedProposer; + currency = _currency; + } + + function requestWithProposalCallback(bytes32 identifier, uint256 timestamp, bytes memory ancillaryData) external { + oracle.requestPrice(identifier, timestamp, ancillaryData, currency, 0); + oracle.setCallbacks(identifier, timestamp, ancillaryData, true, false, false); + } + + function setNestedCalls(bytes[] calldata calls) external { + delete nestedCalls; + for (uint256 i; i < calls.length; ++i) { + nestedCalls.push(calls[i]); + } + } + + function priceProposed(bytes32, uint256, bytes memory) external { + require(msg.sender == address(oracle), "ReentrantRequester: unauthorized"); + + attemptedNestedBatch = true; + try signedProposer.tryMulticall(nestedCalls) returns (bool[] memory) { + nestedBatchSucceeded = true; + } catch (bytes memory reason) { + nestedRevertData = reason; + } + } +} + +contract RevertingSignedProposerOracle { + IERC20 internal immutable currency; + bool internal immutable exhaustGas; + uint256 internal immutable revertDataSize; + + constructor(IERC20 _currency, bool _exhaustGas, uint256 _revertDataSize) { + currency = _currency; + exhaustGas = _exhaustGas; + revertDataSize = _revertDataSize; + } + + function getRequest(address, bytes32, uint256, bytes memory) + external + view + returns (OptimisticOracleV2Interface.Request memory request) + { + if (exhaustGas) { + assembly { + for {} 1 {} {} + } + } + + bytes memory revertData = new bytes(revertDataSize); + assembly ("memory-safe") { + revert(add(revertData, 0x20), mload(revertData)) + } + + request.currency = currency; + } +} diff --git a/test/SignedProposerPermit2.t.sol b/test/SignedProposerPermit2.t.sol index 33b33f4..b3831c7 100644 --- a/test/SignedProposerPermit2.t.sol +++ b/test/SignedProposerPermit2.t.sol @@ -8,6 +8,7 @@ import {IEIP712} from "permit2/src/interfaces/IEIP712.sol"; import {SignatureVerification} from "permit2/src/libraries/SignatureVerification.sol"; import {SignedProposer} from "src/optimistic-oracle-v2/implementation/SignedProposer.sol"; +import {TryMulticall} from "src/common/implementation/TryMulticall.sol"; import {ManagedOptimisticOracleV2} from "src/optimistic-oracle-v2/implementation/ManagedOptimisticOracleV2.sol"; import {OptimisticOracleV2Interface} from "src/optimistic-oracle-v2/interfaces/OptimisticOracleV2Interface.sol"; import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; @@ -20,12 +21,18 @@ import {MockStore} from "./mocks/MockStore.sol"; import {MockIdentifierWhitelist} from "./mocks/MockIdentifierWhitelist.sol"; import {MockFinder} from "./mocks/MockFinder.sol"; import {MockOracle} from "./mocks/MockOracle.sol"; +import {MaliciousSignedProposerOracle} from "./mocks/MaliciousSignedProposerOracle.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; contract SignedProposerPermit2Test is Test, DeployPermit2 { + // Polygon block 81,683,818, shared with SignedProposerTryMulticallForkTest. + uint256 internal constant POLYGON_BLOCK_GAS_LIMIT = 53_902_641; + // Bor rejects transactions larger than 128 KiB before EVM execution. + uint256 internal constant BOR_MAX_TRANSACTION_BYTES = 128 * 1024; + uint256 internal constant POLYGON_MAX_PROPOSALS_WITH_MAX_ANCILLARY_DATA = 14; bytes32 internal constant IDENTIFIER = keccak256("PRICE_ID"); bytes internal constant ANCILLARY = bytes(":memo: test"); uint256 internal constant LEGACY_DEFAULT_LIVENESS = 2 hours; @@ -150,16 +157,27 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { } function _makeRequest(uint256 timestamp, uint256 reward) internal returns (uint256 totalBond) { + return _makeRequest(timestamp, reward, ANCILLARY); + } + + function _makeRequest(uint256 timestamp, uint256 reward, bytes memory ancillaryData) + internal + returns (uint256 totalBond) + { currency.mint(requester, reward); vm.startPrank(requester); currency.approve(address(moo), type(uint256).max); - totalBond = moo.requestPrice(IDENTIFIER, timestamp, ANCILLARY, IERC20(address(currency)), reward); + totalBond = moo.requestPrice(IDENTIFIER, timestamp, ancillaryData, IERC20(address(currency)), reward); vm.stopPrank(); } function _setBond() internal { + _setBond(ANCILLARY); + } + + function _setBond(bytes memory ancillaryData) internal { vm.prank(requestManager); - moo.requestManagerSetBond(requester, IDENTIFIER, ANCILLARY, IERC20(address(currency)), BOND); + moo.requestManagerSetBond(requester, IDENTIFIER, ancillaryData, IERC20(address(currency)), BOND); } function _fundAndApproveProposer(uint256 amount) internal { @@ -176,18 +194,102 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { internal view returns (SignedProposer.Proposal memory) + { + return _buildProposal(timestamp, price, maxPayment, ANCILLARY); + } + + function _buildProposal(uint256 timestamp, int256 price, uint256 maxPayment, bytes memory ancillaryData) + internal + view + returns (SignedProposer.Proposal memory) { return SignedProposer.Proposal({ oracle: address(moo), requester: requester, identifier: IDENTIFIER, timestamp: timestamp, - ancillaryData: ANCILLARY, + ancillaryData: ancillaryData, proposedPrice: price, maxPayment: maxPayment }); } + function _maximallyPricedAncillaryData() internal view returns (bytes memory ancillaryData) { + ancillaryData = new bytes(moo.OO_ANCILLARY_DATA_LIMIT()); + for (uint256 i; i < ancillaryData.length; ++i) { + ancillaryData[i] = 0xff; + } + } + + function _transactionIntrinsicGas(bytes memory transactionData) internal pure returns (uint256 intrinsicGas) { + intrinsicGas = 21_000; + for (uint256 i; i < transactionData.length; ++i) { + intrinsicGas += transactionData[i] == 0 ? 4 : 16; + } + } + + function _executeWithinPolygonBlock(bytes[] memory calls) + internal + returns (bool transactionSucceeded, bool[] memory successes) + { + bytes memory transactionData = abi.encodeCall(TryMulticall.tryMulticall, (calls)); + uint256 intrinsicGas = _transactionIntrinsicGas(transactionData); + if (intrinsicGas >= POLYGON_BLOCK_GAS_LIMIT) return (false, successes); + + vm.prank(relayer); + bytes memory returnData; + (transactionSucceeded, returnData) = + address(signedProposer).call{gas: POLYGON_BLOCK_GAS_LIMIT - intrinsicGas}(transactionData); + if (transactionSucceeded) successes = abi.decode(returnData, (bool[])); + } + + function _prefix(bytes[] memory calls, uint256 length) internal pure returns (bytes[] memory selectedCalls) { + selectedCalls = new bytes[](length); + for (uint256 i; i < length; ++i) { + selectedCalls[i] = calls[i]; + } + } + + function _allSucceeded(bool transactionSucceeded, bool[] memory successes, uint256 expectedLength) + internal + pure + returns (bool) + { + if (!transactionSucceeded || successes.length != expectedLength) return false; + for (uint256 i; i < successes.length; ++i) { + if (!successes[i]) return false; + } + return true; + } + + function _prepareMaxAncillaryCalls(uint256 count, bytes memory ancillaryData) + internal + returns (bytes[] memory calls) + { + vm.warp(block.timestamp + count + 1); + calls = new bytes[](count); + _fundAndApproveProposer(TOTAL_BOND * count); + + for (uint256 i; i < count; ++i) { + uint256 timestamp = block.timestamp - i; + _makeRequest(timestamp, 0, ancillaryData); + _setBond(ancillaryData); + + SignedProposer.Proposal memory proposal = _buildProposal(timestamp, int256(i + 1), 0, ancillaryData); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, i, block.timestamp + 1 hours); + calls[i] = abi.encodeCall( + SignedProposer.propose, + ( + proposal, + proposer, + permit, + _getPermitWitnessTransferSignature(permit, proposal, address(signedProposer)), + 0 + ) + ); + } + } + function _buildPermit(uint256 amount, uint256 nonce, uint256 deadline) internal view @@ -219,6 +321,15 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { ISignatureTransfer.PermitTransferFrom memory permit, SignedProposer.Proposal memory proposal, address spender + ) internal view returns (bytes memory) { + return _getPermitWitnessTransferSignatureFor(proposerKey, permit, proposal, spender); + } + + function _getPermitWitnessTransferSignatureFor( + uint256 ownerKey, + ISignatureTransfer.PermitTransferFrom memory permit, + SignedProposer.Proposal memory proposal, + address spender ) internal view returns (bytes memory) { bytes32 tokenPermissionsHash = keccak256(abi.encode(TOKEN_PERMISSIONS_TYPEHASH, permit.permitted)); bytes32 witnessTypeHash = keccak256( @@ -235,7 +346,7 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { ) ); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", IEIP712(permit2Address).DOMAIN_SEPARATOR(), structHash)); - (uint8 v, bytes32 r, bytes32 s) = vm.sign(proposerKey, digest); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(ownerKey, digest); return abi.encodePacked(r, s, v); } @@ -309,4 +420,200 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { vm.prank(relayer); signedProposer.propose(submittedProposal, proposer, permit, signature, 0); } + + function test_tryMulticall_realPermit2DifferentProposersAndNonces() public { + vm.warp(block.timestamp + 2); + uint256 firstTimestamp = block.timestamp - 1; + uint256 secondTimestamp = block.timestamp; + _makeRequest(firstTimestamp, 0); + _makeRequest(secondTimestamp, 0); + _setBond(); + + uint256 secondProposerKey = 0xB0B; + address secondProposer = vm.addr(secondProposerKey); + defaultProposerWhitelist.addToWhitelist(secondProposer); + + SignedProposer.Proposal memory firstProposal = _buildProposal(firstTimestamp, 1 ether); + SignedProposer.Proposal memory secondProposal = _buildProposal(secondTimestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory firstPermit = + _buildPermit(TOTAL_BOND, 11, block.timestamp + 1 hours); + ISignatureTransfer.PermitTransferFrom memory secondPermit = + _buildPermit(TOTAL_BOND, 777, block.timestamp + 1 hours); + + currency.mint(proposer, TOTAL_BOND); + vm.prank(proposer); + currency.approve(permit2Address, TOTAL_BOND); + currency.mint(secondProposer, TOTAL_BOND); + vm.prank(secondProposer); + currency.approve(permit2Address, TOTAL_BOND); + + bytes[] memory calls = new bytes[](2); + calls[0] = abi.encodeCall( + SignedProposer.propose, + ( + firstProposal, + proposer, + firstPermit, + _getPermitWitnessTransferSignatureFor(proposerKey, firstPermit, firstProposal, address(signedProposer)), + 0 + ) + ); + calls[1] = abi.encodeCall( + SignedProposer.propose, + ( + secondProposal, + secondProposer, + secondPermit, + _getPermitWitnessTransferSignatureFor( + secondProposerKey, secondPermit, secondProposal, address(signedProposer) + ), + 0 + ) + ); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertTrue(successes[0]); + assertTrue(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, firstTimestamp, ANCILLARY).proposer, proposer); + assertEq(moo.getRequest(requester, IDENTIFIER, secondTimestamp, ANCILLARY).proposer, secondProposer); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1 << 11); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(secondProposer, 3), 1 << 9); + } + + function test_tryMulticall_failedProposalRollsBackPermit2NonceAndTokenMovement() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + + SignedProposer.Proposal memory proposal = _buildProposal(timestamp, 1 ether); + ISignatureTransfer.PermitTransferFrom memory initialPermit = + _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + ISignatureTransfer.PermitTransferFrom memory failedPermit = + _buildPermit(TOTAL_BOND, 19, block.timestamp + 1 hours); + _fundAndApproveProposer(TOTAL_BOND * 2); + bytes memory initialSignature = + _getPermitWitnessTransferSignature(initialPermit, proposal, address(signedProposer)); + + vm.prank(relayer); + signedProposer.propose(proposal, proposer, initialPermit, initialSignature, 0); + + bytes[] memory calls = new bytes[](1); + calls[0] = abi.encodeCall( + SignedProposer.propose, + ( + proposal, + proposer, + failedPermit, + _getPermitWitnessTransferSignature(failedPermit, proposal, address(signedProposer)), + 0 + ) + ); + uint256 proposerBalanceBefore = currency.balanceOf(proposer); + uint256 signedProposerBalanceBefore = currency.balanceOf(address(signedProposer)); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertFalse(successes[0]); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1); + assertEq(currency.balanceOf(proposer), proposerBalanceBefore); + assertEq(currency.balanceOf(address(signedProposer)), signedProposerBalanceBefore); + } + + function test_tryMulticall_gasExhaustionAfterPermit2TransferRollsBackFailedChildAndContinues() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + + MaliciousSignedProposerOracle gasExhaustingOracle = + new MaliciousSignedProposerOracle(IERC20(address(currency)), address(signedProposer), address(this)); + gasExhaustingOracle.setBondAmount(TOTAL_BOND); + gasExhaustingOracle.setWhitelisted(proposer, true); + gasExhaustingOracle.setExhaustGasAfterTransfer(true); + + SignedProposer.Proposal memory gasExhaustingProposal = SignedProposer.Proposal({ + oracle: address(gasExhaustingOracle), + requester: requester, + identifier: IDENTIFIER, + timestamp: timestamp, + ancillaryData: ANCILLARY, + proposedPrice: 1 ether, + maxPayment: 0 + }); + SignedProposer.Proposal memory validProposal = _buildProposal(timestamp, 2 ether); + ISignatureTransfer.PermitTransferFrom memory gasExhaustingPermit = + _buildPermit(TOTAL_BOND, 19, block.timestamp + 1 hours); + ISignatureTransfer.PermitTransferFrom memory validPermit = + _buildPermit(TOTAL_BOND, 20, block.timestamp + 1 hours); + _fundAndApproveProposer(TOTAL_BOND * 2); + + bytes[] memory calls = new bytes[](2); + calls[0] = abi.encodeCall( + SignedProposer.propose, + ( + gasExhaustingProposal, + proposer, + gasExhaustingPermit, + _getPermitWitnessTransferSignature(gasExhaustingPermit, gasExhaustingProposal, address(signedProposer)), + 0 + ) + ); + calls[1] = abi.encodeCall( + SignedProposer.propose, + ( + validProposal, + proposer, + validPermit, + _getPermitWitnessTransferSignature(validPermit, validProposal, address(signedProposer)), + 0 + ) + ); + + (bool transactionSucceeded, bool[] memory successes) = _executeWithinPolygonBlock(calls); + + assertTrue(transactionSucceeded); + assertFalse(successes[0]); + assertTrue(successes[1]); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1 << 20); + assertEq(currency.balanceOf(proposer), TOTAL_BOND); + assertEq(currency.balanceOf(address(signedProposer)), 0); + assertEq(currency.balanceOf(address(gasExhaustingOracle)), 0); + assertEq(currency.allowance(address(signedProposer), address(gasExhaustingOracle)), 0); + assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposer, proposer); + assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposedPrice, 2 ether); + } + + function test_tryMulticall_maxAncillaryData_polygonBlockCapacity() public { + bytes memory ancillaryData = _maximallyPricedAncillaryData(); + assertEq(ancillaryData.length, moo.OO_ANCILLARY_DATA_LIMIT()); + + uint256 firstFailingBatch = POLYGON_MAX_PROPOSALS_WITH_MAX_ANCILLARY_DATA + 1; + bytes[] memory allCalls = _prepareMaxAncillaryCalls(firstFailingBatch, ancillaryData); + bytes[] memory boundaryBatch = _prefix(allCalls, POLYGON_MAX_PROPOSALS_WITH_MAX_ANCILLARY_DATA); + bytes memory boundaryTransactionData = abi.encodeCall(TryMulticall.tryMulticall, (boundaryBatch)); + bytes memory overBoundaryTransactionData = abi.encodeCall(TryMulticall.tryMulticall, (allCalls)); + + // The successful boundary leaves more than 6 KiB for the signed transaction envelope. At the next proposal, + // calldata alone exceeds Bor's complete RLP-encoded transaction limit and is rejected before EVM execution. + assertLt(boundaryTransactionData.length, BOR_MAX_TRANSACTION_BYTES); + assertGt(overBoundaryTransactionData.length, BOR_MAX_TRANSACTION_BYTES); + + (bool boundaryTransactionSucceeded, bool[] memory boundarySuccesses) = _executeWithinPolygonBlock(boundaryBatch); + assertTrue( + _allSucceeded( + boundaryTransactionSucceeded, boundarySuccesses, POLYGON_MAX_PROPOSALS_WITH_MAX_ANCILLARY_DATA + ) + ); + + emit log_named_uint("max ancillary bytes", ancillaryData.length); + emit log_named_uint("encoded proposal bytes", allCalls[0].length); + emit log_named_uint("Bor max transaction bytes", BOR_MAX_TRANSACTION_BYTES); + emit log_named_uint("largest accepted batch calldata bytes", boundaryTransactionData.length); + emit log_named_uint("first rejected batch calldata bytes", overBoundaryTransactionData.length); + emit log_named_uint("Polygon block gas limit", POLYGON_BLOCK_GAS_LIMIT); + emit log_named_uint("largest successful proposal batch", POLYGON_MAX_PROPOSALS_WITH_MAX_ANCILLARY_DATA); + emit log_named_uint("first failing proposal batch", firstFailingBatch); + } } diff --git a/test/SignedProposerTryMulticall.Fork.t.sol b/test/SignedProposerTryMulticall.Fork.t.sol new file mode 100644 index 0000000..6ef3289 --- /dev/null +++ b/test/SignedProposerTryMulticall.Fork.t.sol @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: AGPL-3.0-only +pragma solidity ^0.8.27; + +import {Test} from "forge-std/Test.sol"; + +import {IEIP712} from "permit2/src/interfaces/IEIP712.sol"; +import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; +import {SignatureVerification} from "permit2/src/libraries/SignatureVerification.sol"; + +import {SignedProposer} from "src/optimistic-oracle-v2/implementation/SignedProposer.sol"; +import {MaliciousSignedProposerOracle} from "./mocks/MaliciousSignedProposerOracle.sol"; + +import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol"; + +/** + * @notice Polygon fork coverage for partial-success batching against canonical Permit2. + * @dev Uses a pinned block so Permit2 bytecode and EIP-712 domain behavior are deterministic. + */ +contract SignedProposerTryMulticallForkTest is Test { + address internal constant POLYGON_PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3; + uint256 internal constant FORK_BLOCK = 81_683_818; + uint256 internal constant BOND = 1 ether; + + bytes32 internal constant IDENTIFIER = keccak256("FORK_PRICE_ID"); + bytes32 internal constant PROPOSAL_TYPEHASH = keccak256( + "Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" + ); + bytes32 internal constant TOKEN_PERMISSIONS_TYPEHASH = keccak256("TokenPermissions(address token,uint256 amount)"); + string internal constant PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB = + "PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,"; + + event ProposalCallFailed( + uint256 indexed index, bytes32 indexed callHash, bytes4 errorSelector, bytes32 revertDataHash + ); + + SignedProposer internal signedProposer; + MaliciousSignedProposerOracle internal oracle; + ERC20Mock internal currency; + + address internal relayer; + uint256 internal firstProposerKey; + uint256 internal secondProposerKey; + address internal firstProposer; + address internal secondProposer; + + function setUp() public { + vm.createSelectFork(vm.envString("NODE_URL_137"), FORK_BLOCK); + assertGt(POLYGON_PERMIT2.code.length, 0, "canonical Polygon Permit2 missing"); + + address admin = makeAddr("admin"); + relayer = makeAddr("relayer"); + firstProposerKey = _findEoaKey(0xA11CE); + secondProposerKey = _findEoaKey(0xB0B); + firstProposer = vm.addr(firstProposerKey); + secondProposer = vm.addr(secondProposerKey); + assertEq(firstProposer.code.length, 0, "first proposer must be an EOA"); + assertEq(secondProposer.code.length, 0, "second proposer must be an EOA"); + assertNotEq(firstProposer, secondProposer, "proposers must differ"); + + currency = new ERC20Mock(); + signedProposer = new SignedProposer(ISignatureTransfer(POLYGON_PERMIT2), admin); + oracle = new MaliciousSignedProposerOracle(currency, address(signedProposer), address(0)); + oracle.setBondAmount(BOND); + + vm.prank(admin); + signedProposer.addDelegatedProposer(relayer); + + currency.mint(firstProposer, BOND); + currency.mint(secondProposer, BOND); + vm.prank(firstProposer); + currency.approve(POLYGON_PERMIT2, BOND); + vm.prank(secondProposer); + currency.approve(POLYGON_PERMIT2, BOND); + } + + function testFork_tryMulticall_mixedPermit2SignersAndNonces() public { + SignedProposer.Proposal memory firstProposal = _proposal(block.timestamp, 1 ether); + SignedProposer.Proposal memory failedProposal = _proposal(block.timestamp + 1, 2 ether); + SignedProposer.Proposal memory secondProposal = _proposal(block.timestamp + 2, 3 ether); + ISignatureTransfer.PermitTransferFrom memory firstPermit = _permit(7); + ISignatureTransfer.PermitTransferFrom memory failedPermit = _permit(999); + ISignatureTransfer.PermitTransferFrom memory secondPermit = _permit(513); + + bytes[] memory calls = new bytes[](3); + calls[0] = + _call(firstProposal, firstProposer, firstPermit, _signature(firstProposerKey, firstPermit, firstProposal)); + calls[1] = _call( + failedProposal, secondProposer, failedPermit, _signature(firstProposerKey, failedPermit, failedProposal) + ); + calls[2] = _call( + secondProposal, secondProposer, secondPermit, _signature(secondProposerKey, secondPermit, secondProposal) + ); + + bytes memory revertData = abi.encodeWithSelector(SignatureVerification.InvalidSigner.selector); + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed( + 1, keccak256(calls[1]), SignatureVerification.InvalidSigner.selector, keccak256(revertData) + ); + + vm.prank(relayer); + bool[] memory successes = signedProposer.tryMulticall(calls); + + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(currency.balanceOf(address(oracle)), BOND * 2); + assertEq(ISignatureTransfer(POLYGON_PERMIT2).nonceBitmap(firstProposer, 0), 1 << 7); + assertEq(ISignatureTransfer(POLYGON_PERMIT2).nonceBitmap(secondProposer, 2), 1 << 1); + assertEq(ISignatureTransfer(POLYGON_PERMIT2).nonceBitmap(secondProposer, 3), 0); + } + + function _proposal(uint256 timestamp, int256 price) internal view returns (SignedProposer.Proposal memory) { + return SignedProposer.Proposal({ + oracle: address(oracle), + requester: address(this), + identifier: IDENTIFIER, + timestamp: timestamp, + ancillaryData: bytes(":fork: polygon"), + proposedPrice: price, + maxPayment: 0 + }); + } + + function _permit(uint256 nonce) internal view returns (ISignatureTransfer.PermitTransferFrom memory) { + return ISignatureTransfer.PermitTransferFrom({ + permitted: ISignatureTransfer.TokenPermissions({token: address(currency), amount: BOND}), + nonce: nonce, + deadline: block.timestamp + 1 hours + }); + } + + function _findEoaKey(uint256 candidate) internal returns (uint256) { + while (vm.addr(candidate).code.length != 0) ++candidate; + return candidate; + } + + function _call( + SignedProposer.Proposal memory proposal, + address proposer, + ISignatureTransfer.PermitTransferFrom memory permit, + bytes memory signature + ) internal pure returns (bytes memory) { + return abi.encodeCall(SignedProposer.propose, (proposal, proposer, permit, signature, 0)); + } + + function _signature( + uint256 signerKey, + ISignatureTransfer.PermitTransferFrom memory permit, + SignedProposer.Proposal memory proposal + ) internal view returns (bytes memory) { + bytes32 tokenPermissionsHash = keccak256(abi.encode(TOKEN_PERMISSIONS_TYPEHASH, permit.permitted)); + bytes32 witnessTypeHash = keccak256( + abi.encodePacked(PERMIT_TRANSFER_FROM_WITNESS_TYPEHASH_STUB, signedProposer.WITNESS_TYPE_STRING()) + ); + bytes32 witness = keccak256( + abi.encode( + PROPOSAL_TYPEHASH, + proposal.oracle, + proposal.requester, + proposal.identifier, + proposal.timestamp, + keccak256(proposal.ancillaryData), + proposal.proposedPrice, + proposal.maxPayment + ) + ); + bytes32 structHash = keccak256( + abi.encode( + witnessTypeHash, tokenPermissionsHash, address(signedProposer), permit.nonce, permit.deadline, witness + ) + ); + bytes32 digest = + keccak256(abi.encodePacked("\x19\x01", IEIP712(POLYGON_PERMIT2).DOMAIN_SEPARATOR(), structHash)); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerKey, digest); + return abi.encodePacked(r, s, v); + } +} diff --git a/test/mocks/MaliciousSignedProposerOracle.sol b/test/mocks/MaliciousSignedProposerOracle.sol index de9cfac..4e58df4 100644 --- a/test/mocks/MaliciousSignedProposerOracle.sol +++ b/test/mocks/MaliciousSignedProposerOracle.sol @@ -63,6 +63,7 @@ contract MaliciousSignedProposerOracle is IMaliciousSignedProposerOracle { address public immutable attacker; MaliciousSignedProposerWhitelist public immutable whitelist; uint256 public bondAmount; + bool public exhaustGasAfterTransfer; constructor(IERC20 _token, address _target, address _attacker) { token = _token; @@ -75,6 +76,10 @@ contract MaliciousSignedProposerOracle is IMaliciousSignedProposerOracle { bondAmount = newBondAmount; } + function setExhaustGasAfterTransfer(bool enabled) external { + exhaustGasAfterTransfer = enabled; + } + function setDrainOnAdd(bool enabled) external { whitelist.setDrainOnAdd(enabled); } @@ -109,6 +114,11 @@ contract MaliciousSignedProposerOracle is IMaliciousSignedProposerOracle { function proposePriceFor(address, address, bytes32, uint256, bytes memory, int256) external returns (uint256) { if (bondAmount > 0) token.transferFrom(msg.sender, address(this), bondAmount); + if (exhaustGasAfterTransfer) { + assembly { + for {} 1 {} {} + } + } return bondAmount; } From c6802e1d3971351e81617696569dec7d3df66537 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 21 Sep 2026 19:45:40 +0100 Subject: [PATCH 2/6] docs: explain batching permissions (L-04) --- script/README.md | 9 +++++++-- .../implementation/SignedProposer.sol | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/script/README.md b/script/README.md index ca5c3e3..ca95486 100644 --- a/script/README.md +++ b/script/README.md @@ -362,8 +362,13 @@ the authoritative success evidence. A `false` result and `ProposalCallFailed` me execution attempt did not complete successfully; they do not prove the proposal itself is invalid. In particular, empty failure metadata is ambiguous between an empty revert and out-of-gas. -OpenZeppelin `multicall(bytes[])` remains available and atomic for compatibility. `tryMulticall` -does not change worker behavior; worker integration must be performed separately. +OpenZeppelin `multicall(bytes[])` remains available and atomic for compatibility. It deliberately accepts any caller +and selector: self-delegatecall preserves the original caller, and each called function enforces its own permissions. +It has no batch-level reentrancy guard; individual functions must apply any required protection. Future externally +reachable functions must retain their own authorization because `multicall` does not impose the delegated-proposer, +`propose`-only, or nesting restrictions of `tryMulticall`. + +`tryMulticall` does not change worker behavior; worker integration must be performed separately. ### Verification diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 7920288..ff8a518 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -34,6 +34,12 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * The contract is permissioned: * - `DELEGATED_PROPOSER_ROLE` — may call `propose` and `tryMulticall`. * - `WHITELIST_ADMIN_ROLE` — may directly add/remove entries on whitelists owned by this contract. + * + * @dev Inherited `multicall` deliberately accepts any caller and selector and executes atomically. Self-delegatecall + * preserves `msg.sender`, so every externally reachable function must enforce its own authorization, including functions + * added in future versions. The batching entry point does not provide a reentrancy guard; functions that need one must + * apply their own. `tryMulticall` instead restricts the caller to delegated proposers, accepts only `propose`, and rejects + * nested partial-success batches. These restrictions do not apply to the atomic `multicall` entry point. */ contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMulticall { using SafeERC20 for IERC20; From 3e777f6129bca195fb21590448fb720d5399866e Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 21 Sep 2026 19:45:45 +0100 Subject: [PATCH 3/6] docs: add relay security contact (N-02) --- src/common/implementation/TryMulticall.sol | 1 + src/optimistic-oracle-v2/implementation/SignedProposer.sol | 1 + 2 files changed, 2 insertions(+) diff --git a/src/common/implementation/TryMulticall.sol b/src/common/implementation/TryMulticall.sol index f7cd4eb..b093db3 100644 --- a/src/common/implementation/TryMulticall.sol +++ b/src/common/implementation/TryMulticall.sol @@ -4,6 +4,7 @@ pragma solidity ^0.8.27; /** * @title TryMulticall * @notice Executes allowed self-delegatecalls without reverting successful siblings. + * @custom:security-contact bugs@umaproject.org */ abstract contract TryMulticall { bool private _tryMulticallEntered; diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index ff8a518..7721b5f 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -15,6 +15,7 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; /** * @title SignedProposer + * @custom:security-contact bugs@umaproject.org * @notice Allows proposers to sign Permit2 witness proposals off-chain and have them submitted by * a delegated relayer. The proposal parameters are embedded as the Permit2 witness so a single * signature authorises both the token transfer and the specific proposal. From 6b238a755f854936f34afca1be53f0f4d0d8e230 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 21 Sep 2026 19:45:50 +0100 Subject: [PATCH 4/6] fix: namespace TryMulticall reentrancy storage (L-02) --- src/common/implementation/TryMulticall.sol | 22 ++++++++++++++++++---- test/SignedProposer.t.sol | 13 +++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/common/implementation/TryMulticall.sol b/src/common/implementation/TryMulticall.sol index b093db3..d39f8b7 100644 --- a/src/common/implementation/TryMulticall.sol +++ b/src/common/implementation/TryMulticall.sol @@ -7,7 +7,14 @@ pragma solidity ^0.8.27; * @custom:security-contact bugs@umaproject.org */ abstract contract TryMulticall { - bool private _tryMulticallEntered; + /// @custom:storage-location erc7201:uma.storage.TryMulticall + struct TryMulticallStorage { + bool entered; + } + + // keccak256(abi.encode(uint256(keccak256("uma.storage.TryMulticall")) - 1)) & ~bytes32(uint256(0xff)) + bytes32 private constant TRY_MULTICALL_STORAGE_LOCATION = + 0x0dd1bd2d495db0d62878fd399d4ab6dc237ff1584371e8862b3e045d79dcd000; /// @notice Emitted when a child execution attempt returns unsuccessfully. /// @dev Empty failure metadata can mean either an empty revert or an out-of-gas child. This event does not prove @@ -29,7 +36,8 @@ abstract contract TryMulticall { */ function tryMulticall(bytes[] calldata calls) external returns (bool[] memory successes) { _checkTryMulticallCaller(); - if (_tryMulticallEntered) revert TryMulticallReentrantCall(); + TryMulticallStorage storage $ = _getTryMulticallStorage(); + if ($.entered) revert TryMulticallReentrantCall(); uint256 callsLength = calls.length; bytes4 allowedSelector = _tryMulticallSelector(); @@ -40,7 +48,7 @@ abstract contract TryMulticall { } successes = new bool[](callsLength); - _tryMulticallEntered = true; + $.entered = true; for (uint256 i; i < callsLength; ++i) { bytes calldata callData = calls[i]; (bool success, bytes memory revertData) = address(this).delegatecall(callData); @@ -51,7 +59,13 @@ abstract contract TryMulticall { emit ProposalCallFailed(i, keccak256(callData), errorSelector, keccak256(revertData)); } } - _tryMulticallEntered = false; + $.entered = false; + } + + function _getTryMulticallStorage() private pure returns (TryMulticallStorage storage $) { + assembly { + $.slot := TRY_MULTICALL_STORAGE_LOCATION + } } function _checkTryMulticallCaller() internal view virtual; diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index 570ccf7..12a9e6f 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -320,6 +320,19 @@ contract SignedProposerTest is Test { if (outerSuccess) successes = abi.decode(returnData, (bool[])); } + function test_tryMulticall_usesDerivedStorageNamespace() public { + bytes32 location = + keccak256(abi.encode(uint256(keccak256("uma.storage.TryMulticall")) - 1)) & ~bytes32(uint256(0xff)); + vm.store(address(signedProposer), location, bytes32(uint256(1))); + vm.expectRevert(TryMulticall.TryMulticallReentrantCall.selector); + vm.prank(relayer); + signedProposer.tryMulticall(new bytes[](0)); + + vm.store(address(signedProposer), location, bytes32(0)); + vm.prank(relayer); + assertEq(signedProposer.tryMulticall(new bytes[](0)).length, 0); + } + // ─── Propose tests ────────────────────────────────────────────────────────── function test_propose() public { From e40ccc7f95a3c4bf5de02acf260904e22bd82037 Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 21 Sep 2026 19:45:55 +0100 Subject: [PATCH 5/6] fix: bound batch failure revert data (N-01) --- script/README.md | 5 +-- src/common/implementation/TryMulticall.sol | 27 ++++++++++---- test/SignedProposer.t.sol | 41 ++++++++++++++++++++-- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/script/README.md b/script/README.md index ca95486..1950621 100644 --- a/script/README.md +++ b/script/README.md @@ -355,8 +355,9 @@ event ProposalCallFailed( ``` `callHash` is `keccak256(calls[index])`, `errorSelector` is the first four revert-data bytes (or -zero when unavailable), and `revertDataHash` hashes the complete revert data. Full proposal -calldata, signatures, and revert data are never logged. Successful children continue to emit the +zero when unavailable), and `revertDataHash` hashes at most the first 256 revert-data bytes. The +batch copies only that bounded prefix before hashing. Full proposal calldata, signatures, and +revert data are never logged. Successful children continue to emit the existing `ProposalExecuted` and oracle `ProposePrice` events. Consumers should use those events as the authoritative success evidence. A `false` result and `ProposalCallFailed` mean only that the execution attempt did not complete successfully; they do not prove the proposal itself is invalid. diff --git a/src/common/implementation/TryMulticall.sol b/src/common/implementation/TryMulticall.sol index d39f8b7..af6d15e 100644 --- a/src/common/implementation/TryMulticall.sol +++ b/src/common/implementation/TryMulticall.sol @@ -19,6 +19,7 @@ abstract contract TryMulticall { /// @notice Emitted when a child execution attempt returns unsuccessfully. /// @dev Empty failure metadata can mean either an empty revert or an out-of-gas child. This event does not prove /// the submitted operation itself is invalid; callers may retry it with a different gas allocation. + /// `revertDataHash` hashes at most the first 256 bytes of revert data; larger payloads are truncated before hashing. event ProposalCallFailed( uint256 indexed index, bytes32 indexed callHash, bytes4 errorSelector, bytes32 revertDataHash ); @@ -26,10 +27,12 @@ abstract contract TryMulticall { error TryMulticallReentrantCall(); error TryMulticallInvalidSelector(uint256 index, bytes4 selector); + uint256 private constant MAX_REVERT_DATA_SIZE = 256; + /** * @notice Executes allowed calls independently and returns their execution-attempt success values. - * @dev Self-delegatecall preserves the original caller. Ordinary failures emit only bounded metadata. There is no - * child gas or revert-data cap. Under EIP-150, an out-of-gas child can return `false` while leaving the outer call + * @dev Self-delegatecall preserves the original caller. Failed calls copy and hash at most 256 bytes of revert + * data. There is no child gas cap. Under EIP-150, an out-of-gas child can return `false` while leaving the outer call * enough gas to continue, but later children may receive too little gas and also return `false`. If the remaining * outer gas cannot finish the loop or encode the result, the full batch reverts. A `false` value therefore means * only that the corresponding execution attempt failed; it does not prove the submitted operation is invalid. @@ -50,13 +53,25 @@ abstract contract TryMulticall { successes = new bool[](callsLength); $.entered = true; for (uint256 i; i < callsLength; ++i) { - bytes calldata callData = calls[i]; - (bool success, bytes memory revertData) = address(this).delegatecall(callData); + bytes memory callData = calls[i]; + bool success; + bytes4 errorSelector; + bytes32 revertDataHash; + assembly ("memory-safe") { + success := delegatecall(gas(), address(), add(callData, 0x20), mload(callData), 0, 0) + if iszero(success) { + let size := returndatasize() + if gt(size, MAX_REVERT_DATA_SIZE) { size := MAX_REVERT_DATA_SIZE } + let data := mload(0x40) + returndatacopy(data, 0, size) + if iszero(lt(size, 4)) { errorSelector := mload(data) } + revertDataHash := keccak256(data, size) + } + } successes[i] = success; if (!success) { - bytes4 errorSelector = revertData.length >= 4 ? bytes4(revertData) : bytes4(0); - emit ProposalCallFailed(i, keccak256(callData), errorSelector, keccak256(revertData)); + emit ProposalCallFailed(i, keccak256(callData), errorSelector, revertDataHash); } } $.entered = false; diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index 12a9e6f..c84be55 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -842,7 +842,7 @@ contract SignedProposerTest is Test { assertEq(currency.balanceOf(proposer), 0); } - function test_tryMulticall_hashesCompleteLargeRevertData() public { + function test_tryMulticall_hashesBoundedLargeRevertData() public { uint256 timestamp = block.timestamp; _makeRequest(timestamp, 0); _setBond(); @@ -866,8 +866,12 @@ contract SignedProposerTest is Test { calls[0] = _encodeProposalCall(failedProposal, proposer, permit, "", 0); calls[1] = _encodeProposalCall(validProposal, proposer, permit, "", 0); + bytes memory expectedPrefix = new bytes(256); + for (uint256 i; i < expectedPrefix.length; ++i) { + expectedPrefix[i] = bytes1(uint8(i % 251 + 1)); + } vm.expectEmit(true, true, false, true, address(signedProposer)); - emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0), keccak256(new bytes(revertDataSize))); + emit ProposalCallFailed(0, keccak256(calls[0]), bytes4(0x01020304), keccak256(expectedPrefix)); vm.prank(relayer); bool[] memory successes = signedProposer.tryMulticall(calls); @@ -876,6 +880,35 @@ contract SignedProposerTest is Test { assertTrue(successes[1]); } + function test_tryMulticall_largeRevertPreservesEarlierSuccessWithLimitedGas() public { + uint256 timestamp = block.timestamp; + _makeRequest(timestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND); + + SignedProposer.Proposal memory validProposal = _buildProposal(timestamp, 2 ether); + SignedProposer.Proposal memory failedProposal = _buildRevertingProposal(false, 512 * 1024, timestamp, 1 ether); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + bytes[] memory calls = new bytes[](2); + calls[0] = _encodeProposalCall(validProposal, proposer, permit, "", 0); + calls[1] = _encodeProposalCall(failedProposal, proposer, permit, "", 0); + + bytes memory expectedPrefix = new bytes(256); + for (uint256 i; i < expectedPrefix.length; ++i) { + expectedPrefix[i] = bytes1(uint8(i % 251 + 1)); + } + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit ProposalCallFailed(1, keccak256(calls[1]), bytes4(0x01020304), keccak256(expectedPrefix)); + + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, 2_000_000); + + assertTrue(outerSuccess); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposedPrice, 2 ether); + assertEq(currency.balanceOf(proposer), 0); + } + // ─── Delegated proposer role tests ─────────────────────────────────────────── function test_revert_propose_notDelegatedProposer() public { @@ -1573,6 +1606,10 @@ contract RevertingSignedProposerOracle { } bytes memory revertData = new bytes(revertDataSize); + // Pattern the prefix and bytes beyond the cap without exhausting the gas-limited returndata regression. + for (uint256 i; i < revertData.length && i < 512; ++i) { + revertData[i] = bytes1(uint8(i % 251 + 1)); + } assembly ("memory-safe") { revert(add(revertData, 0x20), mload(revertData)) } From 5b87be6b70c7cb0e2d977d57f8a6023f7f68ca7e Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Tue, 22 Sep 2026 07:46:17 +0200 Subject: [PATCH 6/6] feat: add UUPS upgradeability to SignedProposer --- script/DeploySignedProposer.s.sol | 16 ++- script/README.md | 26 ++++- .../implementation/SignedProposer.sol | 41 +++++-- test/SignedProposer.t.sol | 107 +++++++++++++++++- test/SignedProposerPermit2.t.sol | 23 +++- test/SignedProposerTryMulticall.Fork.t.sol | 10 +- 6 files changed, 201 insertions(+), 22 deletions(-) diff --git a/script/DeploySignedProposer.s.sol b/script/DeploySignedProposer.s.sol index 443a53c..b207f55 100644 --- a/script/DeploySignedProposer.s.sol +++ b/script/DeploySignedProposer.s.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.27; +import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import {Script} from "forge-std/Script.sol"; import {console} from "forge-std/console.sol"; import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; @@ -9,7 +10,7 @@ import {SignedProposer} from "../src/optimistic-oracle-v2/implementation/SignedP /** * @title Deployment script for SignedProposer - * @notice Deploys SignedProposer with configurable Permit2 and admin addresses + * @notice Deploys a UUPS SignedProposer implementation and atomically initialized ERC1967 proxy * * Environment variables: * - MNEMONIC: Required. The mnemonic phrase for the deployer wallet @@ -33,12 +34,21 @@ contract DeploySignedProposer is Script { vm.startBroadcast(deployerPrivateKey); - signedProposer = new SignedProposer(ISignatureTransfer(permit2Address), admin); + SignedProposer implementation = new SignedProposer(); + signedProposer = SignedProposer( + address( + new ERC1967Proxy( + address(implementation), + abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(permit2Address), admin)) + ) + ) + ); vm.stopBroadcast(); console.log("\n=== Deployment Summary ==="); - console.log("SignedProposer:", address(signedProposer)); + console.log("SignedProposer proxy:", address(signedProposer)); + console.log("SignedProposer implementation:", address(implementation)); console.log("Chain ID:", block.chainid); console.log("Deployer:", deployer); console.log("Permit2:", permit2Address); diff --git a/script/README.md b/script/README.md index 1950621..a96e1b6 100644 --- a/script/README.md +++ b/script/README.md @@ -307,7 +307,7 @@ The `ManagedOptimisticOracleV2` contract: ## SignedProposer Deployment -The `DeploySignedProposer.s.sol` script deploys `SignedProposer` using the canonical Permit2 deployment by default. +The `DeploySignedProposer.s.sol` script deploys a UUPS `SignedProposer` implementation and an ERC1967 proxy, atomically calling `initialize(permit2, admin)` during proxy construction. It uses the canonical Permit2 deployment by default and logs both addresses. The implementation disables initialization. ### Environment Variables @@ -315,7 +315,7 @@ The `DeploySignedProposer.s.sol` script deploys `SignedProposer` using the canon |----------|----------|-------------| | `MNEMONIC` | Yes | The mnemonic phrase for the deployer wallet (uses 0 index address) | | `PERMIT2_ADDRESS` | No | Permit2 address; defaults to `0x000000000022D473030F116dDEE9F6B43aC78BA3` | -| `SIGNED_PROPOSER_ADMIN` | No | Address receiving the default admin role; defaults to the deployer | +| `SIGNED_PROPOSER_ADMIN` | No | Address receiving the default admin role, including upgrade authority; defaults to the deployer | ### Usage @@ -323,7 +323,21 @@ The `DeploySignedProposer.s.sol` script deploys `SignedProposer` using the canon forge script script/DeploySignedProposer.s.sol --rpc-url "YOUR_RPC_URL" --broadcast ``` -The script only deploys the contract. The admin configures delegated proposers and any required whitelist ownership separately. +The script deploys and initializes the proxy. The admin configures delegated proposers and any required whitelist ownership separately. Use the **proxy address** for all relay calls, the Permit2 spender in signatures, whitelist membership, and whitelist ownership. + +### Upgradeability + +SignedProposer uses the same OpenZeppelin UUPS/ERC1967 mechanism as Managed OO and OOReporter. Its existing `DEFAULT_ADMIN_ROLE` authorizes `upgradeToAndCall(newImplementation, data)` on the proxy; no separate owner, proxy admin contract, or upgrade role is added. Delegated proposers and whitelist admins cannot upgrade unless they also hold the default admin role. Use empty `data` when no migration is needed; do not call `initialize` again. + +The Permit2 address is initialized in proxy storage. Roles, retained token balances, whitelist ownership, and the Permit2 spender address survive compatible implementation upgrades. Existing signatures remain usable subject to their original deadlines, nonce usage, and proposal validity. The default admin is trusted to install implementations that can change relay behavior, including how outstanding signatures are handled. + +Future upgrades must preserve the storage layout, including the inherited `TryMulticall` batch lock and `permit2`, and retain the UUPS authorization hook. Validate storage compatibility against the deployed build before upgrading. This deployment change does not retrofit upgradeability onto any previously deployed direct SignedProposer instance; that requires a new proxy deployment and updating integrations to its address. + +The integrated layout stores the batch lock in the ERC-7201 namespace `uma.storage.TryMulticall` and `permit2` at +slot 0, offset 0. This is the layout for the initial proxy deployment. The earlier UUPS proposal with a sequential batch +lock placed `permit2` at slot 0, offset 1; it is not storage-compatible with this version. Do not upgrade a proxy using +that earlier layout directly to this implementation. Such a deployment requires a separately reviewed migration or a +new proxy. The integration does not include a storage migration. ### Partial-success proposal batches @@ -339,7 +353,7 @@ batch reverts and rolls back earlier successes. Polygon Bor rejects transactions larger than 128 KiB. With the maximum valid OOv2 ancillary data of 8,139 non-zero bytes, each encoded `propose` child is 8,804 bytes: 14 children produce 124,612 -bytes of outer calldata and execute within the 53,902,641 gas limit at pinned block `81,683,818`, +bytes of outer calldata; the proxy-based capacity test uses the 53,902,641 gas limit at pinned block `81,683,818`, while 15 children produce 133,508 bytes before the signed transaction envelope and are rejected. Smaller ancillary data permits larger batches, subject to the same transaction-size and gas bounds. @@ -373,8 +387,10 @@ reachable functions must retain their own authorization because `multicall` does ### Verification +Verify the implementation with no constructor arguments. Verify the ERC1967 proxy separately using its implementation address and encoded `initialize(permit2, admin)` calldata as constructor arguments. + ```bash -forge verify-contract src/optimistic-oracle-v2/implementation/SignedProposer.sol:SignedProposer --chain-id --constructor-args $(cast abi-encode "constructor(address,address)" ) --etherscan-api-key +forge verify-contract src/optimistic-oracle-v2/implementation/SignedProposer.sol:SignedProposer --chain-id --etherscan-api-key ``` ## ManagedOptimisticOracleV2 Upgrade diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 7721b5f..1e8184c 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -3,14 +3,15 @@ pragma solidity ^0.8.27; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; -import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; -import {Multicall} from "@openzeppelin/contracts/utils/Multicall.sol"; -import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; +import {MulticallUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol"; +import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {OptimisticOracleV2Interface} from "../interfaces/OptimisticOracleV2Interface.sol"; import {SignedProposerOracleInterface} from "../interfaces/SignedProposerOracleInterface.sol"; import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol"; import {AddressWhitelist} from "../../common/implementation/AddressWhitelist.sol"; import {AddressWhitelistInterface} from "../../common/interfaces/AddressWhitelistInterface.sol"; +import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; /** @@ -32,7 +33,11 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * spender and the `proposePriceFor` call target, so executing an unintended oracle can spend up to * the signer-approved Permit2 amount for that proposal. * + * Deploy behind an ERC1967Proxy and initialize atomically. The default admin authorizes UUPS + * upgrades; the proxy remains the Permit2 spender and whitelist owner across upgrades. + * * The contract is permissioned: + * - `DEFAULT_ADMIN_ROLE` — manages roles, payments, whitelist ownership, and upgrades. * - `DELEGATED_PROPOSER_ROLE` — may call `propose` and `tryMulticall`. * - `WHITELIST_ADMIN_ROLE` — may directly add/remove entries on whitelists owned by this contract. * @@ -42,7 +47,13 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * apply their own. `tryMulticall` instead restricts the caller to delegated proposers, accepts only `propose`, and rejects * nested partial-success batches. These restrictions do not apply to the atomic `multicall` entry point. */ -contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMulticall { +contract SignedProposer is + AccessControlUpgradeable, + MulticallUpgradeable, + ReentrancyGuardUpgradeable, + UUPSUpgradeable, + TryMulticall +{ using SafeERC20 for IERC20; // ─── Structs ────────────────────────────────────────────────────────────────── @@ -73,9 +84,9 @@ contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMultica string public constant WITNESS_TYPE_STRING = "Proposal witness)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)TokenPermissions(address token,uint256 amount)"; - // ─── Immutables ─────────────────────────────────────────────────────────────── + // ─── Storage ─────────────────────────────────────────────────────────────── - ISignatureTransfer public immutable permit2; + ISignatureTransfer public permit2; // ─── Events ─────────────────────────────────────────────────────────────────── @@ -92,18 +103,34 @@ contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMultica event PaymentWithdrawn(address indexed token, address indexed to, uint256 amount); + error ZeroAddress(); error PaymentExceedsMaxPayment(); error PermitTransferAmountMismatch(uint256 expectedAmount, uint256 receivedAmount); error PermitTokenMismatch(address requestCurrency, address permitToken); error CannotRemoveSelfFromWhitelist(); error NewOwnerNotWhitelisted(address newOwner); + // ─── Constructor ────────────────────────────────────────────────────────────── - constructor(ISignatureTransfer _permit2, address admin) { + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + + /// @notice Initializes the proxy with its Permit2 contract and role/upgrade administrator. + function initialize(ISignatureTransfer _permit2, address admin) external initializer { + if (address(_permit2) == address(0) || admin == address(0)) revert ZeroAddress(); + __AccessControl_init(); + __Multicall_init(); + __ReentrancyGuard_init(); + __UUPSUpgradeable_init(); permit2 = _permit2; _grantRole(DEFAULT_ADMIN_ROLE, admin); } + /// @dev Reuses the existing admin role rather than introducing a separate upgrade authority. + function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) {} + // ─── Propose ────────────────────────────────────────────────────────────────── /** diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index c84be55..31b0d01 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -20,12 +20,14 @@ import {MockOracle} from "./mocks/MockOracle.sol"; import {MockPermit2} from "./mocks/MockPermit2.sol"; import {MaliciousSignedProposerOracle} from "./mocks/MaliciousSignedProposerOracle.sol"; +import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; +import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; -import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; +import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; contract ShortTransferERC20Mock is ERC20Mock { uint256 internal constant TRANSFER_FEE_BPS = 1_000; @@ -164,7 +166,14 @@ contract SignedProposerTest is Test { moo.addRequestManager(requestManager); // Deploy SignedProposer with admin, then grant relayer the delegated proposer role. - signedProposer = new SignedProposer(ISignatureTransfer(address(mockPermit2)), admin); + signedProposer = SignedProposer( + address( + new ERC1967Proxy( + address(new SignedProposer()), + abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(address(mockPermit2)), admin)) + ) + ) + ); vm.prank(admin); signedProposer.addDelegatedProposer(relayer); @@ -176,6 +185,84 @@ contract SignedProposerTest is Test { requesterWhitelist.addToWhitelist(requester); } + function test_revert_initialize_implementationLockedAndProxyCannotReinitialize() public { + SignedProposer implementation = new SignedProposer(); + vm.expectRevert(Initializable.InvalidInitialization.selector); + implementation.initialize(ISignatureTransfer(address(mockPermit2)), admin); + + vm.expectRevert(Initializable.InvalidInitialization.selector); + signedProposer.initialize(ISignatureTransfer(address(mockPermit2)), admin); + } + + function test_revert_initialize_zeroAddresses() public { + SignedProposer implementation = new SignedProposer(); + vm.expectRevert(SignedProposer.ZeroAddress.selector); + new ERC1967Proxy( + address(implementation), abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(address(0)), admin)) + ); + vm.expectRevert(SignedProposer.ZeroAddress.selector); + new ERC1967Proxy( + address(implementation), + abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(address(mockPermit2)), address(0))) + ); + } + + function test_revert_upgrade_onlyDefaultAdmin() public { + SignedProposer implementation = new SignedProposer(); + address whitelistAdmin = makeAddr("whitelistAdmin"); + vm.prank(admin); + signedProposer.addWhitelistAdmin(whitelistAdmin); + address[3] memory unauthorized = [relayer, whitelistAdmin, makeAddr("outsider")]; + for (uint256 i; i < unauthorized.length; ++i) { + vm.expectRevert( + abi.encodeWithSelector( + IAccessControl.AccessControlUnauthorizedAccount.selector, unauthorized[i], DEFAULT_ADMIN_ROLE + ) + ); + vm.prank(unauthorized[i]); + signedProposer.upgradeToAndCall(address(implementation), ""); + } + } + + function test_revert_upgrade_nonUUPSImplementation() public { + vm.expectRevert( + abi.encodeWithSelector(ERC1967Utils.ERC1967InvalidImplementation.selector, address(mockPermit2)) + ); + vm.prank(admin); + signedProposer.upgradeToAndCall(address(mockPermit2), ""); + } + + function test_upgrade_preservesStateAndBatching() public { + vm.prank(admin); + signedProposer.addWhitelistAdmin(relayer); + defaultProposerWhitelist.transferOwnership(address(signedProposer)); + test_tryMulticall_allSuccess_preservesProposalEventsAndAccounting(); + uint256 retainedPayment = currency.balanceOf(address(signedProposer)); + assertGt(retainedPayment, 0); + + SignedProposer implementation = new SignedProposer(); + vm.prank(admin); + signedProposer.upgradeToAndCall(address(implementation), ""); + + assertEq( + address(uint160(uint256(vm.load(address(signedProposer), ERC1967Utils.IMPLEMENTATION_SLOT)))), + address(implementation) + ); + assertEq(address(signedProposer.permit2()), address(mockPermit2)); + assertTrue(signedProposer.hasRole(DEFAULT_ADMIN_ROLE, admin)); + assertTrue(signedProposer.hasRole(DELEGATED_PROPOSER_ROLE, relayer)); + assertTrue(signedProposer.hasRole(WHITELIST_ADMIN_ROLE, relayer)); + assertEq(defaultProposerWhitelist.owner(), address(signedProposer)); + assertTrue(defaultProposerWhitelist.isOnWhitelist(address(signedProposer))); + assertEq(currency.balanceOf(address(signedProposer)), retainedPayment); + vm.prank(admin); + signedProposer.withdrawPayments(IERC20(address(currency)), admin, retainedPayment); + assertEq(currency.balanceOf(admin), retainedPayment); + + // Exercises self-delegatecall, the batch lock, proposal reentrancy guard, and accounting after upgrading. + test_tryMulticall_allSuccess_preservesProposalEventsAndAccounting(); + } + // ─── Helpers ────────────────────────────────────────────────────────────────── function _makeRequest(uint256 timestamp, uint256 reward) internal returns (uint256 totalBond) { @@ -459,7 +546,7 @@ contract SignedProposerTest is Test { assertFalse(callbackRequester.reentrantProposeSucceeded()); assertEq( callbackRequester.reentrantRevertData(), - abi.encodeWithSelector(ReentrancyGuard.ReentrancyGuardReentrantCall.selector) + abi.encodeWithSelector(ReentrancyGuardUpgradeable.ReentrancyGuardReentrantCall.selector) ); } @@ -900,7 +987,8 @@ contract SignedProposerTest is Test { vm.expectEmit(true, true, false, true, address(signedProposer)); emit ProposalCallFailed(1, keccak256(calls[1]), bytes4(0x01020304), keccak256(expectedPrefix)); - (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, 2_000_000); + // The self-delegatecall also traverses the proxy, which must copy the child's revert payload before the cap. + (bool outerSuccess, bool[] memory successes) = _tryMulticallWithGas(calls, 2_800_000); assertTrue(outerSuccess); assertTrue(successes[0]); @@ -1271,7 +1359,16 @@ contract SignedProposerTest is Test { defaultProposerWhitelist.removeFromWhitelist(proposer); address replacementAdmin = makeAddr("replacementAdmin"); - SignedProposer replacement = new SignedProposer(ISignatureTransfer(address(mockPermit2)), replacementAdmin); + SignedProposer replacement = SignedProposer( + address( + new ERC1967Proxy( + address(new SignedProposer()), + abi.encodeCall( + SignedProposer.initialize, (ISignatureTransfer(address(mockPermit2)), replacementAdmin) + ) + ) + ) + ); defaultProposerWhitelist.addToWhitelist(address(replacement)); defaultProposerWhitelist.transferOwnership(address(signedProposer)); diff --git a/test/SignedProposerPermit2.t.sol b/test/SignedProposerPermit2.t.sol index b3831c7..377fca1 100644 --- a/test/SignedProposerPermit2.t.sol +++ b/test/SignedProposerPermit2.t.sol @@ -143,7 +143,14 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { permit2Address = deployPermit2(); vm.label(permit2Address, "PERMIT2"); - signedProposer = new SignedProposer(ISignatureTransfer(permit2Address), admin); + signedProposer = SignedProposer( + address( + new ERC1967Proxy( + address(new SignedProposer()), + abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(permit2Address), admin)) + ) + ) + ); vm.prank(admin); signedProposer.addDelegatedProposer(relayer); @@ -422,6 +429,14 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { } function test_tryMulticall_realPermit2DifferentProposersAndNonces() public { + _testRealPermit2Batch(false); + } + + function test_upgrade_preservesPreviouslySignedPermit2Batch() public { + _testRealPermit2Batch(true); + } + + function _testRealPermit2Batch(bool upgradeBeforeRelay) internal { vm.warp(block.timestamp + 2); uint256 firstTimestamp = block.timestamp - 1; uint256 secondTimestamp = block.timestamp; @@ -471,6 +486,12 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { ) ); + if (upgradeBeforeRelay) { + SignedProposer implementation = new SignedProposer(); + vm.prank(admin); + signedProposer.upgradeToAndCall(address(implementation), ""); + } + vm.prank(relayer); bool[] memory successes = signedProposer.tryMulticall(calls); diff --git a/test/SignedProposerTryMulticall.Fork.t.sol b/test/SignedProposerTryMulticall.Fork.t.sol index 6ef3289..2c0c9e5 100644 --- a/test/SignedProposerTryMulticall.Fork.t.sol +++ b/test/SignedProposerTryMulticall.Fork.t.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.27; +import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import {Test} from "forge-std/Test.sol"; import {IEIP712} from "permit2/src/interfaces/IEIP712.sol"; @@ -58,7 +59,14 @@ contract SignedProposerTryMulticallForkTest is Test { assertNotEq(firstProposer, secondProposer, "proposers must differ"); currency = new ERC20Mock(); - signedProposer = new SignedProposer(ISignatureTransfer(POLYGON_PERMIT2), admin); + signedProposer = SignedProposer( + address( + new ERC1967Proxy( + address(new SignedProposer()), + abi.encodeCall(SignedProposer.initialize, (ISignatureTransfer(POLYGON_PERMIT2), admin)) + ) + ) + ); oracle = new MaliciousSignedProposerOracle(currency, address(signedProposer), address(0)); oracle.setBondAmount(BOND);