Skip to content
Verified contractExactMIT

BatchExecutor

Address0x18057ce3aef55c63cc7fd0500a4c09d1850b2c22
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.39

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.39+commit.ce47f2c8
Language
solidity
Optimization
No
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,457,431
Creation transaction
0x049be26e5c…ce63b0172d

contracts/BatchExecuter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.39;
import {ECDSA} from "./vendor/openzeppelin/ECDSA.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
/**
 * @title BatchExecutor
 * @notice EIP-7702 delegate that lets an EOA run several calls atomically in one transaction.
 *
 * SECURITY MODEL
 *  - Funds can move only through `execute`, and `execute` runs only when the account calls itself,
 *    i.e. the EOA signs and sends a normal transaction to its own address. There is no
 *    signature-based execution, no relayer path, no owner, no admin, no initializer and no upgrade
 *    path, so no off-chain signature can make this contract move funds. Signatures that other
 *    protocols check through `isValidSignature` (e.g. Permit2 permits) work as for a plain EOA.
 *  - Replay protection is the EOA's own transaction nonce and the transaction's chain ID. There is
 *    deliberately no `block.chainid` check: nothing here is signed off-chain, and every transaction
 *    and EIP-7702 authorization the user signs already carries the chain ID.
 *  - The contract reads and writes no storage. Nothing can be front-run after delegation, and storage
 *    left in the account by a previous delegate (e.g. the old `nonce` in slot 0) is never read. A
 *    future version that needs storage must use ERC-7201 namespaced slots so it cannot collide.
 *  - `isValidSignature` (ERC-1271) accepts only 65-byte, low-s signatures by the EOA's own key. That
 *    is a subset of what ecrecover accepts for a plain EOA (no 64-byte EIP-2098 or high-s
 *    signatures), so delegating never widens what signatures are valid for the account.
 *  - There is no fallback: a call with unknown calldata reverts. That includes ETH sent with
 *    non-empty calldata, which a plain EOA would accept, and unknown callbacks (flash loans,
 *    ERC-1363, ERC-777), which fail instead of silently succeeding. Plain ETH is accepted.
 *  - The implementation address itself refuses ETH and tokens, so nothing can get stuck there.
 *
 * DEPLOYMENT (outside this contract, but required for the model above to hold)
 *  - Deploy with CREATE2 via the deterministic deployment proxy so this address holds this exact
 *    bytecode on every chain and nobody can place different code at it on another chain.
 *  - Compile with pinned settings (solc 0.8.38, evm_version prague, fixed optimizer and metadata
 *    settings) so the init code, and therefore the address, is identical on every chain.
 *  - Sign every EIP-7702 authorization with the explicit chain ID. Never use chain ID 0.
 */
contract BatchExecutor is IERC721Receiver, IERC1155Receiver, IERC1271 {
    /// @notice A single call within a batch.
    struct Call {
        address to;
        uint256 value;
        bytes data;
    }
    /// @notice Upper bound on calls per batch, so a dApp-supplied batch cannot become an unbounded tx.
    uint256 public constant MAX_CALLS = 32;
    /// @notice At most this many bytes of a failed call's revert data are kept in `CallFailed`.
    uint256 public constant MAX_REVERT_DATA = 1024;
    /// @dev The implementation's own address. Code running in a delegated account sees the account
    ///      as `address(this)`, so `address(this) == SELF` only on the implementation itself.
    address private immutable SELF = address(this);
    /// @notice Emitted for every call executed. The log's emitter address is the account itself.
    event CallExecuted(uint256 index, address indexed to, uint256 value, bytes4 selector);
    /// @notice `execute` was called by anyone other than the account itself.
    error Unauthorized();
    /// @notice The batch has no calls.
    error EmptyBatch();
    /// @notice The batch has more than MAX_CALLS calls.
    error TooManyCalls(uint256 count, uint256 max);
    /// @notice A call targets the zero address or the account itself.
    error InvalidTarget(uint256 index, address to);
    /// @notice A call reverted; the whole batch is reverted with its index and (capped) revert data.
    error CallFailed(uint256 index, bytes reason);
    /// @notice An ERC-20 transfer, transferFrom or approve returned false instead of reverting.
    error TokenCallReturnedFalse(uint256 index, address to);
    /// @notice ETH or a token was sent to the implementation address instead of a delegated account.
    error NotDelegated();
    /// @dev Refuses ETH and tokens sent to the implementation address, where they would be stuck.
    modifier onlyDelegated() {
        if (address(this) == SELF) revert NotDelegated();
        _;
    }
    /**
     * @notice Executes a batch of calls atomically. If any call fails, the whole batch reverts.
     * @dev Only the account itself can call this (msg.sender == address(this)). A callee cannot call
     *      back into it, because its msg.sender would be the callee, and the batch cannot target the
     *      account itself. `payable` only so a wallet that attaches value does not revert: in a
     *      self-transaction msg.value moves from the account to itself, so nothing is lost.
     * @param calls The calls to make, in order.
     */
    function execute(Call[] calldata calls) external payable {
        if (msg.sender != address(this)) revert Unauthorized();
        uint256 count = calls.length;
        if (count == 0) revert EmptyBatch();
        if (count > MAX_CALLS) revert TooManyCalls(count, MAX_CALLS);
        for (uint256 i; i < count; ++i) {
            _executeCall(i, calls[i]);
        }
    }
    /**
     * @notice ERC-1271: valid only for a 65-byte, low-s signature over `hash` by the account's own key.
     * @dev Slightly stricter than ecrecover against a plain EOA: 64-byte (EIP-2098) and high-s
     *      signatures are rejected. Protocols that switch to ERC-1271 once the account has code
     *      (Permit2, OpenZeppelin SignatureChecker) accept a subset of what they accepted before
     *      delegation, never more. Domain separation (chain ID, verifying contract) is part of the
     *      hash that the verifying protocol computes, exactly as for a plain EOA.
     */
    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4) {
        (address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(hash, signature);
        if (err == ECDSA.RecoverError.NoError && recovered == address(this)) {
            return IERC1271.isValidSignature.selector;
        }
        return 0xffffffff;
    }
    /// @notice Accept ERC-721 tokens sent with safeTransferFrom, as a plain EOA would.
    function onERC721Received(address, address, uint256, bytes calldata)
        external
        view
        onlyDelegated
        returns (bytes4)
    {
        return IERC721Receiver.onERC721Received.selector;
    }
    /// @notice Accept ERC-1155 tokens sent with safeTransferFrom, as a plain EOA would.
    function onERC1155Received(address, address, uint256, uint256, bytes calldata)
        external
        view
        onlyDelegated
        returns (bytes4)
    {
        return IERC1155Receiver.onERC1155Received.selector;
    }
    /// @notice Accept ERC-1155 tokens sent with safeBatchTransferFrom, as a plain EOA would.
    function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
        external
        view
        onlyDelegated
        returns (bytes4)
    {
        return IERC1155Receiver.onERC1155BatchReceived.selector;
    }
    /// @notice ERC-165: ERC-165, ERC-721 receiver, ERC-1155 receiver and ERC-1271.
    function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
        return interfaceId == type(IERC165).interfaceId
            || interfaceId == type(IERC721Receiver).interfaceId
            || interfaceId == type(IERC1155Receiver).interfaceId
            || interfaceId == type(IERC1271).interfaceId;
    }
    /// @notice Accept plain ETH transfers (no calldata), e.g. from DEX swaps or WETH withdrawals.
    receive() external payable onlyDelegated {}
    /**
     * @dev Executes one call of the batch.
     *      The call is made in assembly with no output buffer, so return data is never copied on
     *      success: a callee returning a huge blob cannot inflate the batch's gas. On failure at most
     *      MAX_REVERT_DATA bytes are copied. ERC-20 transfer/transferFrom/approve that return false
     *      instead of reverting fail the batch, as SafeERC20 would; ERC-721 shares the approve and
     *      transferFrom selectors but returns nothing, so it is unaffected.
     * @param index Position of the call in the batch, reported in errors and events.
     * @param callItem The call to make.
     */
    function _executeCall(uint256 index, Call calldata callItem) private {
        address to = callItem.to;
        if (to == address(0) || to == address(this)) revert InvalidTarget(index, to);
        bytes calldata data = callItem.data;
        uint256 value = callItem.value;
        bool success;
        bool returnedFalse;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, data.offset, data.length)
            success := call(gas(), to, value, ptr, data.length, 0, 0)
            // Read the result only when it is exactly one word (a bool), into scratch space.
            if and(success, eq(returndatasize(), 0x20)) {
                returndatacopy(0x00, 0x00, 0x20)
                returnedFalse := iszero(mload(0x00))
            }
        }
        if (!success) revert CallFailed(index, _revertData());
        bytes4 selector = bytes4(data);
        if (
            returnedFalse
                && (
                    selector == IERC20.transfer.selector || selector == IERC20.transferFrom.selector
                        || selector == IERC20.approve.selector
                )
        ) revert TokenCallReturnedFalse(index, to);
        emit CallExecuted(index, to, value, selector);
    }
    /// @dev The last call's revert data, cut at MAX_REVERT_DATA bytes.
    function _revertData() private pure returns (bytes memory reason) {
        uint256 maxSize = MAX_REVERT_DATA;
        assembly ("memory-safe") {
            let size := returndatasize()
            if gt(size, maxSize) { size := maxSize }
            reason := mload(0x40)
            mstore(reason, size)
            returndatacopy(add(reason, 0x20), 0x00, size)
            mstore(0x40, add(add(reason, 0x20), and(add(size, 0x1f), not(0x1f))))
        }
    }
}

@openzeppelin/contracts/interfaces/IERC1271.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1271.sol)

pragma solidity >=0.5.0;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with `hash`
     */
    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue);
}

@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity >=0.6.2;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contracts/vendor/openzeppelin/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/ECDSA.sol)
// Vendored from @openzeppelin/[email protected]; local identifiers named `error`
// are renamed to `recoverError` for Solidity compiler compatibility.

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature is invalid.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     *
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Variant of {tryRecover} that takes a signature in calldata
     */
    function tryRecoverCalldata(
        bytes32 hash,
        bytes calldata signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, calldata slices would work here, but are
            // significantly more expensive (length check) than using calldataload in assembly.
            assembly ("memory-safe") {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError recoverError, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(recoverError, errorArg);
        return recovered;
    }

    /**
     * @dev Variant of {recover} that takes a signature in calldata
     */
    function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
        (address recovered, RecoverError recoverError, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
        _throwError(recoverError, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError recoverError, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(recoverError, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError recoverError, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(recoverError, errorArg);
        return recovered;
    }

    /**
     * @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
     * formats. Returns (0,0,0) for invalid signatures.
     *
     * For 64-byte signatures, `v` is automatically normalized to 27 or 28.
     * For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
     *
     * Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
     */
    function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch mload(signature)
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := mload(add(signature, 0x20))
                r := mload(add(signature, 0x20))
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Variant of {parse} that takes a signature in calldata
     */
    function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch signature.length
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := calldataload(add(signature.offset, 0x20))
                r := calldataload(signature.offset)
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError recoverError, bytes32 errorArg) private pure {
        if (recoverError == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (recoverError == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (recoverError == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (recoverError == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.