From 32e23e49a82dd95ad7621bb2517d33e4587b043d Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Mon, 31 Aug 2026 14:56:36 +0200 Subject: [PATCH 1/8] 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 eb3e7c47418bad2544b19d8ff011ffd5b8aba734 Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Tue, 8 Sep 2026 18:47:18 +0200 Subject: [PATCH 2/8] managed-oracle: add UUPS upgrades to SignedProposer --- script/DeploySignedProposer.s.sol | 16 ++- script/README.md | 20 +++- .../implementation/SignedProposer.sol | 41 +++++-- test/SignedProposer.t.sol | 104 +++++++++++++++++- test/SignedProposerPermit2.t.sol | 23 +++- test/SignedProposerTryMulticall.Fork.t.sol | 10 +- 6 files changed, 193 insertions(+), 21 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 ca5c3e3..68365e5 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,15 @@ 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. ### Partial-success proposal batches @@ -339,7 +347,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. @@ -367,8 +375,10 @@ does not change worker behavior; worker integration must be performed separately ### 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 7920288..5940776 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"; /** @@ -31,11 +32,21 @@ 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. */ -contract SignedProposer is AccessControl, Multicall, ReentrancyGuard, TryMulticall { +contract SignedProposer is + AccessControlUpgradeable, + MulticallUpgradeable, + ReentrancyGuardUpgradeable, + UUPSUpgradeable, + TryMulticall +{ using SafeERC20 for IERC20; // ─── Structs ────────────────────────────────────────────────────────────────── @@ -66,9 +77,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 ─────────────────────────────────────────────────────────────────── @@ -85,18 +96,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 570ccf7..40ef5d8 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) { @@ -446,7 +533,7 @@ contract SignedProposerTest is Test { assertFalse(callbackRequester.reentrantProposeSucceeded()); assertEq( callbackRequester.reentrantRevertData(), - abi.encodeWithSelector(ReentrancyGuard.ReentrancyGuardReentrantCall.selector) + abi.encodeWithSelector(ReentrancyGuardUpgradeable.ReentrancyGuardReentrantCall.selector) ); } @@ -1225,7 +1312,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); From 3332f8aadd15e682de5adc797b8c19df8856f449 Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Tue, 8 Sep 2026 19:16:53 +0200 Subject: [PATCH 3/8] managed-oracle: add one-signature partial-success proposal batches --- script/README.md | 81 +++++ .../implementation/SignedProposer.sol | 141 +++++++-- test/SignedProposer.t.sol | 120 ++++++++ test/SignedProposerPermit2.t.sol | 280 ++++++++++++++++++ 4 files changed, 604 insertions(+), 18 deletions(-) diff --git a/script/README.md b/script/README.md index 68365e5..e513e2d 100644 --- a/script/README.md +++ b/script/README.md @@ -373,6 +373,87 @@ In particular, empty failure metadata is ambiguous between an empty revert and o OpenZeppelin `multicall(bytes[])` remains available and atomic for compatibility. `tryMulticall` does not change worker behavior; worker integration must be performed separately. +### One-signature proposal batches + +`proposeBatch(BatchProposal[] proposals, address proposer, PermitTransferFrom permit, bytes signature, uint256[] payments)` executes a partial-success batch for **one signer and one collateral token**. Unlike `tryMulticall`, it uses one Permit2 signature, one nonce, and one upfront token transfer for the entire batch. It adds no persistent batch state or initializer changes. + +```solidity +struct BatchProposal { + Proposal proposal; // Existing fields, including maxPayment. + uint256 maxAmount; // This item's maximum bond + payment spend. +} +``` + +The signed witness is `BatchWitness(BatchProposal[] proposals)`. Each array item binds all existing proposal fields and its own `maxAmount`, and the array order is signed. The sum of `maxAmount` values must equal `permit.permitted.amount`. The batch must be nonempty and `payments.length` must match `proposals.length`. Actual `payments` are selected by the relayer and capped by each signed `proposal.maxPayment`; payments also consume that item's budget. + +The contract pulls the full budget once, verifies the exact token receipt, and attempts each item in an external self-call. That helper is callable only by the contract itself; the outer reentrancy guard remains active. Each oracle receives an allowance bounded by its item's budget minus payment, and any remaining allowance is revoked. A failed item rolls back all of its effects, including token movement and temporary whitelist changes. An item whose request currency does not match the permit token fails individually. The final refund is: + +```text +permit.permitted.amount - sum(successful actual bonds + successful payments) +``` + +Previously retained payments are excluded from the refund. Successful items emit `ProposalExecuted`; failed items emit `BatchProposalFailed(index, proposalHash, errorSelector, revertDataHash)`, where `proposalHash` is the EIP-712 struct hash of the signed `BatchProposal` item. The function returns a matching `bool[]`, and `BatchExecuted(proposer, token, nonce, spent, refund)` summarizes the batch. Full signatures and ancillary data are not logged by these batch events. + +A completed outer transaction consumes the Permit2 nonce **even when every item fails**. Refunds do not restore it: retry failed items using a fresh batch signature and unused nonce. Invalid signatures, malformed batch shape/budgets, a failed Permit2 transfer, or a failed final refund revert the whole transaction, including nonce consumption and any successful proposals. This is a one-shot batch authorization, not an authorization that can be filled over multiple transactions. + +Like `tryMulticall`, this method has no per-child gas cap or batch-size constant. An out-of-gas child can starve later items or prevent the outer transaction from finishing; an outer revert rolls everything back. Clients must estimate gas and check calldata size for the actual batch. The 14/15 maximum-ancillary-data boundary documented above applies to the older `tryMulticall` encoding, not this encoding; do not assume that 15–20 items always fit Polygon's transaction-size limit. + +#### Constructing the signature in a UI + +Use the existing `Proposal` fields as typed data rather than ABI-encoded arbitrary calls. With `@uniswap/permit2-sdk` and an ethers v6 signer, the following constructs one signature. `proposals` is the ordered array of `{ proposal: { oracle, requester, identifier, timestamp, ancillaryData, proposedPrice, maxPayment }, maxAmount }` objects. `ancillaryData` is a hex-encoded byte string, and large integers should use decimal strings or bigint rather than JavaScript numbers. + +```typescript +import { SignatureTransfer } from '@uniswap/permit2-sdk' + +const permit = { + permitted: { + token: collateralToken, + amount: proposals.reduce((sum, item) => sum + BigInt(item.maxAmount), 0n).toString(), + }, + spender: signedProposerProxy, // The proxy, not the implementation or relayer. + nonce, // Unused Permit2 unordered nonce for this signer. + deadline, +} + +const { domain, types, values } = SignatureTransfer.getPermitData( + permit, + permit2Address, + chainId, + { + witness: { proposals }, + witnessTypeName: 'BatchWitness', + witnessType: { + BatchWitness: [{ name: 'proposals', type: 'BatchProposal[]' }], + BatchProposal: [ + { name: 'proposal', type: 'Proposal' }, + { name: 'maxAmount', type: 'uint256' }, + ], + Proposal: [ + { name: 'oracle', type: 'address' }, + { name: 'requester', type: 'address' }, + { name: 'identifier', type: 'bytes32' }, + { name: 'timestamp', type: 'uint256' }, + { name: 'ancillaryData', type: 'bytes' }, + { name: 'proposedPrice', type: 'int256' }, + { name: 'maxPayment', type: 'uint256' }, + ], + }, + }, +) +const signature = await signer.signTypedData(domain, types, values) + +// Submit via an account holding DELEGATED_PROPOSER_ROLE. +await relayContract.proposeBatch( + proposals, + await signer.getAddress(), + { permitted: permit.permitted, nonce: permit.nonce, deadline: permit.deadline }, + signature, + payments, +) +``` + +The wallet must already have sufficient ERC20 allowance to Permit2; a first-time token approval is separate from this one batch signature. The UI should show every proposal and its spend/payment caps, verify intended oracle addresses, and identify failed items for a fresh signature. Wallet rendering of nested typed-data arrays varies. The existing single-proposal witness remains unchanged, and `tryMulticall` still accepts only `propose` calls; use `proposeBatch` directly for this flow. + ### 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. diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 5940776..12a041f 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -18,7 +18,7 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * @title SignedProposer * @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. + * signature authorises both the token transfer and a specific proposal or ordered proposal batch. * * The signer is set as the proposer (receiving rewards on settlement). * @@ -37,7 +37,7 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * * The contract is permissioned: * - `DEFAULT_ADMIN_ROLE` — manages roles, payments, whitelist ownership, and upgrades. - * - `DELEGATED_PROPOSER_ROLE` — may call `propose` and `tryMulticall`. + * - `DELEGATED_PROPOSER_ROLE` — may call `propose`, `proposeBatch`, and `tryMulticall`. * - `WHITELIST_ADMIN_ROLE` — may directly add/remove entries on whitelists owned by this contract. */ contract SignedProposer is @@ -51,7 +51,7 @@ contract SignedProposer is // ─── Structs ────────────────────────────────────────────────────────────────── - /// @notice Proposal witness — token amount, nonce & deadline live in the Permit2 permit. + /// @notice Proposal witness fields shared by individual permits and batch items. struct Proposal { address oracle; address requester; @@ -62,6 +62,12 @@ contract SignedProposer is uint256 maxPayment; } + /// @notice One signed batch item; maxAmount covers this proposal's bond and payment. + struct BatchProposal { + Proposal proposal; + uint256 maxAmount; + } + // ─── Roles ───────────────────────────────────────────────────────────────────── bytes32 public constant DELEGATED_PROPOSER_ROLE = keccak256("DELEGATED_PROPOSER_ROLE"); @@ -77,6 +83,15 @@ contract SignedProposer is 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)"; + bytes32 public constant BATCH_PROPOSAL_TYPEHASH = keccak256( + "BatchProposal(Proposal proposal,uint256 maxAmount)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" + ); + bytes32 public constant BATCH_WITNESS_TYPEHASH = keccak256( + "BatchWitness(BatchProposal[] proposals)BatchProposal(Proposal proposal,uint256 maxAmount)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" + ); + string public constant BATCH_WITNESS_TYPE_STRING = + "BatchWitness witness)BatchProposal(Proposal proposal,uint256 maxAmount)BatchWitness(BatchProposal[] proposals)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)TokenPermissions(address token,uint256 amount)"; + // ─── Storage ─────────────────────────────────────────────────────────────── ISignatureTransfer public permit2; @@ -96,6 +111,17 @@ contract SignedProposer is event PaymentWithdrawn(address indexed token, address indexed to, uint256 amount); + event BatchProposalFailed( + uint256 indexed index, bytes32 indexed proposalHash, bytes4 errorSelector, bytes32 revertDataHash + ); + event BatchExecuted( + address indexed proposer, address indexed token, uint256 indexed nonce, uint256 spent, uint256 refund + ); + + error EmptyBatch(); + error BatchLengthMismatch(); + error BatchAmountMismatch(uint256 totalBudget, uint256 permitAmount); + error OnlySelf(); error ZeroAddress(); error PaymentExceedsMaxPayment(); error PermitTransferAmountMismatch(uint256 expectedAmount, uint256 receivedAmount); @@ -163,8 +189,79 @@ contract SignedProposer is if (address(currency) != permit.permitted.token) { revert PermitTokenMismatch(address(currency), permit.permitted.token); } - _permit2Transfer(proposal, permit, proposer, signature); - totalBond = _executeProposal(proposal, proposer, currency, permit.permitted.amount, payment); + _permit2Transfer(permit, proposer, signature, _hashProposal(proposal), WITNESS_TYPE_STRING); + totalBond = _executeProposal(proposal, proposer, currency, permit.permitted.amount, payment, true); + } + + /** + * @notice Execute a same-token batch for one signer using one Permit2 witness signature. + * @dev The ordered proposals and their individual budgets are signed. Their budgets must sum + * exactly to permit.permitted.amount. Each child rolls back independently on failure; only + * successful bonds/payments are charged, and all unused funds are refunded once at the end. + * A completed batch consumes its nonce even if every child fails. Invalid signatures, invalid + * batch shape/funding, a failed final refund, or insufficient outer gas revert the whole batch. + * As with tryMulticall, there is no per-child gas cap or guarantee against gas starvation. + * @param proposals Signed proposal fields and bond-plus-payment budgets, in execution order. + * @param proposer Signer, token owner, and refund recipient for the entire batch. + * @param permit Single-token Permit2 authorization covering the sum of all item budgets. + * @param signature One signature over the permit and BatchWitness. + * @param payments Actual per-item payments, bounded by each signed proposal.maxPayment. + * @return successes Per-item execution results. Failed items require a fresh signed batch to retry. + */ + function proposeBatch( + BatchProposal[] calldata proposals, + address proposer, + ISignatureTransfer.PermitTransferFrom calldata permit, + bytes calldata signature, + uint256[] calldata payments + ) external onlyRole(DELEGATED_PROPOSER_ROLE) nonReentrant returns (bool[] memory successes) { + uint256 length = proposals.length; + if (length == 0) revert EmptyBatch(); + if (length != payments.length) revert BatchLengthMismatch(); + + bytes32[] memory hashes = new bytes32[](length); + uint256 totalBudget; + for (uint256 i; i < length; ++i) { + hashes[i] = _hashBatchProposal(proposals[i]); + totalBudget += proposals[i].maxAmount; + } + if (totalBudget != permit.permitted.amount) { + revert BatchAmountMismatch(totalBudget, permit.permitted.amount); + } + bytes32 witness = keccak256(abi.encode(BATCH_WITNESS_TYPEHASH, keccak256(abi.encodePacked(hashes)))); + _permit2Transfer(permit, proposer, signature, witness, BATCH_WITNESS_TYPE_STRING); + + IERC20 currency = IERC20(permit.permitted.token); + uint256 refund = totalBudget; + successes = new bool[](length); + for (uint256 i; i < length; ++i) { + try this.executeBatchProposal(proposals[i], proposer, currency, payments[i]) returns (uint256 spent) { + successes[i] = true; + refund -= spent; + } catch (bytes memory reason) { + bytes4 errorSelector = reason.length >= 4 ? bytes4(reason) : bytes4(0); + emit BatchProposalFailed(i, hashes[i], errorSelector, keccak256(reason)); + } + } + if (refund > 0) currency.safeTransfer(proposer, refund); + emit BatchExecuted(proposer, address(currency), permit.nonce, totalBudget - refund, refund); + } + + /// @dev Only the funded batch may enter this call boundary. The outer nonReentrant guard stays + /// active throughout child execution; token/oracle callbacks cannot enter propose or proposeBatch. + /// An external self-call lets the parent catch failures and roll back every effect of this child. + function executeBatchProposal(BatchProposal calldata item, address proposer, IERC20 currency, uint256 payment) + external + returns (uint256 spent) + { + if (msg.sender != address(this)) revert OnlySelf(); + if (payment > item.proposal.maxPayment) revert PaymentExceedsMaxPayment(); + IERC20 requestCurrency = _getRequestCurrency(item.proposal); + if (requestCurrency != currency) { + revert PermitTokenMismatch(address(requestCurrency), address(currency)); + } + // Defer refunds to the outer batch; the individual cap still bounds this oracle's allowance. + spent = _executeProposal(item.proposal, proposer, currency, item.maxAmount, payment, false) + payment; } // ─── Internals ──────────────────────────────────────────────────────────────── @@ -184,16 +281,8 @@ contract SignedProposer is return request.currency; } - function _permit2Transfer( - Proposal calldata proposal, - ISignatureTransfer.PermitTransferFrom calldata permit, - address proposer, - bytes calldata signature - ) internal { - IERC20 currency = IERC20(permit.permitted.token); - uint256 balanceBefore = currency.balanceOf(address(this)); - - bytes32 witness = keccak256( + function _hashProposal(Proposal calldata proposal) internal pure returns (bytes32) { + return keccak256( abi.encode( PROPOSAL_TYPEHASH, proposal.oracle, @@ -205,13 +294,28 @@ contract SignedProposer is proposal.maxPayment ) ); + } + + function _hashBatchProposal(BatchProposal calldata item) internal pure returns (bytes32) { + return keccak256(abi.encode(BATCH_PROPOSAL_TYPEHASH, _hashProposal(item.proposal), item.maxAmount)); + } + + function _permit2Transfer( + ISignatureTransfer.PermitTransferFrom calldata permit, + address proposer, + bytes calldata signature, + bytes32 witness, + string memory witnessTypeString + ) internal { + IERC20 currency = IERC20(permit.permitted.token); + uint256 balanceBefore = currency.balanceOf(address(this)); permit2.permitWitnessTransferFrom( permit, ISignatureTransfer.SignatureTransferDetails({to: address(this), requestedAmount: permit.permitted.amount}), proposer, witness, - WITNESS_TYPE_STRING, + witnessTypeString, signature ); @@ -227,7 +331,8 @@ contract SignedProposer is address proposer, IERC20 currency, uint256 maxAmount, - uint256 payment + uint256 payment, + bool refundExcess ) internal returns (uint256 totalBond) { AddressWhitelistInterface whitelist = _getEffectiveProposerWhitelist(proposal); bool addedToWhitelist; @@ -244,7 +349,7 @@ contract SignedProposer is if (addedToWhitelist) whitelist.removeFromWhitelist(proposer); uint256 excess = maxAmount - totalBond - payment; - if (excess > 0) currency.safeTransfer(proposer, excess); + if (refundExcess && excess > 0) currency.safeTransfer(proposer, excess); emit ProposalExecuted( proposer, diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index 40ef5d8..bb887e2 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -263,6 +263,117 @@ contract SignedProposerTest is Test { test_tryMulticall_allSuccess_preservesProposalEventsAndAccounting(); } + function test_proposeBatch_rejectsEmptyMismatchedAndIncorrectlyFundedBatches() public { + SignedProposer.BatchProposal[] memory items = new SignedProposer.BatchProposal[](0); + uint256[] memory payments = new uint256[](0); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(1 ether, 0, block.timestamp + 1 hours); + vm.expectRevert(SignedProposer.EmptyBatch.selector); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, "", payments); + + items = new SignedProposer.BatchProposal[](1); + items[0] = SignedProposer.BatchProposal(_buildProposal(block.timestamp, 1 ether), 2 ether); + vm.expectRevert(SignedProposer.BatchLengthMismatch.selector); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, "", payments); + + payments = new uint256[](1); + vm.expectRevert(abi.encodeWithSelector(SignedProposer.BatchAmountMismatch.selector, 2 ether, 1 ether)); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, "", payments); + } + + function test_proposeBatch_onlyDelegatedRelayers() public { + SignedProposer.BatchProposal[] memory items = new SignedProposer.BatchProposal[](0); + uint256[] memory payments = new uint256[](0); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(0, 0, block.timestamp + 1 hours); + vm.expectRevert( + abi.encodeWithSelector( + IAccessControl.AccessControlUnauthorizedAccount.selector, admin, DELEGATED_PROPOSER_ROLE + ) + ); + vm.prank(admin); + signedProposer.proposeBatch(items, proposer, permit, "", payments); + } + + function test_executeBatchProposal_cannotBypassFundingThroughPublicEntryPoints() public { + SignedProposer.BatchProposal memory item = + SignedProposer.BatchProposal(_buildProposal(block.timestamp, 1 ether), TOTAL_BOND); + bytes[] memory calls = new bytes[](1); + calls[0] = abi.encodeCall(SignedProposer.executeBatchProposal, (item, proposer, IERC20(address(currency)), 0)); + vm.expectRevert(SignedProposer.OnlySelf.selector); + vm.prank(relayer); + signedProposer.executeBatchProposal(item, proposer, IERC20(address(currency)), 0); + vm.expectRevert(SignedProposer.OnlySelf.selector); + vm.prank(admin); + signedProposer.multicall(calls); + vm.expectRevert( + abi.encodeWithSelector( + TryMulticall.TryMulticallInvalidSelector.selector, 0, SignedProposer.executeBatchProposal.selector + ) + ); + vm.prank(relayer); + signedProposer.tryMulticall(calls); + } + + function test_proposeBatch_rejectsShortPermit2Receipt() public { + ShortTransferERC20Mock shortToken = new ShortTransferERC20Mock(); + SignedProposer.BatchProposal[] memory items = new SignedProposer.BatchProposal[](1); + items[0] = SignedProposer.BatchProposal(_buildProposal(block.timestamp, 1 ether), 100 ether); + uint256[] memory payments = new uint256[](1); + ISignatureTransfer.PermitTransferFrom memory permit = + _buildPermitForToken(address(shortToken), 100 ether, 0, block.timestamp + 1 hours); + shortToken.mint(proposer, 100 ether); + vm.prank(proposer); + shortToken.approve(address(mockPermit2), 100 ether); + vm.expectRevert( + abi.encodeWithSelector(SignedProposer.PermitTransferAmountMismatch.selector, 100 ether, 90 ether) + ); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, "", payments); + assertEq(shortToken.balanceOf(proposer), 100 ether); + } + + function test_proposeBatch_blocksReentrantSingleProposal() public { + _batchWithReentrantCallback(false); + } + + function test_proposeBatch_blocksReentrantBatch() public { + _batchWithReentrantCallback(true); + } + + function _batchWithReentrantCallback(bool nestedBatch) internal { + ReentrantSignedProposerRequester callbackRequester = + new ReentrantSignedProposerRequester(moo, signedProposer, IERC20(address(currency))); + requester = address(callbackRequester); + requesterWhitelist.addToWhitelist(requester); + vm.prank(admin); + signedProposer.addDelegatedProposer(requester); + callbackRequester.requestWithProposalCallback(IDENTIFIER, block.timestamp, ANCILLARY); + _setBond(); + SignedProposer.BatchProposal[] memory items = new SignedProposer.BatchProposal[](1); + items[0] = SignedProposer.BatchProposal(_buildProposal(block.timestamp, 1 ether), TOTAL_BOND); + uint256[] memory payments = new uint256[](1); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND, 0, block.timestamp + 1 hours); + if (nestedBatch) { + callbackRequester.setReentrantBatchCall( + abi.encodeCall(SignedProposer.proposeBatch, (items, proposer, permit, bytes(""), payments)) + ); + } else { + callbackRequester.setReentrantProposal(items[0].proposal, proposer, permit, "", 0); + } + _fundAndApproveProposer(TOTAL_BOND); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, "", payments); + assertTrue(successes[0]); + assertTrue(callbackRequester.attemptedReentrantPropose()); + assertFalse(callbackRequester.reentrantProposeSucceeded()); + assertEq( + callbackRequester.reentrantRevertData(), + abi.encodeWithSelector(ReentrancyGuardUpgradeable.ReentrancyGuardReentrantCall.selector) + ); + } + // ─── Helpers ────────────────────────────────────────────────────────────────── function _makeRequest(uint256 timestamp, uint256 reward) internal returns (uint256 totalBond) { @@ -1547,6 +1658,7 @@ contract ReentrantSignedProposerRequester { ISignatureTransfer.PermitTransferFrom internal reentrantPermit; address internal reentrantProposer; bytes internal reentrantSignature; + bytes internal reentrantBatchCall; uint256 internal reentrantPayment; bool public attemptedReentrantPropose; @@ -1564,6 +1676,10 @@ contract ReentrantSignedProposerRequester { oracle.setCallbacks(identifier, timestamp, ancillaryData, true, false, false); } + function setReentrantBatchCall(bytes calldata callData) external { + reentrantBatchCall = callData; + } + function setReentrantProposal( SignedProposer.Proposal calldata proposal, address proposer, @@ -1582,6 +1698,10 @@ contract ReentrantSignedProposerRequester { require(msg.sender == address(oracle), "ReentrantRequester: unauthorized"); attemptedReentrantPropose = true; + if (reentrantBatchCall.length > 0) { + (reentrantProposeSucceeded, reentrantRevertData) = address(signedProposer).call(reentrantBatchCall); + return; + } try signedProposer.propose( reentrantProposal, reentrantProposer, reentrantPermit, reentrantSignature, reentrantPayment ) returns (uint256) { diff --git a/test/SignedProposerPermit2.t.sol b/test/SignedProposerPermit2.t.sol index 377fca1..2860d01 100644 --- a/test/SignedProposerPermit2.t.sol +++ b/test/SignedProposerPermit2.t.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.27; +import {Vm} from "forge-std/Vm.sol"; import {Test} from "forge-std/Test.sol"; import {DeployPermit2} from "permit2/test/utils/DeployPermit2.sol"; @@ -357,6 +358,285 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { return abi.encodePacked(r, s, v); } + function _prepareSignedBatch() + internal + returns ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) + { + vm.warp(block.timestamp + 3); + items = new SignedProposer.BatchProposal[](3); + payments = new uint256[](3); + for (uint256 i; i < 3; ++i) { + uint256 timestamp = block.timestamp - i; + _makeRequest(timestamp, 0); + items[i] = SignedProposer.BatchProposal({ + proposal: _buildProposal(timestamp, int256(i + 1), 5 ether), + maxAmount: TOTAL_BOND + 10 ether + }); + payments[i] = 1 ether; + } + _setBond(); + permit = _buildPermit(3 * (TOTAL_BOND + 10 ether), 42, block.timestamp + 1 hours); + _fundAndApproveProposer(permit.permitted.amount); + } + + function _batchSignature( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + address spender + ) internal view returns (bytes memory) { + // Independently encode the typed array and its nested dependencies, as a wallet would. + bytes32 itemTypeHash = keccak256( + "BatchProposal(Proposal proposal,uint256 maxAmount)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" + ); + bytes32 batchTypeHash = keccak256( + "BatchWitness(BatchProposal[] proposals)BatchProposal(Proposal proposal,uint256 maxAmount)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" + ); + bytes32[] memory hashes = new bytes32[](items.length); + for (uint256 i; i < items.length; ++i) { + hashes[i] = keccak256(abi.encode(itemTypeHash, _computeWitnessHash(items[i].proposal), items[i].maxAmount)); + } + bytes32 witness = keccak256(abi.encode(batchTypeHash, keccak256(abi.encodePacked(hashes)))); + bytes32 permitTypeHash = keccak256( + "PermitWitnessTransferFrom(TokenPermissions permitted,address spender,uint256 nonce,uint256 deadline,BatchWitness witness)BatchProposal(Proposal proposal,uint256 maxAmount)BatchWitness(BatchProposal[] proposals)Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)TokenPermissions(address token,uint256 amount)" + ); + bytes32 structHash = keccak256( + abi.encode( + permitTypeHash, + keccak256(abi.encode(TOKEN_PERMISSIONS_TYPEHASH, permit.permitted)), + spender, + permit.nonce, + permit.deadline, + witness + ) + ); + bytes32 digest = keccak256(abi.encodePacked("\x19\x01", IEIP712(permit2Address).DOMAIN_SEPARATOR(), structHash)); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(proposerKey, digest); + return abi.encodePacked(r, s, v); + } + + function test_proposeBatch_oneSignatureAllSuccessAndRefund() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + currency.mint(address(signedProposer), 7 ether); // Existing payments must not fund or be refunded by this batch. + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertEq(successes.length, 3); + for (uint256 i; i < 3; ++i) { + assertTrue(successes[i]); + assertEq(moo.getRequest(requester, IDENTIFIER, items[i].proposal.timestamp, ANCILLARY).proposer, proposer); + } + assertEq(currency.balanceOf(proposer), 27 ether); + assertEq(currency.balanceOf(address(signedProposer)), 10 ether); + assertEq(currency.allowance(address(signedProposer), address(moo)), 0); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1 << 42); + vm.expectRevert(bytes4(keccak256("InvalidNonce()"))); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, signature, payments); + } + + function test_proposeBatch_collisionRefundsFailedBudgetAndContinues() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + defaultProposerWhitelist.removeFromWhitelist(proposer); + defaultProposerWhitelist.transferOwnership(address(signedProposer)); + items[1].proposal = items[0].proposal; + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.recordLogs(); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(currency.balanceOf(proposer), permit.permitted.amount - 2 * (TOTAL_BOND + 1 ether)); + assertEq(currency.balanceOf(address(signedProposer)), 2 ether); + assertFalse(defaultProposerWhitelist.isOnWhitelist(proposer)); + assertTrue(defaultProposerWhitelist.isOnWhitelist(address(signedProposer))); + assertEq(currency.allowance(address(signedProposer), address(moo)), 0); + Vm.Log[] memory logs = vm.getRecordedLogs(); + uint256 failures; + for (uint256 i; i < logs.length; ++i) { + if ( + logs[i].emitter == address(signedProposer) + && logs[i].topics[0] == keccak256("BatchProposalFailed(uint256,bytes32,bytes4,bytes32)") + ) { + ++failures; + assertEq(uint256(logs[i].topics[1]), 1); + } + } + assertEq(failures, 1); + } + + function test_proposeBatch_allFailRefundsEverythingButConsumesNonce() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + for (uint256 i; i < 3; ++i) { + payments[i] = 6 ether; + } // Above signed maxPayment. + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + for (uint256 i; i < 3; ++i) { + assertFalse(successes[i]); + } + assertEq(currency.balanceOf(proposer), permit.permitted.amount); + assertEq(currency.balanceOf(address(signedProposer)), 0); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1 << 42); + } + + function test_proposeBatch_individualBudgetCannotBorrowFromSibling() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + // Keep the aggregate budget unchanged while making the first item unable to fund its bond. + items[0].maxAmount -= 20 ether; + items[1].maxAmount += 20 ether; + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertFalse(successes[0]); + assertTrue(successes[1]); + assertTrue(successes[2]); + assertEq(currency.balanceOf(proposer), permit.permitted.amount - 2 * (TOTAL_BOND + 1 ether)); + assertEq(currency.balanceOf(address(signedProposer)), 2 ether); + } + + function test_proposeBatch_wrongCurrencyOnlyFailsThatItem() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + ERC20Mock otherCurrency = new ERC20Mock(); + items[1].proposal.oracle = address( + new MaliciousSignedProposerOracle(IERC20(address(otherCurrency)), address(signedProposer), address(this)) + ); + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(currency.balanceOf(proposer), permit.permitted.amount - 2 * (TOTAL_BOND + 1 ether)); + } + + function testFuzz_proposeBatch_rejectsSignedItemTampering(uint8 mutation) public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + mutation = uint8(bound(mutation, 0, 8)); + if (mutation == 0) { + items[0].proposal.oracle = address(1); + } else if (mutation == 1) { + items[0].proposal.requester = address(1); + } else if (mutation == 2) { + items[0].proposal.identifier = bytes32(uint256(1)); + } else if (mutation == 3) { + items[0].proposal.timestamp += 1; + } else if (mutation == 4) { + items[0].proposal.ancillaryData = hex"1234"; + } else if (mutation == 5) { + items[0].proposal.proposedPrice += 1; + } else if (mutation == 6) { + items[0].proposal.maxPayment += 1; + } else if (mutation == 7) { + items[0].maxAmount += 1; + items[1].maxAmount -= 1; + } else { + SignedProposer.BatchProposal memory first = items[0]; + items[0] = items[1]; + items[1] = first; + } + vm.expectRevert(SignatureVerification.InvalidSigner.selector); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 0); + assertEq(currency.balanceOf(proposer), permit.permitted.amount); + } + + function test_proposeBatch_rejectsSignatureForDifferentSpender() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + bytes memory signature = _batchSignature(items, permit, address(123)); + vm.expectRevert(SignatureVerification.InvalidSigner.selector); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, signature, payments); + } + + function test_proposeBatch_refundFailureRevertsFundingNonceAndSuccessfulProposals() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.mockCallRevert(address(currency), abi.encodeCall(IERC20.transfer, (proposer, 27 ether)), hex"1234"); + vm.expectRevert(hex"1234"); + vm.prank(relayer); + signedProposer.proposeBatch(items, proposer, permit, signature, payments); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 0); + assertEq(currency.balanceOf(proposer), permit.permitted.amount); + assertEq(currency.balanceOf(address(signedProposer)), 0); + for (uint256 i; i < 3; ++i) { + assertEq(moo.getRequest(requester, IDENTIFIER, items[i].proposal.timestamp, ANCILLARY).proposer, address(0)); + } + vm.clearMockedCalls(); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, signature, payments); + for (uint256 i; i < 3; ++i) { + assertTrue(successes[i]); + } + } + + function test_proposeBatch_gasExhaustingLastChildRollsBackItsTokenPull() public { + ( + SignedProposer.BatchProposal[] memory items, + ISignatureTransfer.PermitTransferFrom memory permit, + uint256[] memory payments + ) = _prepareSignedBatch(); + MaliciousSignedProposerOracle gasOracle = + new MaliciousSignedProposerOracle(IERC20(address(currency)), address(signedProposer), address(this)); + gasOracle.setBondAmount(TOTAL_BOND); + gasOracle.setExhaustGasAfterTransfer(true); + items[2].proposal.oracle = address(gasOracle); + bytes memory signature = _batchSignature(items, permit, address(signedProposer)); + vm.prank(relayer); + (bool outerSuccess, bytes memory result) = address(signedProposer).call{gas: 30_000_000}( + abi.encodeCall(SignedProposer.proposeBatch, (items, proposer, permit, signature, payments)) + ); + assertTrue(outerSuccess); + bool[] memory successes = abi.decode(result, (bool[])); + assertTrue(successes[0]); + assertTrue(successes[1]); + assertFalse(successes[2]); + assertEq(currency.balanceOf(address(gasOracle)), 0); + assertEq(currency.allowance(address(signedProposer), address(gasOracle)), 0); + assertFalse(gasOracle.whitelist().isOnWhitelist(proposer)); + assertEq(currency.balanceOf(proposer), permit.permitted.amount - 2 * (TOTAL_BOND + 1 ether)); + assertEq(currency.balanceOf(address(signedProposer)), 2 ether); + } + function test_propose_realPermit2Signature() public { uint256 timestamp = block.timestamp; _makeRequest(timestamp, 0); From a4003bc4cb3984853a699fb54cbe907a0e6877c1 Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Tue, 8 Sep 2026 19:26:42 +0200 Subject: [PATCH 4/8] managed-oracle: verify batch capacity and explain witness passes --- script/README.md | 13 +++- .../implementation/SignedProposer.sol | 10 ++- test/SignedProposerPermit2.t.sol | 78 ++++++++++++++++++- 3 files changed, 95 insertions(+), 6 deletions(-) diff --git a/script/README.md b/script/README.md index e513e2d..e77f141 100644 --- a/script/README.md +++ b/script/README.md @@ -396,7 +396,18 @@ Previously retained payments are excluded from the refund. Successful items emit A completed outer transaction consumes the Permit2 nonce **even when every item fails**. Refunds do not restore it: retry failed items using a fresh batch signature and unused nonce. Invalid signatures, malformed batch shape/budgets, a failed Permit2 transfer, or a failed final refund revert the whole transaction, including nonce consumption and any successful proposals. This is a one-shot batch authorization, not an authorization that can be filled over multiple transactions. -Like `tryMulticall`, this method has no per-child gas cap or batch-size constant. An out-of-gas child can starve later items or prevent the outer transaction from finishing; an outer revert rolls everything back. Clients must estimate gas and check calldata size for the actual batch. The 14/15 maximum-ancillary-data boundary documented above applies to the older `tryMulticall` encoding, not this encoding; do not assume that 15–20 items always fit Polygon's transaction-size limit. +Like `tryMulticall`, this method has no per-child gas cap or batch-size constant. An out-of-gas child can starve later items or prevent the outer transaction from finishing; an outer revert rolls everything back. Clients must estimate gas and check calldata size for the actual batch. + +For **8,139 bytes of ancillary data per proposal** and a standard **65-byte EOA Permit2 signature**, `proposeBatch` fits **15 proposals** within Polygon Bor's 131,072-byte transaction-size limit: + +| Proposals | Outer calldata bytes | Result | +|-----------|----------------------|--------| +| 15 | 128,612 | Fits, with 2,460 bytes left for the transaction envelope | +| 16 | 137,156 | Exceeds the limit before adding the envelope | + +The encoding is `452 + 8,544 × proposals` bytes at this ancillary-data/signature size. The capacity test reserves another 512 bytes for an ordinary signed legacy/type-2 transaction without an access list. Larger contract-wallet signatures or access lists require their own size check. Shorter ancillary data allows larger batches. + +`test_proposeBatch_maxAncillaryData_polygonCapacity` uses maximum-length, all-nonzero ancillary data, real Permit2 bytecode, the upgradeable relay, Managed OO, and temporary whitelist insertion/removal for every proposal. All 15 proposals succeed within the repository's 53,902,641 Polygon block gas reference limit (block `81,683,818`), after reserving intrinsic calldata gas. The test also passes with Foundry `--isolate` for separate transaction contexts. This is a local execution/capacity test, not a live Polygon submission or a guarantee of current RPC acceptance. The older `tryMulticall` encoding fits 14 proposals at the same maximum ancillary size because it carries a separate permit and signature for each proposal. #### Constructing the signature in a UI diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 12a041f..10f5c99 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -213,12 +213,15 @@ contract SignedProposer is address proposer, ISignatureTransfer.PermitTransferFrom calldata permit, bytes calldata signature, - uint256[] calldata payments + uint256[] memory payments ) external onlyRole(DELEGATED_PROPOSER_ROLE) nonReentrant returns (bool[] memory successes) { uint256 length = proposals.length; if (length == 0) revert EmptyBatch(); if (length != payments.length) revert BatchLengthMismatch(); + // Permit2 needs the full ordered witness before it can authenticate and fund the batch. + // This first pass hashes each item once and checks the total budget; the second executes + // the funded items. A permissioned relayer must still prove the signer's exact authorization. bytes32[] memory hashes = new bytes32[](length); uint256 totalBudget; for (uint256 i; i < length; ++i) { @@ -232,7 +235,8 @@ contract SignedProposer is _permit2Transfer(permit, proposer, signature, witness, BATCH_WITNESS_TYPE_STRING); IERC20 currency = IERC20(permit.permitted.token); - uint256 refund = totalBudget; + // Deduct only successful bond + payment spends; failed budgets remain refundable. + uint256 refund = permit.permitted.amount; successes = new bool[](length); for (uint256 i; i < length; ++i) { try this.executeBatchProposal(proposals[i], proposer, currency, payments[i]) returns (uint256 spent) { @@ -244,7 +248,7 @@ contract SignedProposer is } } if (refund > 0) currency.safeTransfer(proposer, refund); - emit BatchExecuted(proposer, address(currency), permit.nonce, totalBudget - refund, refund); + emit BatchExecuted(proposer, address(currency), permit.nonce, permit.permitted.amount - refund, refund); } /// @dev Only the funded batch may enter this call boundary. The outer nonReentrant guard stays diff --git a/test/SignedProposerPermit2.t.sol b/test/SignedProposerPermit2.t.sol index 2860d01..b950807 100644 --- a/test/SignedProposerPermit2.t.sol +++ b/test/SignedProposerPermit2.t.sol @@ -240,7 +240,13 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { internal returns (bool transactionSucceeded, bool[] memory successes) { - bytes memory transactionData = abi.encodeCall(TryMulticall.tryMulticall, (calls)); + return _executeWithinPolygonBlock(abi.encodeCall(TryMulticall.tryMulticall, (calls))); + } + + function _executeWithinPolygonBlock(bytes memory transactionData) + internal + returns (bool transactionSucceeded, bool[] memory successes) + { uint256 intrinsicGas = _transactionIntrinsicGas(transactionData); if (intrinsicGas >= POLYGON_BLOCK_GAS_LIMIT) return (false, successes); @@ -592,7 +598,7 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { ) = _prepareSignedBatch(); bytes memory signature = _batchSignature(items, permit, address(signedProposer)); vm.mockCallRevert(address(currency), abi.encodeCall(IERC20.transfer, (proposer, 27 ether)), hex"1234"); - vm.expectRevert(hex"1234"); + vm.expectRevert(bytes(hex"1234")); vm.prank(relayer); signedProposer.proposeBatch(items, proposer, permit, signature, payments); assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 0); @@ -886,6 +892,74 @@ contract SignedProposerPermit2Test is Test, DeployPermit2 { assertEq(moo.getRequest(requester, IDENTIFIER, timestamp, ANCILLARY).proposedPrice, 2 ether); } + function test_proposeBatch_maxAncillaryData_polygonCapacity() public { + uint256 maxBatch = 15; + bytes memory ancillaryData = _maximallyPricedAncillaryData(); + assertEq(ancillaryData.length, 8_139); + vm.warp(block.timestamp + maxBatch + 1); + SignedProposer.BatchProposal[] memory boundary = new SignedProposer.BatchProposal[](maxBatch); + SignedProposer.BatchProposal[] memory oversized = new SignedProposer.BatchProposal[](maxBatch + 1); + for (uint256 i; i < oversized.length; ++i) { + uint256 timestamp = block.timestamp - i; + _makeRequest(timestamp, 0, ancillaryData); + oversized[i] = + SignedProposer.BatchProposal(_buildProposal(timestamp, int256(i + 1), 0, ancillaryData), TOTAL_BOND); + if (i < maxBatch) boundary[i] = oversized[i]; + } + _setBond(ancillaryData); + _fundAndApproveProposer(TOTAL_BOND * maxBatch); + // Include temporary whitelist insertion/removal for every successful item. + defaultProposerWhitelist.removeFromWhitelist(proposer); + defaultProposerWhitelist.transferOwnership(address(signedProposer)); + + ISignatureTransfer.PermitTransferFrom memory permit = + _buildPermit(TOTAL_BOND * maxBatch, 43, block.timestamp + 1 hours); + bytes memory boundaryData = abi.encodeCall( + SignedProposer.proposeBatch, + ( + boundary, + proposer, + permit, + _batchSignature(boundary, permit, address(signedProposer)), + new uint256[](maxBatch) + ) + ); + permit.permitted.amount += TOTAL_BOND; + bytes memory oversizedData = abi.encodeCall( + SignedProposer.proposeBatch, + ( + oversized, + proposer, + permit, + _batchSignature(oversized, permit, address(signedProposer)), + new uint256[](maxBatch + 1) + ) + ); + + // For 65-byte EOA signatures: 452 fixed bytes + 8,544 bytes per maximum-sized item. + assertEq(boundaryData.length, 128_612); + assertEq(oversizedData.length, 137_156); + // Leave ample room for an ordinary signed legacy/type-2 envelope without an access list. + assertLt(boundaryData.length + 512, BOR_MAX_TRANSACTION_BYTES); + // The next batch already exceeds Bor's 128 KiB limit before adding the transaction envelope. + assertGt(oversizedData.length, BOR_MAX_TRANSACTION_BYTES); + (bool outerSuccess, bool[] memory successes) = _executeWithinPolygonBlock(boundaryData); + uint256 executionGas = vm.lastCallGas().gasTotalUsed; + assertTrue(_allSucceeded(outerSuccess, successes, maxBatch)); + assertEq(currency.balanceOf(proposer), 0); + assertEq(currency.balanceOf(address(signedProposer)), 0); + assertEq(currency.allowance(address(signedProposer), address(moo)), 0); + assertFalse(defaultProposerWhitelist.isOnWhitelist(proposer)); + assertEq(ISignatureTransfer(permit2Address).nonceBitmap(proposer, 0), 1 << 43); + + emit log_named_uint("max ancillary bytes per proposal", ancillaryData.length); + emit log_named_uint("largest successful proposal batch", maxBatch); + emit log_named_uint("15 proposal calldata bytes", boundaryData.length); + emit log_named_uint("batch execution gas (excluding intrinsic gas)", executionGas); + emit log_named_uint("16 proposal calldata bytes", oversizedData.length); + emit log_named_uint("Polygon block gas limit", POLYGON_BLOCK_GAS_LIMIT); + } + function test_tryMulticall_maxAncillaryData_polygonBlockCapacity() public { bytes memory ancillaryData = _maximallyPricedAncillaryData(); assertEq(ancillaryData.length, moo.OO_ANCILLARY_DATA_LIMIT()); From 621b4d3788e2c2437aee994d1f303b8a3d57ad51 Mon Sep 17 00:00:00 2001 From: Chris Maree Date: Mon, 28 Sep 2026 17:14:08 +0200 Subject: [PATCH 5/8] managed-oracle: bound proposal batch revert data --- script/README.md | 2 +- .../implementation/SignedProposer.sol | 37 +++++++++-- test/SignedProposer.t.sol | 62 +++++++++++++++++++ 3 files changed, 95 insertions(+), 6 deletions(-) diff --git a/script/README.md b/script/README.md index 964f872..acc2da7 100644 --- a/script/README.md +++ b/script/README.md @@ -404,7 +404,7 @@ The contract pulls the full budget once, verifies the exact token receipt, and a permit.permitted.amount - sum(successful actual bonds + successful payments) ``` -Previously retained payments are excluded from the refund. Successful items emit `ProposalExecuted`; failed items emit `BatchProposalFailed(index, proposalHash, errorSelector, revertDataHash)`, where `proposalHash` is the EIP-712 struct hash of the signed `BatchProposal` item. The function returns a matching `bool[]`, and `BatchExecuted(proposer, token, nonce, spent, refund)` summarizes the batch. Full signatures and ancillary data are not logged by these batch events. `BatchProposalFailed.revertDataHash` hashes the complete child revert data; the external self-call catch copies that data without a size cap. Large revert payloads can therefore exhaust outer gas. The separate `tryMulticall` entry point caps copied revert data at 256 bytes. +Previously retained payments are excluded from the refund. Successful items emit `ProposalExecuted`; failed items emit `BatchProposalFailed(index, proposalHash, errorSelector, revertDataHash)`, where `proposalHash` is the EIP-712 struct hash of the signed `BatchProposal` item. The function returns a matching `bool[]`, and `BatchExecuted(proposer, token, nonce, spent, refund)` summarizes the batch. Full signatures and ancillary data are not logged by these batch events. `BatchProposalFailed.revertDataHash` hashes at most the first 256 bytes of child revert data, matching the bounded-copy policy of `tryMulticall`. Longer payloads are truncated before copying and hashing in the parent; errors shorter than four bytes have a zero error selector. This bounds failure-metadata processing, but does not cap child execution gas. A completed outer transaction consumes the Permit2 nonce **even when every item fails**. Refunds do not restore it: retry failed items using a fresh batch signature and unused nonce. Invalid signatures, malformed batch shape/budgets, a failed Permit2 transfer, or a failed final refund revert the whole transaction, including nonce consumption and any successful proposals. This is a one-shot batch authorization, not an authorization that can be filled over multiple transactions. diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 2281dda..73e2ef8 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -82,6 +82,8 @@ contract SignedProposer is // ─── Constants ──────────────────────────────────────────────────────────────── + uint256 private constant MAX_BATCH_REVERT_DATA_SIZE = 256; + bytes32 public constant PROPOSAL_TYPEHASH = keccak256( "Proposal(address oracle,address requester,bytes32 identifier,uint256 timestamp,bytes ancillaryData,int256 proposedPrice,uint256 maxPayment)" ); @@ -118,6 +120,7 @@ contract SignedProposer is event PaymentWithdrawn(address indexed token, address indexed to, uint256 amount); + /// @dev revertDataHash hashes at most the first 256 bytes of child revert data. event BatchProposalFailed( uint256 indexed index, bytes32 indexed proposalHash, bytes4 errorSelector, bytes32 revertDataHash ); @@ -246,12 +249,36 @@ contract SignedProposer is uint256 refund = permit.permitted.amount; successes = new bool[](length); for (uint256 i; i < length; ++i) { - try this.executeBatchProposal(proposals[i], proposer, currency, payments[i]) returns (uint256 spent) { - successes[i] = true; + bytes memory callData = + abi.encodeCall(this.executeBatchProposal, (proposals[i], proposer, currency, payments[i])); + bool success; + uint256 spent; + bytes4 errorSelector; + bytes32 revertDataHash; + // Avoid allocating the complete child revert payload in the parent frame. + assembly ("memory-safe") { + success := call(gas(), address(), 0, add(callData, 0x20), mload(callData), 0, 0) + switch success + case 1 { + // The self-only helper returns exactly one uint256; never accept a missing spend value. + if iszero(eq(returndatasize(), 0x20)) { revert(0, 0) } + returndatacopy(0, 0, 0x20) + spent := mload(0) + } + default { + let size := returndatasize() + if gt(size, MAX_BATCH_REVERT_DATA_SIZE) { size := MAX_BATCH_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) { refund -= spent; - } catch (bytes memory reason) { - bytes4 errorSelector = reason.length >= 4 ? bytes4(reason) : bytes4(0); - emit BatchProposalFailed(i, hashes[i], errorSelector, keccak256(reason)); + } else { + emit BatchProposalFailed(i, hashes[i], errorSelector, revertDataHash); } } if (refund > 0) currency.safeTransfer(proposer, refund); diff --git a/test/SignedProposer.t.sol b/test/SignedProposer.t.sol index a579d40..876d460 100644 --- a/test/SignedProposer.t.sol +++ b/test/SignedProposer.t.sol @@ -61,6 +61,10 @@ contract SignedProposerTest is Test { uint256 indexed index, bytes32 indexed callHash, bytes4 errorSelector, bytes32 revertDataHash ); + event BatchProposalFailed( + uint256 indexed index, bytes32 indexed proposalHash, bytes4 errorSelector, bytes32 revertDataHash + ); + SignedProposer internal signedProposer; ManagedOptimisticOracleV2 internal moo; MockPermit2 internal mockPermit2; @@ -334,6 +338,64 @@ contract SignedProposerTest is Test { assertEq(shortToken.balanceOf(proposer), 100 ether); } + function test_proposeBatch_boundsRevertDataAndPreservesSiblings() public { + uint256[6] memory sizes = [uint256(0), 3, 4, 256, 257, 512 * 1024]; + for (uint256 i; i < sizes.length; ++i) { + _batchWithRevertData(sizes[i]); + } + } + + function _batchWithRevertData(uint256 revertDataSize) internal { + vm.warp(block.timestamp + 2); + uint256 firstTimestamp = block.timestamp - 1; + uint256 lastTimestamp = block.timestamp; + _makeRequest(firstTimestamp, 0); + _makeRequest(lastTimestamp, 0); + _setBond(); + _fundAndApproveProposer(TOTAL_BOND * 3); + uint256 proposerBalanceBefore = currency.balanceOf(proposer); + currency.mint(address(signedProposer), 7 ether); + uint256 retainedBalanceBefore = currency.balanceOf(address(signedProposer)); + + SignedProposer.BatchProposal[] memory items = new SignedProposer.BatchProposal[](3); + items[0] = SignedProposer.BatchProposal(_buildProposal(firstTimestamp, 1 ether), TOTAL_BOND); + items[1] = SignedProposer.BatchProposal( + _buildRevertingProposal(false, revertDataSize, firstTimestamp, 9 ether), TOTAL_BOND + ); + items[2] = SignedProposer.BatchProposal(_buildProposal(lastTimestamp, 2 ether), TOTAL_BOND); + ISignatureTransfer.PermitTransferFrom memory permit = _buildPermit(TOTAL_BOND * 3, 0, block.timestamp + 1 hours); + bytes memory prefix = new bytes(revertDataSize > 256 ? 256 : revertDataSize); + for (uint256 i; i < prefix.length; ++i) { + prefix[i] = bytes1(uint8(i % 251 + 1)); + } + SignedProposer.Proposal memory proposal = items[1].proposal; + bytes32 proposalHash = keccak256( + abi.encode( + signedProposer.PROPOSAL_TYPEHASH(), + proposal.oracle, + proposal.requester, + proposal.identifier, + proposal.timestamp, + keccak256(proposal.ancillaryData), + proposal.proposedPrice, + proposal.maxPayment + ) + ); + bytes32 itemHash = keccak256(abi.encode(signedProposer.BATCH_PROPOSAL_TYPEHASH(), proposalHash, TOTAL_BOND)); + vm.expectEmit(true, true, false, true, address(signedProposer)); + emit BatchProposalFailed(1, itemHash, revertDataSize >= 4 ? bytes4(0x01020304) : bytes4(0), keccak256(prefix)); + vm.prank(relayer); + bool[] memory successes = signedProposer.proposeBatch(items, proposer, permit, "", new uint256[](3)); + assertTrue(successes[0]); + assertFalse(successes[1]); + assertTrue(successes[2]); + assertEq(moo.getRequest(requester, IDENTIFIER, firstTimestamp, ANCILLARY).proposedPrice, 1 ether); + assertEq(moo.getRequest(requester, IDENTIFIER, lastTimestamp, ANCILLARY).proposedPrice, 2 ether); + assertEq(currency.balanceOf(proposer), proposerBalanceBefore - 2 * TOTAL_BOND); + assertEq(currency.balanceOf(address(signedProposer)), retainedBalanceBefore); + assertEq(currency.allowance(address(signedProposer), address(moo)), 0); + } + function test_proposeBatch_blocksReentrantSingleProposal() public { _batchWithReentrantCallback(false); } From 1ff247e4e94842c7b199fd5e09fa21ae71eaf20f Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 5 Oct 2026 13:07:18 +0200 Subject: [PATCH 6/8] docs: document trusted batch relayers (L-05) (#89) --- src/optimistic-oracle-v2/implementation/SignedProposer.sol | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 73e2ef8..e8f4335 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -38,7 +38,8 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * * The contract is permissioned: * - `DEFAULT_ADMIN_ROLE` — manages roles, payments, whitelist ownership, and upgrades. - * - `DELEGATED_PROPOSER_ROLE` — may call `propose`, `proposeBatch`, and `tryMulticall`. + * - `DELEGATED_PROPOSER_ROLE` — fully trusted, company-controlled relayers that may call + * `propose`, `proposeBatch`, 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 @@ -210,6 +211,10 @@ contract SignedProposer is * successful bonds/payments are charged, and all unused funds are refunded once at the end. * A completed batch consumes its nonce even if every child fails. Invalid signatures, invalid * batch shape/funding, a failed final refund, or insufficient outer gas revert the whole batch. + * Delegated relayers are fully trusted to select per-item payments and supply sufficient gas. + * A payment above maxPayment, or one leaving insufficient budget for the bond, fails that item + * without reverting the batch. Such failures, including relayer mistakes, consume the shared + * nonce on batch completion; unused funds are refunded and retries require a fresh signature. * As with tryMulticall, there is no per-child gas cap or guarantee against gas starvation. * @param proposals Signed proposal fields and bond-plus-payment budgets, in execution order. * @param proposer Signer, token owner, and refund recipient for the entire batch. From d98912b2a87b6987e1eb2df65efdaf01c4d6799c Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 5 Oct 2026 13:07:29 +0200 Subject: [PATCH 7/8] perf: read batch payments from calldata (N-03) (#90) --- src/optimistic-oracle-v2/implementation/SignedProposer.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index e8f4335..822b50c 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -228,7 +228,7 @@ contract SignedProposer is address proposer, ISignatureTransfer.PermitTransferFrom calldata permit, bytes calldata signature, - uint256[] memory payments + uint256[] calldata payments ) external onlyRole(DELEGATED_PROPOSER_ROLE) nonReentrant returns (bool[] memory successes) { uint256 length = proposals.length; if (length == 0) revert EmptyBatch(); From cb82a63bd07b1176f55e8973a30148953a6d504d Mon Sep 17 00:00:00 2001 From: Pablo Maldonado Date: Mon, 5 Oct 2026 13:07:40 +0200 Subject: [PATCH 8/8] docs: describe batching entry points (N-04) (#91) --- src/optimistic-oracle-v2/implementation/SignedProposer.sol | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/optimistic-oracle-v2/implementation/SignedProposer.sol b/src/optimistic-oracle-v2/implementation/SignedProposer.sol index 822b50c..1e9173b 100644 --- a/src/optimistic-oracle-v2/implementation/SignedProposer.sol +++ b/src/optimistic-oracle-v2/implementation/SignedProposer.sol @@ -46,7 +46,11 @@ import {TryMulticall} from "../../common/implementation/TryMulticall.sol"; * preserves `msg.sender`, so every externally reachable function must enforce its own authorization, including functions * added in future versions. The `multicall` 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. + * nested partial-success batches. Each `tryMulticall` child uses its own permit and nonce; failed children preserve their + * permits. `proposeBatch` restricts the caller to delegated proposers and holds a reentrancy guard across an ordered, + * same-token batch for one signer. It funds the batch with one Permit2 signature and nonce, isolates child failures, and + * refunds unused funds at completion. A completed batch consumes the shared nonce even if every child fails; retries + * require a fresh signature. These restrictions do not apply to the atomic `multicall` entry point. */ contract SignedProposer is AccessControlUpgradeable,