Skip to content
Verified contractPartialMIT

AggregatorProver

Address0xec0d2ce6b827b29561c8e65dd8d793f5bd433028
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,188,698
Creation transaction
0x5e9913c08a…91dd8e6e12

contracts/prover/AggregatorProver.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IProver} from "../interfaces/IProver.sol";
import {Semver} from "../libs/Semver.sol";
import {Whitelist} from "../libs/Whitelist.sol";
import {AddressConverter} from "../libs/AddressConverter.sol";

/**
 * @title AggregatorProver
 * @notice Reports an intent as proven when ANY member prover has proven it
 * @dev Stateless 1-of-N union over an immutable set of member provers. Records
 *      no proofs of its own and dispatches no messages: solvers prove through a
 *      concrete member via Portal.prove, and this contract only reads the
 *      results on the source chain.
 *
 *      SECURITY: union semantics mean the security floor is the WEAKEST member.
 *      A compromised member can forge a claimant and drain any vault whose
 *      intent names this aggregator. Membership is immutable and cannot be
 *      ejected; member selection is the security-critical decision.
 *
 *      Reuses Whitelist as an immutable ordered address set. Elsewhere in this
 *      repo Whitelist holds REMOTE cross-VM prover addresses; here it holds
 *      LOCAL EVM member contracts.
 */
/// @dev Whitelist's getWhitelist()/getWhitelistSize()/isWhitelisted() carry a
///      DIFFERENT meaning here than on every other IProver implementation: on
///      those, "whitelisted" means a trusted remote cross-VM prover address;
///      here it means a local EVM member of the 1-of-N union. Off-chain
///      tooling that reads isWhitelisted() uniformly across IProver
///      implementations will misread this contract.
///
/// @dev WARNING: this address must NEVER be used as a bridge message
///      recipient. `data.sourceChainProver` in a `Portal.prove` /
///      `fulfillAndProve` call must be one of `getMembers()` resolved on the
///      SOURCE chain, never `reward.prover` (which may legitimately be this
///      aggregator). `AggregatorProver` implements no `handle`, no `lzReceive`, and
///      no fallback, so delivery to it reverts on an unknown selector
///      forever — permanently stranding the message. For every other prover,
///      CREATE3 parity makes `reward.prover` the correct recipient too, which
///      makes this a real footgun: the pattern that works for every other
///      prover silently does not work here.
contract AggregatorProver is IProver, ERC165, Whitelist, Semver {
    using AddressConverter for bytes32;

    /// @notice Proof mechanism identifier
    string public constant PROOF_TYPE = "Aggregator";

    /// @notice Maximum members; tighter than Whitelist's 20 because every
    ///         member costs a call on both withdraw and refund
    uint256 public constant MAX_MEMBERS = 8;

    /// @notice prove() is not supported; route through a concrete member
    error ProvingNotSupported();

    /// @notice Member set is empty or exceeds MAX_MEMBERS
    error InvalidMemberSet(uint256 size, uint256 maxSize);

    /// @notice Member is zero or not a valid EVM address
    error InvalidMember(bytes32 member);

    /// @notice Member appears more than once in the set
    error DuplicateMember(bytes32 member);

    /// @notice Thrown when a member has no code on this chain at construction
    error MemberHasNoCode(address member);

    /// @notice Emitted once per member at construction, so the immutable,
    ///         setter-less set is auditable after deploy
    /// @param member Member prover address
    /// @param priority Index in the set; lower wins on conflict
    event MemberRegistered(address indexed member, uint256 indexed priority);

    /// @notice Emitted when a challenge was RELAYED to members
    /// @dev Does not imply anything was invalidated; a member that deletes an
    ///      entry emits its own IntentProofInvalidated
    event ChallengeForwarded(bytes32 indexed intentHash);

    /**
     * @notice Initializes the aggregator with an ordered, immutable member set
     * @dev Validates the `members` MEMORY PARAMETER, never getWhitelist():
     *      immutables cannot be read during construction.
     *      Whitelist's constructor runs first, so a set larger than its own
     *      20-address cap reverts with WhitelistSizeExceeded, not
     *      InvalidMemberSet.
     *
     *      The `isValidAddress` check below is the ONLY reason the unguarded
     *      `toAddress()` calls in getMembers/provenIntents/challengeIntentProof
     *      never revert; loosening it would make all three revert-capable and
     *      break IntentSource.batchWithdraw's per-intent isolation.
     * @param members Member prover addresses as bytes32, in priority order
     */
    constructor(bytes32[] memory members) Whitelist(members) {
        uint256 length = members.length;

        if (length == 0 || length > MAX_MEMBERS) {
            revert InvalidMemberSet(length, MAX_MEMBERS);
        }

        for (uint256 i = 0; i < length; ++i) {
            bytes32 member = members[i];

            if (member == bytes32(0) || !member.isValidAddress()) {
                revert InvalidMember(member);
            }

            // O(n^2) over a constructor-only list of at most MAX_MEMBERS
            for (uint256 j = 0; j < i; ++j) {
                if (members[j] == member) {
                    revert DuplicateMember(member);
                }
            }

            address memberAddr = member.toAddress();

            // Fail closed here so the read paths do not have to guard at
            // runtime. A codeless member would otherwise be skipped forever by
            // provenIntents (silently shrinking the trust set to fewer members
            // than the operator believes they configured) and would revert
            // challengeIntentProof outright, since solc's extcodesize check on
            // a void high-level call lands in THIS frame, outside the catch.
            //
            // Checking once at construction is sound because code cannot
            // disappear afterwards: post-EIP-6780 SELFDESTRUCT only clears code
            // when it runs in the same transaction that created the contract,
            // and no chain this aggregator targets predates Cancun. There is no
            // AggregatorProverTron variant; TRON deploys via scripts/tron.
            //
            // Consequence, deliberately accepted: on a chain where a member is
            // not live yet, deployment REVERTS rather than silently deploying a
            // smaller set at the same address.
            if (memberAddr.code.length == 0) {
                revert MemberHasNoCode(memberAddr);
            }

            emit MemberRegistered(memberAddr, i);
        }
    }

    /**
     * @notice Returns the member provers in priority order
     */
    function getMembers() external view returns (address[] memory) {
        bytes32[] memory members = getWhitelist();
        uint256 length = members.length;
        address[] memory result = new address[](length);

        for (uint256 i = 0; i < length; ++i) {
            result[i] = members[i].toAddress();
        }

        return result;
    }

    /**
     * @notice Returns the first member proof with a non-zero claimant
     * @dev Iterates members in immutable priority order. Members that are
     *      codeless, revert, or return a zero claimant are skipped and never
     *      propagated: a zero-claimant success must fall through to the next
     *      member, not terminate the search.
     *
     *      The `code.length` guard closes the CODELESS case: a staticcall to a
     *      codeless address SUCCEEDS with empty returndata, and ABI-decoding
     *      empty data would revert in THIS frame where try/catch cannot catch
     *      it. Without it, a member deployed only on other chains would brick
     *      withdraw AND refund for every intent naming this aggregator.
     *      Mirrors the same defense at IntentSource.sol:872-880.
     *
     *      The call below is a low-level staticcall, not an interface call,
     *      and the read path is revert-free for ANY 64-byte payload, honest or
     *      not. A non-dynamic ProofData{address; uint64;} ABI-encodes to
     *      exactly 64 bytes, so `ret.length == 64` closes the WRONG-SHAPE case
     *      first: a code-bearing member returning SUCCESS with insufficient
     *      returndata would otherwise make solc's generated decoder revert in
     *      THIS frame, outside any try/catch. That length check alone is not
     *      enough, though: decoding a full 64-byte payload directly to
     *      (address, uint64) is ALSO strict — solc reverts, still in this
     *      frame, if the upper 96 bits of the address word or the upper 192
     *      bits of the uint64 word are non-zero. So the 64 bytes are decoded
     *      first as (uint256, uint256), which cannot revert for any bit
     *      pattern, and only then range-checked (`>> 160`/`>> 64` non-zero)
     *      before narrowing; a dirty payload is treated exactly like a
     *      wrong-length one, i.e. skipped via `continue`. Either failure
     *      mode — wrong length or dirty high bits — would otherwise be a
     *      permanent freeze of both withdraw and refund for every intent
     *      naming this aggregator, since provenIntents is read by both.
     *
     *      An uncatchable out-of-gas (oversized returndata, or an unbounded
     *      gas burn by a hostile member) is still possible and is ACCEPTED:
     *      solc copies the full returndata into memory in our frame before
     *      any length check runs, so a member returning gigabytes of data
     *      still costs us quadratic memory-expansion gas; a member that
     *      simply burns gas without returning is the same failure mode by a
     *      different mechanism. This is tolerated because deploy-time
     *      validation (`Deploy.validateAggregatorProverMembers`) only probes that
     *      each member exposes `chainIdByDomain(uint64)` — a duck-typed check
     *      that any contract implementing that one function passes, not a
     *      guarantee of `MessageBridgeProver`-descended or repo-built
     *      bytecode. It guards against an operator's config mistake (e.g. a
     *      non-bridge-attested or unrelated address), not against a
     *      deliberately malicious member contract. That validator also
     *      assumes NON-PROXY member bytecode: a proxy whose fallback returned
     *      a plausible 64-byte payload could defeat the shape checks above;
     *      it does not defend against a malicious proxy member.
     *
     *      No per-member gas cap by design: a cap would silently skip an honest
     *      member whose read exceeds it, leaving a delivered solver unpayable
     *      with no error. A compromised member can already forge a valid-looking
     *      proof through the front door, so a returndata bomb grants it nothing
     *      new. Fan-out is bounded by MAX_MEMBERS.
     *
     *      The size check plus the bit-range check are NOT sufficient on their
     *      own: a member function returning a single EMPTY DYNAMIC value
     *      (bytes, string, any array, or a struct with a dynamic field)
     *      ABI-encodes to exactly 64 bytes too — an offset head `0x20`
     *      followed by a length word `0x00` — which passes `ret.length == 64`
     *      and passes both range checks (`32 >> 160 == 0`, `0 >> 64 == 0`).
     *      Decoded naively, the ABI OFFSET WORD itself would surface as a
     *      fabricated non-zero claimant (`address(0x20)`) with `destination`
     *      0, for every intentHash — the only known payload class that
     *      FABRICATES a claimant rather than being skipped. The
     *      `rawDestination == 0` guard below closes this: no eligible member
     *      can legitimately hold destination 0, since `MessageBridgeProver`
     *      rejects chainId 0 at construction and `_resolveChainId` reverts
     *      `UnregisteredDomain(0)`. A static two-word `ProofData` tuple is
     *      what an honest member actually returns; together the size check,
     *      the bit-range check, and this zero-destination check mean any
     *      wrong-shaped payload is skipped (falls through to the next
     *      member) rather than surfaced.
     *
     *      KNOWN LIMITATION (shadowing): a member holding an entry whose
     *      `destination` is wrong shadows a valid proof held by a
     *      lower-priority member, since this function returns the first
     *      non-zero claimant. `IntentSource.withdraw` recovers by forwarding a
     *      challenge on its wrong-destination branch, so a second `withdraw`
     *      pays, but `_validateRefund` reads the same shadowed value, never
     *      forwards a challenge, and past `reward.deadline` refunds the
     *      creator while the solver who delivered goes unpaid. The mitigation
     *      is `Deploy.validateAggregatorProverMembers`, which admits only
     *      `MessageBridgeProver` descendants — the provers whose `destination`
     *      is cross-checked against the bridge origin domain in
     *      `_handleCrossChainMessage`.
     *
     *      Be precise about how far that reaches. `HyperProver` and
     *      `MetaProver` resolve an unregistered domain via
     *      `chainId != 0 ? chainId : originDomain`, so they do NOT fail closed:
     *      an omitted lane records `destination = originDomain`, a non-zero and
     *      plausible-looking WRONG chain id. For those two the deploy validator
     *      therefore also REQUIRES a non-empty domain config and round-trips
     *      every configured lane, so "bridge-attested" does not silently reduce
     *      to "the bridge's domain id happens to equal the chain id".
     *      `LayerZeroProver` needs no such requirement: its strict
     *      domain->chainId map has no fallback and reverts `UnregisteredDomain`.
     *
     *      Members admitted through
     *      `AGGREGATOR_PROVER_ALLOW_UNVERIFIED_MEMBERS` skip the per-lane check
     *      entirely and are audited out-of-band. The withdraw/refund asymmetry
     *      itself remains in `IntentSource`.
     * @param intentHash The intent hash to query
     * @return First non-zero member proof, or a zero ProofData if none
     */
    function provenIntents(
        bytes32 intentHash
    ) external view returns (ProofData memory) {
        bytes32[] memory members = getWhitelist();
        uint256 length = members.length;

        for (uint256 i = 0; i < length; ++i) {
            address member = members[i].toAddress();

            // No code.length guard: the constructor already rejects codeless
            // members, and a staticcall to a codeless address returns success
            // with EMPTY returndata anyway, which the ret.length != 64 check
            // below rejects. Dropping it saves an EXTCODESIZE per member.
            (bool success, bytes memory ret) = member.staticcall(
                abi.encodeWithSelector(
                    IProver.provenIntents.selector,
                    intentHash
                )
            );

            if (!success || ret.length != 64) continue;

            // Decode to (bytes32, uint256) first: unlike decoding directly to
            // (address, uint64), this cannot revert for any 64-byte payload.
            // Dirty high-order bits are then rejected by the checks below,
            // exactly like a wrong-length payload, rather than left to solc's
            // strict (address, uint64) decoder, which WOULD revert in this frame.
            (bytes32 rawClaimant, uint256 rawDestination) = abi.decode(
                ret,
                (bytes32, uint256)
            );

            // isValidAddress is the same >> 160 test AddressConverter applies
            // everywhere else; using it keeps one canonical notion of "this
            // word is an address" and makes the toAddress() below provably
            // revert-free.
            if (!rawClaimant.isValidAddress() || rawDestination >> 64 != 0) {
                continue;
            }

            // A single empty dynamic return value (bytes/string/array) encodes
            // to exactly 64 bytes — offset head 0x20, then length 0x00 — which
            // passes the size and range checks above and would otherwise surface
            // the ABI OFFSET WORD as a fabricated claimant with destination 0.
            // No eligible member can legitimately hold destination 0:
            // MessageBridgeProver rejects chainId 0 at construction and
            // _resolveChainId reverts UnregisteredDomain(0).
            if (rawDestination == 0) continue;

            address claimant = rawClaimant.toAddress();
            uint64 destination = uint64(rawDestination);

            if (claimant != address(0)) {
                return
                    ProofData({claimant: claimant, destination: destination});
            }
        }

        return ProofData({claimant: address(0), destination: 0});
    }

    /**
     * @notice Forwards a challenge to every member prover
     * @dev Forwarding is required, not cosmetic: IntentSource.withdraw calls
     *      this itself on its wrong-destination branch (IntentSource.sol:468).
     *      Reverting here would revert withdraw, and would revert an entire
     *      batchWithdraw (IntentSource.sol:492) over one planted bad proof.
     *
     *      Blanket-forwarding is precise even though this contract cannot tell
     *      which member is wrong: each member re-derives the intent hash and
     *      deletes ONLY its own entry, and ONLY on its own destination mismatch
     *      (BaseProver.sol:112-129). Honest proofs take the false branch and
     *      are untouched.
     * @param destination The intended destination chain ID
     * @param routeHash The hash of the intent's route
     * @param rewardHash The hash of the reward specification
     */
    function challengeIntentProof(
        uint64 destination,
        bytes32 routeHash,
        bytes32 rewardHash
    ) external {
        bytes32[] memory members = getWhitelist();
        uint256 length = members.length;

        for (uint256 i = 0; i < length; ++i) {
            address member = members[i].toAddress();

            // No code.length guard: the constructor rejects codeless members and
            // code cannot disappear afterwards (EIP-6780), so the codeless case
            // is unreachable. It is worth stating what it would cost if that
            // assumption ever broke: solc's extcodesize check on this void
            // high-level call reverts in THIS frame, outside the `catch` below,
            // so this whole function would revert — and with it the
            // wrong-destination branch of IntentSource.withdraw that calls it,
            // breaking batchWithdraw's per-intent isolation. The `try/catch`
            // guards the CALL, never the codeless-target case.
            try
                IProver(member).challengeIntentProof(
                    destination,
                    routeHash,
                    rewardHash
                )
            {} catch {
                continue;
            }
        }

        emit ChallengeForwarded(
            keccak256(abi.encodePacked(destination, routeHash, rewardHash))
        );
    }

    /**
     * @notice Always reverts; the aggregator dispatches no messages
     * @dev Reverting makes a misrouted Portal.prove or fulfillAndProve fail
     *      loudly and return the solver's ETH, rather than silently accepting a
     *      proof that was never sent.
     */
    function prove(
        address,
        uint64,
        bytes calldata,
        bytes calldata
    ) external payable {
        revert ProvingNotSupported();
    }

    /**
     * @notice Gets the proof mechanism type used by this prover
     */
    function getProofType() external pure returns (string memory) {
        return PROOF_TYPE;
    }

    /**
     * @notice Checks if this contract supports a given interface
     */
    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual override returns (bool) {
        return
            interfaceId == type(IProver).interfaceId ||
            super.supportsInterface(interfaceId);
    }
}

contracts/interfaces/IProver.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {ISemver} from "./ISemver.sol";

/**
 * @title IProver
 * @notice Interface for proving intent fulfillment
 * @dev Defines required functionality for proving intent execution with different
 * proof mechanisms (storage or Hyperlane)
 */
interface IProver is ISemver {
    /**
     * @notice Proof data stored for each proven intent
     * @param claimant Address eligible to claim the intent rewards; CANCELLED_CLAIMANT
     *        (types/Intent.sol) marks a proven cancellation, which is refundable only
     * @param destination Chain ID where the intent was proven
     */
    struct ProofData {
        address claimant;
        uint64 destination;
    }

    /**
     * @notice Arrays of intent hashes and claimants must have the same length
     */
    error ArrayLengthMismatch();

    /**
     * @notice Portal address cannot be zero
     */
    error ZeroPortal();

    /**
     * @notice Chain ID is too large to fit in uint64
     * @param chainId The chain ID that is too large
     */
    error ChainIdTooLarge(uint256 chainId);

    /**
     * @notice Emitted when an intent is successfully proven
     * @dev Emitted by the Prover on the source chain.
     * @param intentHash Hash of the proven intent
     * @param claimant Address eligible to claim the intent rewards; CANCELLED_CLAIMANT
     *        (types/Intent.sol) marks a proven cancellation, which is refundable only
     * @param destination Destination chain ID where the intent was proven
     */
    event IntentProven(
        bytes32 indexed intentHash,
        address indexed claimant,
        uint64 destination
    );

    /**
     * @notice Emitted when an intent proof is invalidated
     * @param intentHash Hash of the invalidated intent
     */
    event IntentProofInvalidated(bytes32 indexed intentHash);

    /**
     * @notice Emitted when attempting to prove an already-proven intent
     * @dev Event instead of error to allow batch processing to continue
     * @param intentHash Hash of the already proven intent
     */
    event IntentAlreadyProven(bytes32 intentHash);

    /**
     * @notice Gets the proof mechanism type used by this prover
     * @return string indicating the prover's mechanism
     */
    function getProofType() external pure returns (string memory);

    /**
     * @notice Initiates the proving process for intents from the destination chain
     * @dev Implemented by specific prover mechanisms (storage, Hyperlane, Metalayer)
     * @param sender Address of the original transaction sender
     * @param sourceChainDomainID Domain ID of the source chain
     * @param encodedProofs Encoded (intentHash, claimant) pairs as bytes
     * @param data Additional data specific to the proving implementation
     *
     * @dev WARNING: sourceChainDomainID is NOT necessarily the same as chain ID.
     *      Each bridge provider uses their own domain ID mapping system:
     *      - Hyperlane: Uses custom domain IDs that may differ from chain IDs
     *      - LayerZero: Uses endpoint IDs that map to chains differently
     *      - Metalayer: Uses domain IDs specific to their routing system
     *      - Polymer: Uses chainIDs
     *      - CCIP: Uses chain selectors that are totally separate from chainIDs
     *      You MUST consult the specific bridge provider's documentation to determine
     *      the correct domain ID for the source chain.
     */
    function prove(
        address sender,
        uint64 sourceChainDomainID,
        bytes calldata encodedProofs,
        bytes calldata data
    ) external payable;

    /**
     * @notice Returns the proof data for a given intent hash
     * @param intentHash Hash of the intent to query
     * @return ProofData containing claimant and destination chain ID
     */
    function provenIntents(
        bytes32 intentHash
    ) external view returns (ProofData memory);

    /**
     * @notice Challenge an intent proof if destination chain ID doesn't match
     * @dev Can be called by anyone to remove invalid proofs. This is a safety mechanism to ensure
     *      intents are only claimable when executed on their intended destination chains.
     * @param destination The intended destination chain ID
     * @param routeHash The hash of the intent's route
     * @param rewardHash The hash of the reward specification
     */
    function challengeIntentProof(
        uint64 destination,
        bytes32 routeHash,
        bytes32 rewardHash
    ) external;
}

contracts/interfaces/ISemver.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

/**
 * @title Semver Interface
 * @dev An interface for a contract that has a version
 */
interface ISemver {
    function version() external pure returns (string memory);
}

contracts/libs/AddressConverter.sol

/* -*- c-basic-offset: 4 -*- */
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

/**
 * @title AddressConverter
 * @notice Utility library for converting between address and bytes32 types
 * @dev Provides simple functions to convert between address (20 bytes) and bytes32 (32 bytes)
 */
library AddressConverter {
    error InvalidAddress(bytes32 value);

    /**
     * @notice Convert an Ethereum address to bytes32
     * @dev Pads the 20-byte address to 32 bytes by converting to uint160, then uint256, then bytes32
     * @param addr The address to convert
     * @return The bytes32 representation of the address
     */
    function toBytes32(address addr) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(addr)));
    }

    /**
     * @notice Convert bytes32 to an Ethereum address
     * @dev Truncates the 32-byte value to 20 bytes by converting to uint256, then uint160, then address
     * @param b The bytes32 value to convert
     * @return The address representation of the bytes32 value
     */
    function toAddress(bytes32 b) internal pure returns (address) {
        if (!isValidAddress(b)) {
            revert InvalidAddress(b);
        }

        return address(uint160(uint256(b)));
    }

    /**
     * @notice Check if a bytes32 value represents a valid Ethereum address
     * @dev An Ethereum address must have the top 12 bytes as zero
     * @param b The bytes32 value to check
     * @return True if the bytes32 value can be safely converted to an Ethereum address
     */
    function isValidAddress(bytes32 b) internal pure returns (bool) {
        // The top 12 bytes must be zero for a valid Ethereum address
        return uint256(b) >> 160 == 0;
    }
}

contracts/libs/Semver.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {ISemver} from "../interfaces/ISemver.sol";

/**
 * @title Semver
 * @notice Implements semantic versioning for contracts
 * @dev Abstract contract that provides a standard way to access version information
 */
abstract contract Semver is ISemver {
    /**
     * @notice Returns the semantic version of the contract
     * @dev Implementation of ISemver interface
     * @return Current version string in semantic format
     */
    function version() external pure returns (string memory) {
        return "2.12.0";
    }
}

contracts/libs/Whitelist.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

/**
 * @title Whitelist
 * @notice Abstract contract providing immutable whitelist functionality
 * @dev Uses immutable arrays to store up to 20 whitelisted addresses as bytes32 for cross-VM compatibility
 *
 * This contract provides a gas-efficient, immutable approach to whitelisting:
 * - The whitelist is configured ONCE at construction time
 * - After deployment, the whitelist CANNOT be modified (addresses cannot be added or removed)
 * - Maximum of 20 addresses can be whitelisted
 * - Uses immutable slots for each whitelisted address (lower gas cost than storage)
 * - Optimized for early exit when checking whitelist membership
 * - Uses bytes32 for cross-VM compatibility (Ethereum addresses and Solana public keys)
 */
abstract contract Whitelist {
    /**
     * @notice Error thrown when an address is not whitelisted
     * @param addr The address that was not found in the whitelist
     */
    error AddressNotWhitelisted(bytes32 addr);

    /**
     * @notice Whitelist size exceeds maximum allowed
     * @param size Attempted whitelist size
     * @param maxSize Maximum allowed size
     */
    error WhitelistSizeExceeded(uint256 size, uint256 maxSize);

    /// @dev Maximum number of addresses that can be whitelisted
    uint256 private constant MAX_WHITELIST_SIZE = 20;

    /// @dev Number of addresses actually in the whitelist
    uint256 private immutable WHITELIST_SIZE;

    /// @dev Immutable storage for whitelisted addresses (up to 20)
    bytes32 private immutable ADDRESS_1;
    bytes32 private immutable ADDRESS_2;
    bytes32 private immutable ADDRESS_3;
    bytes32 private immutable ADDRESS_4;
    bytes32 private immutable ADDRESS_5;
    bytes32 private immutable ADDRESS_6;
    bytes32 private immutable ADDRESS_7;
    bytes32 private immutable ADDRESS_8;
    bytes32 private immutable ADDRESS_9;
    bytes32 private immutable ADDRESS_10;
    bytes32 private immutable ADDRESS_11;
    bytes32 private immutable ADDRESS_12;
    bytes32 private immutable ADDRESS_13;
    bytes32 private immutable ADDRESS_14;
    bytes32 private immutable ADDRESS_15;
    bytes32 private immutable ADDRESS_16;
    bytes32 private immutable ADDRESS_17;
    bytes32 private immutable ADDRESS_18;
    bytes32 private immutable ADDRESS_19;
    bytes32 private immutable ADDRESS_20;

    /**
     * @notice Initializes the whitelist with a set of addresses
     * @param addresses Array of addresses to whitelist (as bytes32 for cross-VM compatibility)
     */
    // solhint-disable-next-line function-max-lines
    constructor(bytes32[] memory addresses) {
        if (addresses.length > MAX_WHITELIST_SIZE) {
            revert WhitelistSizeExceeded(addresses.length, MAX_WHITELIST_SIZE);
        }

        // Store whitelist size
        WHITELIST_SIZE = addresses.length;

        // Initialize all addresses to zero
        ADDRESS_1 = addresses.length > 0 ? addresses[0] : bytes32(0);
        ADDRESS_2 = addresses.length > 1 ? addresses[1] : bytes32(0);
        ADDRESS_3 = addresses.length > 2 ? addresses[2] : bytes32(0);
        ADDRESS_4 = addresses.length > 3 ? addresses[3] : bytes32(0);
        ADDRESS_5 = addresses.length > 4 ? addresses[4] : bytes32(0);
        ADDRESS_6 = addresses.length > 5 ? addresses[5] : bytes32(0);
        ADDRESS_7 = addresses.length > 6 ? addresses[6] : bytes32(0);
        ADDRESS_8 = addresses.length > 7 ? addresses[7] : bytes32(0);
        ADDRESS_9 = addresses.length > 8 ? addresses[8] : bytes32(0);
        ADDRESS_10 = addresses.length > 9 ? addresses[9] : bytes32(0);
        ADDRESS_11 = addresses.length > 10 ? addresses[10] : bytes32(0);
        ADDRESS_12 = addresses.length > 11 ? addresses[11] : bytes32(0);
        ADDRESS_13 = addresses.length > 12 ? addresses[12] : bytes32(0);
        ADDRESS_14 = addresses.length > 13 ? addresses[13] : bytes32(0);
        ADDRESS_15 = addresses.length > 14 ? addresses[14] : bytes32(0);
        ADDRESS_16 = addresses.length > 15 ? addresses[15] : bytes32(0);
        ADDRESS_17 = addresses.length > 16 ? addresses[16] : bytes32(0);
        ADDRESS_18 = addresses.length > 17 ? addresses[17] : bytes32(0);
        ADDRESS_19 = addresses.length > 18 ? addresses[18] : bytes32(0);
        ADDRESS_20 = addresses.length > 19 ? addresses[19] : bytes32(0);
    }

    /**
     * @notice Checks if an address is whitelisted
     * @param addr Address to check (as bytes32 for cross-VM compatibility)
     * @return True if the address is whitelisted, false otherwise
     */
    // solhint-disable-next-line function-max-lines
    function isWhitelisted(bytes32 addr) public view returns (bool) {
        // Short circuit check for empty whitelist
        if (WHITELIST_SIZE == 0) return false;

        // Short circuit check for zero address
        if (addr == bytes32(0)) return false;

        if (ADDRESS_1 == addr) return true;
        if (WHITELIST_SIZE <= 1) return false;

        if (ADDRESS_2 == addr) return true;
        if (WHITELIST_SIZE <= 2) return false;

        if (ADDRESS_3 == addr) return true;
        if (WHITELIST_SIZE <= 3) return false;

        if (ADDRESS_4 == addr) return true;
        if (WHITELIST_SIZE <= 4) return false;

        if (ADDRESS_5 == addr) return true;
        if (WHITELIST_SIZE <= 5) return false;

        if (ADDRESS_6 == addr) return true;
        if (WHITELIST_SIZE <= 6) return false;

        if (ADDRESS_7 == addr) return true;
        if (WHITELIST_SIZE <= 7) return false;

        if (ADDRESS_8 == addr) return true;
        if (WHITELIST_SIZE <= 8) return false;

        if (ADDRESS_9 == addr) return true;
        if (WHITELIST_SIZE <= 9) return false;

        if (ADDRESS_10 == addr) return true;
        if (WHITELIST_SIZE <= 10) return false;

        if (ADDRESS_11 == addr) return true;
        if (WHITELIST_SIZE <= 11) return false;

        if (ADDRESS_12 == addr) return true;
        if (WHITELIST_SIZE <= 12) return false;

        if (ADDRESS_13 == addr) return true;
        if (WHITELIST_SIZE <= 13) return false;

        if (ADDRESS_14 == addr) return true;
        if (WHITELIST_SIZE <= 14) return false;

        if (ADDRESS_15 == addr) return true;
        if (WHITELIST_SIZE <= 15) return false;

        if (ADDRESS_16 == addr) return true;
        if (WHITELIST_SIZE <= 16) return false;

        if (ADDRESS_17 == addr) return true;
        if (WHITELIST_SIZE <= 17) return false;

        if (ADDRESS_18 == addr) return true;
        if (WHITELIST_SIZE <= 18) return false;

        if (ADDRESS_19 == addr) return true;
        if (WHITELIST_SIZE <= 19) return false;

        return ADDRESS_20 == addr;
    }

    /**
     * @notice Validates that an address is whitelisted, reverting if not
     * @param addr Address to validate (as bytes32 for cross-VM compatibility)
     */
    function validateWhitelisted(bytes32 addr) internal view {
        if (!isWhitelisted(addr)) {
            revert AddressNotWhitelisted(addr);
        }
    }

    /**
     * @notice Returns the list of whitelisted addresses
     * @return whitelist Array of whitelisted addresses (as bytes32 for cross-VM compatibility)
     */
    function getWhitelist() public view returns (bytes32[] memory) {
        bytes32[] memory whitelist = new bytes32[](WHITELIST_SIZE);

        if (WHITELIST_SIZE > 0) whitelist[0] = ADDRESS_1;
        if (WHITELIST_SIZE > 1) whitelist[1] = ADDRESS_2;
        if (WHITELIST_SIZE > 2) whitelist[2] = ADDRESS_3;
        if (WHITELIST_SIZE > 3) whitelist[3] = ADDRESS_4;
        if (WHITELIST_SIZE > 4) whitelist[4] = ADDRESS_5;
        if (WHITELIST_SIZE > 5) whitelist[5] = ADDRESS_6;
        if (WHITELIST_SIZE > 6) whitelist[6] = ADDRESS_7;
        if (WHITELIST_SIZE > 7) whitelist[7] = ADDRESS_8;
        if (WHITELIST_SIZE > 8) whitelist[8] = ADDRESS_9;
        if (WHITELIST_SIZE > 9) whitelist[9] = ADDRESS_10;
        if (WHITELIST_SIZE > 10) whitelist[10] = ADDRESS_11;
        if (WHITELIST_SIZE > 11) whitelist[11] = ADDRESS_12;
        if (WHITELIST_SIZE > 12) whitelist[12] = ADDRESS_13;
        if (WHITELIST_SIZE > 13) whitelist[13] = ADDRESS_14;
        if (WHITELIST_SIZE > 14) whitelist[14] = ADDRESS_15;
        if (WHITELIST_SIZE > 15) whitelist[15] = ADDRESS_16;
        if (WHITELIST_SIZE > 16) whitelist[16] = ADDRESS_17;
        if (WHITELIST_SIZE > 17) whitelist[17] = ADDRESS_18;
        if (WHITELIST_SIZE > 18) whitelist[18] = ADDRESS_19;
        if (WHITELIST_SIZE > 19) whitelist[19] = ADDRESS_20;

        return whitelist;
    }

    /**
     * @notice Returns the number of whitelisted addresses
     * @return Number of addresses in the whitelist
     */
    function getWhitelistSize() public view returns (uint256) {
        return WHITELIST_SIZE;
    }
}

node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000000,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "@hyperlane-xyz/core/=node_modules/@hyperlane-xyz/core/",
    "@eth-optimism/contracts-bedrock/=node_modules/@eth-optimism/contracts-bedrock/",
    "@metalayer/contracts/=node_modules/@metalayer/contracts/",
    "@chainlink/contracts-ccip/=node_modules/@chainlink/contracts-ccip/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.