Skip to content
Verified contractExactMIT

Relay

Address0x5bb16e0cc39e770b4483e5fb25ec2b4a574e3fbe
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,279,245
Creation transaction
0xb6b938e946…9939dd12bd

35 files

contracts/protocol/implementation/Relay.sol

// SPDX-License-Identifier: MIT
// Exact-version pin: the FV manifest (test-forge/fv/verification-manifest.json) attests the
// deployment artifact against this exact compiler, and the forge deploy scripts must produce
// byte-identical code to the attested Hardhat artifact — do not widen the pragma.
pragma solidity =0.8.35;

import { IIRelay } from "../interface/IIRelay.sol";
import { IRelay } from "../../userInterfaces/IRelay.sol";
// solhint-disable-next-line no-unused-import
import { RandomNumberV2Interface } from "../../userInterfaces/LTS/RandomNumberV2Interface.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { OwnableWithTimelock } from "../../utils/implementation/OwnableWithTimelock.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import { ERC1967Utils } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/**
 * Relay (finalization) contract.
 */
contract Relay is IIRelay, OwnableWithTimelock, UUPSUpgradeable {
    using MerkleProof for bytes32[];
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.UintSet;
    /**
     * State variables for the relay contract.
     * IMPORTANT: if you change this, you have to adapt the assembly code interacting with
     * the struct with relay() function.
     */
    struct StateData {
        /// The protocol id of the random number protocol.
        uint8 randomNumberProtocolId;
        /// The timestamp of the first voting round start.
        uint32 firstVotingRoundStartTs;
        /// The duration of a voting epoch in seconds.
        uint8 votingEpochDurationSeconds;
        /// The start voting round id of the first reward epoch.
        uint32 firstRewardEpochStartVotingRoundId;
        /// The duration of a reward epoch in voting epochs.
        uint16 rewardEpochDurationInVotingEpochs;
        /// The threshold increase in BIPS for signing with old signing policy.
        uint16 thresholdIncreaseBIPS;

        // Publication of current random number
        /// The voting round id of the random number generation.
        uint32 randomVotingRoundId;
        /// If true, the random number is generated secure.
        bool isSecureRandom;

        /// The last reward epoch id for which the signing policy has been initialized.
        uint32 lastInitializedRewardEpoch;

        /// If true, signing policy relay is disabled.
        bool noSigningPolicyRelay;

        /// If reward epoch of a message is less then
        /// lastInitializedRewardEpoch - messageFinalizationWindowInRewardEpochs
        /// relaying the message is rejected.
        uint32 messageFinalizationWindowInRewardEpochs;
    }

    // 4-byte custom-error selectors for the hand-written relay() assembly (compile-time
    // folded; the matching error declarations live on IRelay). One selector per failure.
    /* solhint-disable const-name-snakecase */
    uint32 private constant ERR_ALREADY_RELAYED = 0xd0ebeb4b; // bytes4(keccak256("AlreadyRelayed()"))
    uint32 private constant ERR_BAD_S = 0xf54d11f5; // bytes4(keccak256("BadS()"))
    uint32 private constant ERR_BAD_V = 0x8320c358; // bytes4(keccak256("BadV()"))
    uint32 private constant ERR_DELAYED_SIGN_POLICY = 0x0c01bf37; // bytes4(keccak256("DelayedSignPolicy()"))
    uint32 private constant ERR_ECRECOVER_ERROR = 0xc859b3f5; // bytes4(keccak256("EcrecoverError()"))
    // bytes4(keccak256("EcrecoverReturnedBadData()"))
    uint32 private constant ERR_ECRECOVER_RETURNED_BAD_DATA = 0x62bd175a;
    uint32 private constant ERR_INCORRECT_MERKLE_PROOF = 0x5d2f8a05; // bytes4(keccak256("IncorrectMerkleProof()"))
    uint32 private constant ERR_INDEX_OUT_OF_ORDER = 0x297f31e1; // bytes4(keccak256("IndexOutOfOrder()"))
    uint32 private constant ERR_INDEX_OUT_OF_RANGE = 0x1390f2a1; // bytes4(keccak256("IndexOutOfRange()"))
    // bytes4(keccak256("InvalidRandomNumberProof()"))
    uint32 private constant ERR_INVALID_RANDOM_NUMBER_PROOF = 0x987d1299;
    // bytes4(keccak256("InvalidSignPolicyLength()"))
    uint32 private constant ERR_INVALID_SIGN_POLICY_LENGTH = 0x5509ecdf;
    // bytes4(keccak256("InvalidSignPolicyMetadata()"))
    uint32 private constant ERR_INVALID_SIGN_POLICY_METADATA = 0x3fcc839e;
    uint32 private constant ERR_INVALID_VOTING_ROUND_ID = 0x01ed5f84; // bytes4(keccak256("InvalidVotingRoundId()"))
    uint32 private constant ERR_MESSAGE_TOO_OLD = 0x4ed02d0d; // bytes4(keccak256("MessageTooOld()"))
    uint32 private constant ERR_MUST_USE_NEW_SIGN_POLICY = 0xf64fd99c; // bytes4(keccak256("MustUseNewSignPolicy()"))
    uint32 private constant ERR_NO_NEW_SIGN_POLICY_SIZE = 0xf63c072c; // bytes4(keccak256("NoNewSignPolicySize()"))
    uint32 private constant ERR_NO_RANDOM_NUMBER = 0xd76adcd1; // bytes4(keccak256("NoRandomNumber()"))
    uint32 private constant ERR_NO_SIGNATURE_COUNT = 0xf8139caf; // bytes4(keccak256("NoSignatureCount()"))
    uint32 private constant ERR_NOT_ENOUGH_SIGNATURES = 0xe246dc63; // bytes4(keccak256("NotEnoughSignatures()"))
    uint32 private constant ERR_NOT_NEXT_REWARD_EPOCH = 0x124f824d; // bytes4(keccak256("NotNextRewardEpoch()"))
    // bytes4(keccak256("NotWithLastInitialized()"))
    uint32 private constant ERR_NOT_WITH_LAST_INITIALIZED = 0xbe8b3520;
    // bytes4(keccak256("SignPolicyRelayDisabled()"))
    uint32 private constant ERR_SIGN_POLICY_RELAY_DISABLED = 0xf0059553;
    uint32 private constant ERR_SIGNING_POLICY_EMPTY = 0x53c236da; // bytes4(keccak256("SigningPolicyEmpty()"))
    // bytes4(keccak256("SigningPolicyHashMismatch()"))
    uint32 private constant ERR_SIGNING_POLICY_HASH_MISMATCH = 0x143fc35c;
    uint32 private constant ERR_THRESHOLD_TOO_HIGH = 0xe56d58cf; // bytes4(keccak256("ThresholdTooHigh()"))
    uint32 private constant ERR_THRESHOLD_TOO_LOW = 0x398ecf8a; // bytes4(keccak256("ThresholdTooLow()"))
    uint32 private constant ERR_TOO_MANY_VOTERS = 0x4647aac9; // bytes4(keccak256("TooManyVoters()"))
    uint32 private constant ERR_TOO_SHORT_MESSAGE = 0x43a69646; // bytes4(keccak256("TooShortMessage()"))
    uint32 private constant ERR_TOTAL_WEIGHT_TOO_BIG = 0x8dd23571; // bytes4(keccak256("TotalWeightTooBig()"))
    uint32 private constant ERR_UNREACHABLE_CODE = 0xe0c9078c; // bytes4(keccak256("UnreachableCode()"))
    uint32 private constant ERR_WRONG_MESSAGE_FORMAT = 0xe3427225; // bytes4(keccak256("WrongMessageFormat()"))
    uint32 private constant ERR_WRONG_MESSAGE_FORMAT2 = 0x4913ec0d; // bytes4(keccak256("WrongMessageFormat2()"))
    // bytes4(keccak256("WrongSignPolicyRewardEpoch()"))
    uint32 private constant ERR_WRONG_SIGN_POLICY_REWARD_EPOCH = 0x8134d963;
    uint32 private constant ERR_WRONG_SIGNATURE = 0x356a4418; // bytes4(keccak256("WrongSignature()"))
    // bytes4(keccak256("WrongSizeForNewSignPolicy()"))
    uint32 private constant ERR_WRONG_SIZE_FOR_NEW_SIGN_POLICY = 0x60c18b0d;
    uint32 private constant ERR_ZERO_MERKLE_ROOT = 0x9266ee62; // bytes4(keccak256("ZeroMerkleRoot()"))
    uint32 private constant ERR_ZERO_SIGNER = 0xe5c48ac5; // bytes4(keccak256("ZeroSigner()"))
    /* solhint-enable const-name-snakecase */

    uint256 private constant THRESHOLD_BIPS = 10000;
    uint256 private constant SELECTOR_BYTES = 4;
    uint256 private constant MAX_VOTERS = 300;
    uint256 private constant MIN_THRESHOLD_BIPS = 5000;
    uint256 private constant MAX_THRESHOLD_BIPS = 6600;

    /// Transient (EIP-1153) slot holding verifyCustomSignatureWithThreshold's threshold override
    /// for the duration of its relay() self-call; 0 = no override, so a top-level relay() call
    /// always reads 0. uint256(keccak256("flare.relay.thresholdOverride")).
    uint256 private constant TSLOT_THRESHOLD_OVERRIDE =
        0x6cea5c73f8043432390b6161c6418f07a6dc8cc07557416a3f28d2fd6007a2c3;

    // Signing policy byte encoding structure
    // 2 bytes - numberOfVoters
    // 3 bytes - rewardEpochId
    // 4 bytes - startingVotingRoundId
    // 2 bytes - threshold
    // 32 bytes - randomSeed
    // array of 'size':
    // - 20 bytes address
    // - 2 bytes weight
    // Total 43 + size * (20 + 2) bytes
    // metadataLength = 11 bytes (size, rewardEpochId, startingVotingRoundId, threshold)

    /* solhint-disable const-name-snakecase */
    uint256 private constant METADATA_BYTES = 11;
    uint256 private constant REWARD_EPOCH_ID_BYTES = 3;
    uint256 private constant MD_MASK_threshold = 0xffff;
    uint256 private constant MD_BOFF_threshold = 0;
    uint256 private constant MD_MASK_startingVotingRoundId = 0xffffffff;
    uint256 private constant MD_BOFF_startingVotingRoundId = 16;
    uint256 private constant MD_MASK_rewardEpochId = 0xffffff;
    uint256 private constant MD_BOFF_rewardEpochId = 48;
    uint256 private constant MD_MASK_numberOfVoters = 0xffff;
    uint256 private constant MD_BOFF_numberOfVoters = 72;
    /* solhint-enable const-name-snakecase */

    uint256 private constant RANDOM_SEED_BYTES = 32;
    uint256 private constant ADDRESS_BYTES = 20;
    uint256 private constant WEIGHT_BYTES = 2;
    uint256 private constant WEIGHT_MASK = 0xffff;
    uint256 private constant ADDRESS_AND_WEIGHT_BYTES = 22; // ADDRESS_BYTES + WEIGHT_BYTES;
    //METADATA_BYTES + RANDOM_SEED_BYTES;
    uint256 private constant SIGNING_POLICY_PREFIX_BYTES = 43;

    // Protocol message merkle root structure
    // 1 byte - protocolId
    // 4 bytes - votingRoundId
    // 1 byte - isSecureRandom (a bool: 0 or 1 for the random-number protocol, 0 for every other
    //          protocol id; enforced while parsing the message)
    // 32 bytes - merkleRoot
    // Total 38 bytes
    // if loaded into a memory slot, these are right shifts and masks
    /* solhint-disable const-name-snakecase */
    uint256 private constant MESSAGE_BYTES = 38;
    uint256 private constant PROTOCOL_ID_BYTES = 1;
    uint256 private constant MESSAGE_NO_MR_BYTES = 6;
    uint256 private constant MSG_NMR_MASK_isSecureRandom = 0xff;
    uint256 private constant MSG_NMR_BOFF_isSecureRandom = 0;
    uint256 private constant MSG_NMR_MASK_votingRoundId = 0xffffffff;
    uint256 private constant MSG_NMR_BOFF_votingRoundId = 8;
    uint256 private constant MSG_NMR_MASK_protocolId = 0xff;
    uint256 private constant MSG_NMR_BOFF_protocolId = 40;
    /* solhint-enable const-name-snakecase */

    /* solhint-disable const-name-snakecase */
    uint256 private constant SD_MASK_randomNumberProtocolId = 0xff;
    uint256 private constant SD_BOFF_randomNumberProtocolId = 0;
    uint256 private constant SD_MASK_firstVotingRoundStartTs = 0xffffffff;
    uint256 private constant SD_BOFF_firstVotingRoundStartTs = 8;
    uint256 private constant SD_MASK_votingEpochDurationSeconds = 0xff;
    uint256 private constant SD_BOFF_votingEpochDurationSeconds = 40;
    uint256 private constant SD_MASK_firstRewardEpochStartVotingRoundId = 0xffffffff;
    uint256 private constant SD_BOFF_firstRewardEpochStartVotingRoundId = 48;
    uint256 private constant SD_MASK_rewardEpochDurationInVotingEpochs = 0xffff;
    uint256 private constant SD_BOFF_rewardEpochDurationInVotingEpochs = 80;
    uint256 private constant SD_MASK_thresholdIncreaseBIPS = 0xffff;
    uint256 private constant SD_BOFF_thresholdIncreaseBIPS = 96;
    uint256 private constant SD_MASK_randomVotingRoundId = 0xffffffff;
    uint256 private constant SD_BOFF_randomVotingRoundId = 112;
    uint256 private constant SD_MASK_isSecureRandom = 0xff;
    uint256 private constant SD_BOFF_isSecureRandom = 144;
    uint256 private constant SD_MASK_lastInitializedRewardEpoch = 0xffffffff;
    uint256 private constant SD_BOFF_lastInitializedRewardEpoch = 152;
    uint256 private constant SD_MASK_noSigningPolicyRelay = 0xff;
    uint256 private constant SD_BOFF_noSigningPolicyRelay = 184;
    uint256 private constant SD_MASK_messageFinalizationWindowInRewardEpochs = 0xffffffff;
    uint256 private constant SD_BOFF_messageFinalizationWindowInRewardEpochs = 192;

    /* solhint-enable const-name-snakecase */

    // Signature with index structure
    // 1 byte - v
    // 32 bytes - r
    // 32 bytes - s
    // 2 byte - index in signing policy
    // Total 67 bytes

    uint256 private constant NUMBER_OF_SIGNATURES_BYTES = 2;
    uint256 private constant NUMBER_OF_SIGNATURES_RIGHT_SHIFT_BITS = 240; // 8 * (32 - NUMBER_OF_SIGNATURES_BYTES)
    uint256 private constant NUMBER_OF_SIGNATURES_MASK = 0xffff;
    uint256 private constant SIGNATURE_WITH_INDEX_BYTES = 67; // 1 v + 32 r + 32 s + 2 index
    uint256 private constant SIGNATURE_V_BYTES = 1;
    uint256 private constant SIGNATURE_INDEX_RIGHT_SHIFT_BITS = 240; // 256 - 2*8 = 240

    // Memory slots
    /* solhint-disable const-name-snakecase */
    uint256 private constant M_0 = 0;
    uint256 private constant M_1 = 32;
    uint256 private constant M_2 = 64;
    uint256 private constant M_2_signingPolicyHashTmp = 64;
    uint256 private constant M_3 = 96;
    uint256 private constant M_3_existingSigningPolicyHashTmp = 96;
    uint256 private constant M_4 = 128;
    uint256 private constant M_5_stateData = 160;
    uint256 private constant M_5_isSecureRandom = 160;
    uint256 private constant M_6_merkleRoot = 192;
    uint256 private constant M_7_randomNumber = 224;
    uint256 private constant M_8_signatureStart = 256;
    /// Start of the digest scratch region, above every fixed slot: the single-keccak digest
    /// computations write sourceChainId followed by the raw content bytes here (up to
    /// 32 + 43 + MAX_VOTERS * 22 bytes for a signing policy), so no fixed slot is ever clobbered.
    uint256 private constant M_9_digestScratch = 288;

    uint256 private constant ADDRESS_OFFSET = 12;
    /* solhint-enable const-name-snakecase */

    /// The signing policy hash for given reward epoch id.
    mapping(uint256 rewardEpochId => bytes32) private toSigningPolicyHashPrivate;
    /// The merkle root for given protocol id and voting round id.
    //slither-disable-next-line uninitialized-state
    mapping(uint256 protocolId => mapping(uint256 votingRoundId => bytes32)) private merkleRootsPrivate;
    /// The start voting round id for given reward epoch id.
    mapping(uint256 rewardEpochId => uint256) public startingVotingRoundIds;
    /// The address of the signing policy setter (zero if disabled).
    address public signingPolicySetter;

    /// Fees per protocol, in native wei — or in base units of `feeToken` when one is set.
    mapping(uint256 => uint256) public override protocolFee;
    /// fee collection address.
    address payable public feeCollectionAddress;
    /// The ERC-20 the verify() fee is paid in; zero = native coin via msg.value. For mirror
    /// deployments on chains without a (spendable) native token, e.g. Tempo, where msg.value
    /// is always 0. Owner-set atomically with the fee table via setProtocolFees; relay mode
    /// only (like every fee setting), so it can never be nonzero while oldRelay is configured.
    /// Must be a standard exact-transfer ERC-20 — fee-on-transfer or rebasing tokens are
    /// unsupported (the pull is assumed to deliver exactly the fee).
    address public override feeToken;
    /// Protocol ids with a nonzero fee, kept in lockstep with `protocolFee`
    /// (id in set ⟺ protocolFee[id] != 0). Replacing the fee token clears and rebuilds
    /// this set and the mapping atomically, preserving one denomination for the entire table.
    EnumerableSet.UintSet private feeProtocolIdsPrivate;
    /// Addresses allowed to call verify() without paying the protocol fee (e.g. DVN
    /// adapters). Owner-set via setFeeExemptions.
    mapping(address account => bool) public override feeExemptAddress;

    /// A map with bits indicating whether a random number is secure for
    /// historical purposes. For given votingRoundId, the bit vector is obtained
    /// in index  votingRoundId / 256 and the bit is at position votingRoundId % 256.
    //slither-disable-next-line uninitialized-state
    mapping(uint256 => bytes32) internal isSecureRandomMap;

    /// The state of the relay contract.
    StateData public stateData;

    /// The relayed (Merkle-proven) random number for a given voting round id.
    //slither-disable-next-line uninitialized-state
    mapping(uint256 votingRoundId => uint256) private toRandomNumberPrivate;

    /// Old relay contract
    IRelay public oldRelay;
    /// The initial reward epoch id.
    uint32 public initialRewardEpochId;
    /// The starting voting round id for the initial
    uint32 public startingVotingRoundIdForInitialRewardEpochId;
    /// The source network id bound into every stored signing-policy hash and, via the analogous
    /// digest in relay(), every signed protocol-message digest —
    /// keccak256(sourceChainId ‖ raw content bytes), one keccak — so policies and messages minted
    /// for another network are rejected even under a fully overlapping voter set. Explicit and
    /// nonzero on every deployment, set once in initialize; home deploys force it to block.chainid.
    uint256 public override sourceChainId;

    /// Only signingPolicySetter address/contract can call this method.
    modifier onlySigningPolicySetter() {
        require(msg.sender == signingPolicySetter, OnlySigningPolicySetterRole());
        _;
    }

    /// Locks the implementation contract; state lives behind the proxy only.
    constructor() {
        _disableInitializers();
    }

    /**
     * Initializes the Relay behind its proxy. One atomic call configures EVERYTHING —
     * protocol config, the source-network binding, the owner-timelock duration and the
     * per-chain owner — and it runs inside the proxy constructor (see RelayProxy), so the
     * deterministic proxy address never exists uninitialized.
     * @param _initialConfig The initial configuration of the relay.
     * @param _signingPolicySetter The address of the signing policy setter.
     * @param _oldRelay The old relay contract (can be address(0)); home/setter-mode deployments
     * only — must be zero in relay mode (mirrors), see OldRelayNotAllowedInRelayMode.
     * @param _initialOwner The per-chain owner (multisig): authorizes every guarded call — fee
     * settings, upgrades, the timelock duration and ownership transfer — through the
     * OwnableWithTimelock owner-timelock path (see IOwnableWithTimelock).
     */
    function initialize(
        RelayInitialConfig memory _initialConfig,
        address _signingPolicySetter,
        IRelay _oldRelay,
        address _initialOwner
    )
        external initializer
    {
        __Ownable_init(_initialOwner);
        require(_initialConfig.thresholdIncreaseBIPS >= THRESHOLD_BIPS, ThresholdIncreaseTooSmall());
        // Epoch durations are divisors in relay() and timestamp calculations and must be nonzero.
        require(_initialConfig.rewardEpochDurationInVotingEpochs > 0, RewardEpochDurationZero());
        require(_initialConfig.votingEpochDurationSeconds > 0, VotingEpochDurationZero());
        // A zero initial signing-policy hash would make every policy fail the initial-epoch hash check.
        // The supplied hash must already be source-bound — keccak256(sourceChainId ‖ encoded policy
        // bytes), one keccak — matching what relay()/setSigningPolicy store and verify. A hash of another
        // shape (or bound to another source) fails closed: no relay message can ever match it. Deploy
        // scripts reconstruct the full policy from chain state and hash it under this scheme on migration.
        require(_initialConfig.initialSigningPolicyHash != bytes32(0), InitialSigningPolicyHashZero());
        require(_initialConfig.firstRewardEpochStartVotingRoundId +
            _initialConfig.initialRewardEpochId * _initialConfig.rewardEpochDurationInVotingEpochs <=
            _initialConfig.startingVotingRoundIdForInitialRewardEpochId, InvalidInitialStartingVotingRoundId());
        initialRewardEpochId = _initialConfig.initialRewardEpochId;
        startingVotingRoundIdForInitialRewardEpochId =
            _initialConfig.startingVotingRoundIdForInitialRewardEpochId;
        // lastInitializedRewardEpoch is seeded to initialRewardEpochId, so the first subsequent
        // setSigningPolicy call must provide exactly initialRewardEpochId + 1. Deployment configuration
        // and the trusted setter's policy sequence must agree on this cutover epoch.
        stateData.lastInitializedRewardEpoch = _initialConfig.initialRewardEpochId;
        startingVotingRoundIds[_initialConfig.initialRewardEpochId] =
            _initialConfig.startingVotingRoundIdForInitialRewardEpochId;
        toSigningPolicyHashPrivate[_initialConfig.initialRewardEpochId] = _initialConfig.initialSigningPolicyHash;
        require(_initialConfig.randomNumberProtocolId > 1, InvalidRandomNumberProtocolId());
        stateData.randomNumberProtocolId = _initialConfig.randomNumberProtocolId;
        stateData.firstVotingRoundStartTs = _initialConfig.firstVotingRoundStartTs;
        stateData.votingEpochDurationSeconds = _initialConfig.votingEpochDurationSeconds;
        stateData.firstRewardEpochStartVotingRoundId = _initialConfig.firstRewardEpochStartVotingRoundId;
        stateData.rewardEpochDurationInVotingEpochs = _initialConfig.rewardEpochDurationInVotingEpochs;
        stateData.thresholdIncreaseBIPS = _initialConfig.thresholdIncreaseBIPS;
        stateData.messageFinalizationWindowInRewardEpochs = _initialConfig.messageFinalizationWindowInRewardEpochs;
        if (_signingPolicySetter != address(0)) {
            // Setter-mode (home) deployments never charge a verify() fee, so seeded fees, fee
            // exemptions and a fee-collection address are all meaningless here; reject them to
            // catch a misconfigured home config.
            require(_initialConfig.feeConfigs.length == 0, FeeConfigNotAllowed());
            require(_initialConfig.feeExemptAddresses.length == 0, FeeExemptionsNotAllowed());
            require(_initialConfig.feeCollectionAddress == address(0), FeeConfigNotAllowed());
            require(_initialConfig.feeToken == address(0), FeeConfigNotAllowed());
            // A home deployment must bind policy and message digests to its own chain.
            require(
                _initialConfig.sourceChainId == block.chainid,
                SourceChainIdMismatchOnHomeDeploy()
            );
            signingPolicySetter = _signingPolicySetter;
            stateData.noSigningPolicyRelay = true;
            emit SigningPolicySetterSet(_signingPolicySetter);
        } else {
            // In relay mode a zero fee-collection address would burn collected fees, so reject it.
            require(_initialConfig.feeCollectionAddress != address(0), FeeCollectionAddressZero());
            feeCollectionAddress = _initialConfig.feeCollectionAddress;
            emit FeeCollectionAddressSet(_initialConfig.feeCollectionAddress);
            // Seed the fee token and fee table so a mirror on a chain without a native token
            // charges in the right medium from block one. Relay mode only — the setter-mode
            // branch above requires them empty/zero. The self-contained ProtocolFeesSet event
            // is always emitted (like in setProtocolFees), so every relay-mode deployment
            // announces its complete fee configuration exactly once at initialization
            // (zero token = native fees; protocols not listed are free).
            _setProtocolFees(_initialConfig.feeToken, _initialConfig.feeConfigs);
        }
        // Seed initial verify() fee exemptions (e.g. DVN adapters) so they are exempt from block
        // one, with no post-deploy governance round-trip. Relay mode only — the setter-mode branch
        // above requires this list empty. The owner can grant/revoke later via setFeeExemptions.
        for (uint256 i = 0; i < _initialConfig.feeExemptAddresses.length; i++) {
            address exemptAccount = _initialConfig.feeExemptAddresses[i];
            require(exemptAccount != address(0), FeeExemptAddressZero());
            feeExemptAddress[exemptAccount] = true;
            emit FeeExemptionSet(exemptAccount, true);
        }
        // The source-network id is mandatory on every deployment — home, mirror and
        // old-relay migration alike. A live
        // signing-policy setter (home deploy) additionally forces it to this chain (checked above).
        require(_initialConfig.sourceChainId != 0, SourceChainIdZero());
        sourceChainId = _initialConfig.sourceChainId;
        // The owner-timelock duration is deploy-configured so the owner (a multisig) needs no
        // post-deploy ceremony call. Writing the ERC-7201 namespaced state via the base's
        // internal getState() preserves the base contract's ERC-7201 storage layout; the guard
        // matches setTimelockDuration.
        require(
            _initialConfig.timelockDurationSeconds <= MAX_TIMELOCK_DURATION_SECONDS,
            TimelockDurationTooLong()
        );
        getState().timelockDurationSeconds = _initialConfig.timelockDurationSeconds;
        emit TimelockDurationSet(_initialConfig.timelockDurationSeconds);
        if (address(_oldRelay) != address(0)) {
            // Old-relay migration is HOME-ONLY (setter mode). Relay-mode mirrors use their local
            // fee configuration and seed a source snapshot instead of delegating pre-boundary reads.
            // Combined with the setter-mode check on the old relay below, this makes every
            // supported Relay in the configured chain fee-free: setter-mode initialization
            // rejects fee configs, fee mutators (where present) require relay mode, and setter
            // mode cannot be cleared. verify() relies on that invariant and forwards no value
            // on the old-relay path.
            require(_signingPolicySetter != address(0), OldRelayNotAllowedInRelayMode());
            // The old relay must itself be a home (setter-mode) deployment.
            require(_oldRelay.signingPolicySetter() != address(0), OldRelayIncompatible());
            (
                ,
                uint32 firstVotingRoundStartTs,
                uint8 votingEpochDurationSeconds,
                uint32 firstRewardEpochStartVotingRoundId,
                uint16 rewardEpochDurationInVotingEpochs,
                ,,,,,
            ) = _oldRelay.stateData();
            require(_initialConfig.firstVotingRoundStartTs == firstVotingRoundStartTs, OldRelayWrongStartTs());
            require(
                _initialConfig.rewardEpochDurationInVotingEpochs == rewardEpochDurationInVotingEpochs,
                OldRelayWrongRewardEpochDuration()
            );
            require(
                _initialConfig.firstRewardEpochStartVotingRoundId == firstRewardEpochStartVotingRoundId,
                OldRelayWrongFirstRewardEpochStart()
            );
            require(
                _initialConfig.votingEpochDurationSeconds == votingEpochDurationSeconds,
                OldRelayWrongVotingEpochDuration()
            );
            oldRelay = _oldRelay;
        }
    }

    /**
     * @inheritdoc IIRelay
     */
    function setSigningPolicy(
        // using memory instead of calldata as called from another contract where signing policy is already in memory
        SigningPolicy memory _signingPolicy
    )
        external onlySigningPolicySetter
        returns (bytes32)
    {
        // The trusted signing policy setter is responsible for nonzero unique voters, canonical voter
        // order and normalized weights. This function validates only the structural and threshold
        // constraints below.
        require(stateData.lastInitializedRewardEpoch + 1 == _signingPolicy.rewardEpochId, NotNextRewardEpoch());
        // Policy selection reads startingVotingRoundIds[rewardEpochId + 1] and therefore requires
        // non-decreasing startVotingRoundId values across epochs. The setter must preserve this invariant;
        // relay-mode deployments rely on quorum-signed policies preserving the same invariant.
        require(_signingPolicy.voters.length > 0, SigningPolicyEmpty());
        require(_signingPolicy.voters.length <= MAX_VOTERS, TooManyVoters());
        require(_signingPolicy.voters.length == _signingPolicy.weights.length, VotersWeightsSizeMismatch());
        uint256 totalWeight = 0;
        for (uint256 i = 0; i < _signingPolicy.weights.length; i++) {
            totalWeight += _signingPolicy.weights[i];
        }
        require(totalWeight < 2**16, TotalWeightTooBig());
        require(
            uint256(_signingPolicy.threshold) * uint256(THRESHOLD_BIPS) >= totalWeight * MIN_THRESHOLD_BIPS,
            ThresholdTooLow()
        );
        require(
            uint256(_signingPolicy.threshold) * uint256(THRESHOLD_BIPS) <= totalWeight * MAX_THRESHOLD_BIPS,
            ThresholdTooHigh()
        );

        uint256 numberOfVoters = _signingPolicy.voters.length;
        uint256 policyLength = SIGNING_POLICY_PREFIX_BYTES + numberOfVoters * ADDRESS_AND_WEIGHT_BYTES;
        // One word of slack so the packed 32-byte mstores below never write outside the allocation;
        // the length is shrunk to the real encoded size right after.
        bytes memory signingPolicyBytes = new bytes(policyLength + 32);
        assembly ("memory-safe") {
            mstore(signingPolicyBytes, policyLength)
        }

        // _signingPolicy.rewardEpochId is uint24 (see IIRelay.SigningPolicy), so the packing
        // below is lossless and matches the mapping key — no >2**24 truncation is possible.
        bytes memory prefix = abi.encodePacked(
            uint16(numberOfVoters),
            _signingPolicy.rewardEpochId,
            _signingPolicy.startVotingRoundId,
            _signingPolicy.threshold,
            _signingPolicy.seed
        );
        assembly ("memory-safe") {
            mcopy(add(signingPolicyBytes, 0x20), add(prefix, 0x20), SIGNING_POLICY_PREFIX_BYTES)
        }
        for (uint256 i = 0; i < numberOfVoters; i++) {
            address voter = _signingPolicy.voters[i];
            uint256 weight = _signingPolicy.weights[i];
            assembly ("memory-safe") {
                let ptr := add(
                    add(signingPolicyBytes, 0x20),
                    add(SIGNING_POLICY_PREFIX_BYTES, mul(i, ADDRESS_AND_WEIGHT_BYTES))
                )
                // 20-byte address followed by the 2-byte weight; each mstore writes a full word whose
                // tail is overwritten by the next write (the last one lands in the slack word above)
                mstore(ptr, shl(96, voter))
                mstore(add(ptr, ADDRESS_BYTES), shl(240, weight))
            }
        }

        // Chain-domain binding: the stored signing-policy hash commits to the configured
        // source network: keccak256(sourceChainId ‖ signingPolicyBytes), one keccak over the 32-byte
        // source id followed by the raw encoded policy (no padding). Signatures over policies (and,
        // via the analogous digest in relay(), over protocol messages) minted for another network are
        // thereby rejected even under a fully overlapping voter set. On a home deploy
        // sourceChainId == block.chainid.
        bytes32 currentHash = keccak256(abi.encodePacked(sourceChainId, signingPolicyBytes));
        toSigningPolicyHashPrivate[_signingPolicy.rewardEpochId] = currentHash;
        stateData.lastInitializedRewardEpoch = _signingPolicy.rewardEpochId;
        startingVotingRoundIds[_signingPolicy.rewardEpochId] = _signingPolicy.startVotingRoundId;
        emit SigningPolicyInitialized(
            _signingPolicy.rewardEpochId,
            _signingPolicy.startVotingRoundId,
            _signingPolicy.threshold,
            _signingPolicy.seed,
            _signingPolicy.voters,
            _signingPolicy.weights,
            signingPolicyBytes,
            uint64(block.timestamp)
        );

        return currentHash;
    }

    /**
     * @inheritdoc IRelay
     */
    function verifyCustomSignature(
        bytes calldata _relayMessage,
        bytes32 _messageHash
    ) external returns (uint256 _rewardEpochId) {
        return _verifyCustomSignature(_relayMessage, _messageHash);
    }

    /**
     * @inheritdoc IRelay
     * @dev The override travels to the relay() self-call through a transient (EIP-1153) slot,
     * so relay()'s calldata layout and 35-byte return discriminator stay untouched.
     * The slot is cleared before returning; on revert the tstore is rolled back with the frame,
     * so no override can ever leak into a later call of the same transaction.
     */
    function verifyCustomSignatureWithThreshold(
        bytes calldata _relayMessage,
        bytes32 _messageHash,
        uint16 _thresholdBIPS
    )
        external
        returns (uint256 _rewardEpochId)
    {
        // Values of 100% and above can never be satisfied under the strict weight > threshold
        // comparison — fail fast instead of burning the signature loop on them.
        require(_thresholdBIPS < THRESHOLD_BIPS, ThresholdTooHigh());
        // Zero is the no-override sentinel in the transient slot, so 0 falls back to the signing
        // policy's own threshold — the Fdc2RequestHeader.thresholdBIPS convention.
        uint256 tslot = TSLOT_THRESHOLD_OVERRIDE;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            tstore(tslot, _thresholdBIPS)
        }
        _rewardEpochId = _verifyCustomSignature(_relayMessage, _messageHash);
        // solhint-disable-next-line no-inline-assembly
        assembly {
            tstore(tslot, 0)
        }
    }

    /**
     * @inheritdoc IIRelay
     * @dev Relay-mode only: setter-mode (home) deployments never charge verify() fees, so
     * the setter fail-closes there (mirrors the initialize() seeding rule). With a nonzero
     * timelock duration the call is queued for permissionless execution after its ETA;
     * with zero it applies immediately (see IOwnableWithTimelock).
     */
    function setProtocolFees(
        address _feeToken,
        FeeConfig[] calldata _feeConfigs
    )
        external
        onlyOwnerWithTimelock
    {
        require(signingPolicySetter == address(0), FeeConfigNotAllowed());
        _setProtocolFees(_feeToken, _feeConfigs);
    }

    /**
     * @inheritdoc IIRelay
     * @dev Relay-mode only — setter-mode deployments charge no fee, so exemptions are
     * meaningless there (mirrors the initialize() seeding rule); same timelock semantics
     * as setProtocolFees.
     */
    function setFeeExemptions(
        FeeExemption[] calldata _exemptions
    )
        external
        onlyOwnerWithTimelock
    {
        require(signingPolicySetter == address(0), FeeExemptionsNotAllowed());
        for (uint256 i = 0; i < _exemptions.length; i++) {
            address account = _exemptions[i].account;
            require(account != address(0), FeeExemptAddressZero());
            feeExemptAddress[account] = _exemptions[i].exempt;
            emit FeeExemptionSet(account, _exemptions[i].exempt);
        }
    }

    /**
     * @inheritdoc IIRelay
     * @dev Relay-mode only (setter-mode deployments never collect fees); same timelock
     * semantics as setProtocolFees. The nonzero guard is load-bearing: a zero recipient
     * would burn every collected fee.
     */
    function setFeeCollectionAddress(
        address _feeCollectionAddress
    )
        external
        onlyOwnerWithTimelock
    {
        require(signingPolicySetter == address(0), FeeConfigNotAllowed());
        require(_feeCollectionAddress != address(0), FeeCollectionAddressZero());
        feeCollectionAddress = payable(_feeCollectionAddress);
        emit FeeCollectionAddressSet(_feeCollectionAddress);
    }

    /**
     * @inheritdoc IIRelay
     * @dev Setter-mode only — the deployment mode is fixed at initialize, so a relay-mode
     * deployment can never gain a setter and a setter-mode one can never clear it; same
     * timelock semantics as setProtocolFees.
     */
    function setSigningPolicySetter(
        address _signingPolicySetter
    )
        external
        onlyOwnerWithTimelock
    {
        require(signingPolicySetter != address(0), SigningPolicySetterNotAllowed());
        require(_signingPolicySetter != address(0), SigningPolicySetterZero());
        signingPolicySetter = _signingPolicySetter;
        emit SigningPolicySetterSet(_signingPolicySetter);
    }

    /////////////////////////////// UUPS UPGRADABLE ///////////////////////////////

    /// Returns the current implementation address behind the proxy.
    function implementation() external view returns (address) {
        return ERC1967Utils.getImplementation();
    }

    /**
     * Upgrades the UUPS implementation through the owner-timelock path: with a nonzero
     * duration the exact call is queued for permissionless execution after its ETA; with
     * zero it executes immediately. Only the per-chain owner can queue; on Flare this is
     * Flare governance, on other chains the designated multisig.
     * @param _newImplementation The new implementation address.
     * @param _data Optional post-upgrade initialization calldata.
     */
    function upgradeToAndCall(
        address _newImplementation,
        bytes memory _data
    )
        public payable override
        onlyOwnerWithTimelock
    {
        super.upgradeToAndCall(_newImplementation, _data);
    }

    /// @dev Empty: authorization is `onlyOwnerWithTimelock` on the `upgradeToAndCall`
    ///      wrapper above.
    // solhint-disable-next-line no-empty-blocks
    function _authorizeUpgrade(
        address _newImplementation
    )
        internal override
    {}

    /**
     * @inheritdoc IRelay
     */
    function relay() external returns (bytes memory){
        // Read once here; bound below into the signing-policy hash (threaded into
        // the calculateSigningPolicyHash helper as _sourceChainId) and, directly in the
        // main assembly body, into the protocol-message digest.
        uint256 srcChainId = sourceChainId;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            // Helper function to revert with a 4-byte custom-error selector (declared on
            // IRelay; the ERR_* constants are compile-time keccak folds of the signatures).
            function revertWithError(_memPtr, _selector) {
                mstore(_memPtr, shl(224, _selector))
                revert(_memPtr, 4)
            }

            function assignStruct(_structObj, _valOffset, _valMask, newVal)
                -> _newStructObj
            {
                _newStructObj := or(
                    and(
                        // zeroing the field
                        _structObj,
                        not(
                            // zeroing mask
                            shl(_valOffset, _valMask)
                        )
                    ),
                    shl(_valOffset, newVal)
                )
            }

            // Helper function to assign value to right aligned byte encoded struct like object
            function structValue(_structObj, _valOffset, _valMask) -> _val {
                _val := and(shr(_valOffset, _structObj), _valMask)
            }

            // Helper function to calculate the expected reward epoch id from voting round id
            // Here the constants should be set properly
            function rewardEpochIdFromVotingRoundId(
                _stateDataObj,
                _votingRoundId
            ) -> _rewardEpochId {
                let firstRewardEpochStartVotingRoundId := structValue(
                    _stateDataObj,
                    SD_BOFF_firstRewardEpochStartVotingRoundId,
                    SD_MASK_firstRewardEpochStartVotingRoundId
                )
                if lt(_votingRoundId, firstRewardEpochStartVotingRoundId) {
                    revertWithError(mload(0x40), ERR_INVALID_VOTING_ROUND_ID)
                }
                _rewardEpochId := div(
                    sub(
                        _votingRoundId,
                        firstRewardEpochStartVotingRoundId
                    ),
                    structValue(
                        _stateDataObj,
                        SD_BOFF_rewardEpochDurationInVotingEpochs,
                        SD_MASK_rewardEpochDurationInVotingEpochs
                    )
                )
            }

            // Helper function to calculate the signing policy hash: one keccak over the 32-byte
            // source chain id followed by the raw encoded policy bytes (no padding).
            // Chain-domain binding: the hash commits to the configured source network,
            // so policies minted for another network are rejected even under a fully overlapping
            // voter set. The id is set once at initialize (threaded in as _sourceChainId), so the
            // same policy verifies on every Relay that mirrors this source.
            // Writes 32 + _policyLength bytes of scratch starting at _memPos — callers pass the
            // M_9_digestScratch region so no fixed memory slot is clobbered.
            function calculateSigningPolicyHash(
                _memPos,
                _calldataPos,
                _policyLength,
                _sourceChainId
            ) -> _policyHash {
                mstore(_memPos, _sourceChainId)
                calldatacopy(add(_memPos, 0x20), _calldataPos, _policyLength)
                _policyHash := keccak256(_memPos, add(0x20, _policyLength))
            }

            function extractVotingRoundIdFromMessage(
                _signingPolicyLength
            ) -> _votingRoundId {
                _votingRoundId := structValue(
                    shr(
                        sub(256, mul(8, MESSAGE_NO_MR_BYTES)),
                        calldataload(add(SELECTOR_BYTES, _signingPolicyLength))
                    ),
                    MSG_NMR_BOFF_votingRoundId,
                    MSG_NMR_MASK_votingRoundId
                )
            }

            // Sums the voters' normalized weights of the signing policy starting at
            // _signingPolicyStart in calldata. Each weight is the WEIGHT_BYTES-wide field after
            // the voter address; reading it as the top bytes of a calldataload avoids memory use.
            function calculateTotalWeight(
                _metadata,
                _signingPolicyStart
            ) -> _totalWeight {
                let offset := add(
                    add(_signingPolicyStart, SIGNING_POLICY_PREFIX_BYTES),
                    ADDRESS_BYTES
                )
                let numberOfVoters := structValue(
                    _metadata,
                    MD_BOFF_numberOfVoters,
                    MD_MASK_numberOfVoters
                )
                for { let i := 0 } lt(i, numberOfVoters) { i := add(i, 1) } {
                    _totalWeight := add(
                        _totalWeight,
                        shr(
                            sub(256, mul(8, WEIGHT_BYTES)),
                            calldataload(add(offset, mul(i, ADDRESS_AND_WEIGHT_BYTES)))
                        )
                    )
                }
            }

            function checkThresholdConsistency(
                _memPtr,
                _metadata,
                _signingPolicyStart
            ) {
                let totalWeight := calculateTotalWeight(_metadata, _signingPolicyStart)
                if gt(totalWeight, sub(shl(16, 1),1)) {   // totalWeight > 2 ** 16 - 1
                    revertWithError(_memPtr, ERR_TOTAL_WEIGHT_TOO_BIG)
                }
                let threshold := structValue(
                    _metadata,
                    MD_BOFF_threshold,
                    MD_MASK_threshold
                )
                if lt(mul(threshold, THRESHOLD_BIPS), mul(totalWeight, MIN_THRESHOLD_BIPS)) {
                    revertWithError(_memPtr, ERR_THRESHOLD_TOO_LOW)
                }
                if gt(mul(threshold, THRESHOLD_BIPS), mul(totalWeight, MAX_THRESHOLD_BIPS)) {
                    revertWithError(_memPtr, ERR_THRESHOLD_TOO_HIGH)
                }
            }

            function setIsSecureRandomBit(_memPtr, _votingRoundId) {
                //  isSecureRandomMap[_votingRoundId / 256]
                mstore(_memPtr, div(_votingRoundId, 256)) // key (_votingRoundId / 256)
                mstore(add(_memPtr, 32), isSecureRandomMap.slot)

                sstore(
                    keccak256(_memPtr, 64),
                    or(
                        sload(keccak256(_memPtr, 64)),
                        shl(sub(255, mod(_votingRoundId, 256)), 1)
                    )
                )
            }

            // Verify a random-number Merkle proof and persist the value.
            // The calldata after the signatures must be: randomNumber (32 bytes) followed by the
            // Merkle proof (a sequence of 32-byte nodes). The leaf is
            //   keccak256(abi.encode(uint256 votingRoundId, uint256 value, uint256 isSecure))
            // and the proof is processed with OpenZeppelin sorted-pair hashing up to _memPtrMerkleRoot.
            // On success, toRandomNumberPrivate[_votingRoundId] = randomNumber; otherwise it reverts.
            // Uses scratch at _memPtr, _memPtr+32, _memPtr+64.
            function processRandomMerkleProof(
                _memPtr, _proofStart, _memPtrMerkleRoot, _votingRoundId, _isSecureRandom
            ) {
                // calldata must contain at least the 32-byte random number after the signatures
                if lt(calldatasize(), add(_proofStart, 32)) {
                    revertWithError(_memPtr, ERR_NO_RANDOM_NUMBER)
                }
                // the trailing calldata (random number + proof) must be a whole number of 32-byte words
                if iszero(eq(mod(sub(calldatasize(), _proofStart), 32), 0)) {
                    revertWithError(_memPtr, ERR_INCORRECT_MERKLE_PROOF)
                }
                // leaf = keccak256(votingRoundId || value || isSecure)
                mstore(_memPtr, _votingRoundId)
                calldatacopy(add(_memPtr, 32), _proofStart, 32) // random number value
                mstore(add(_memPtr, 64), _isSecureRandom)
                mstore(_memPtr, keccak256(_memPtr, 96))
                for {
                    let pos := add(_proofStart, 32)
                } lt(pos, calldatasize()) {
                    pos := add(pos, 32)
                } {
                    calldatacopy(add(_memPtr, 32), pos, 32) // proof element
                    // sorted-pair parent hash
                    if lt(mload(_memPtr), mload(add(_memPtr, 32))) {
                        mstore(_memPtr, keccak256(_memPtr, 64))
                        continue
                    }
                    mstore(add(_memPtr, 64), mload(_memPtr))
                    mstore(_memPtr, keccak256(add(_memPtr, 32), 64))
                }
                if iszero(eq(mload(_memPtr), mload(_memPtrMerkleRoot))) {
                    revertWithError(_memPtr, ERR_INVALID_RANDOM_NUMBER_PROOF)
                }
                // toRandomNumberPrivate[_votingRoundId] = randomNumber
                calldatacopy(add(_memPtr, 64), _proofStart, 32) // reload value (slots 0/32 reused as map key/slot)
                mstore(_memPtr, _votingRoundId)
                mstore(add(_memPtr, 32), toRandomNumberPrivate.slot)
                sstore(keccak256(_memPtr, 64), mload(add(_memPtr, 64)))
            }
////////////// A comment on handling of signing policy and a message /////////////////////////////////////////
//
// A relayer provides a signing policy and a message.
// Let:
// v - votingRoundId of the message
// r - reward epoch of the signing policy
// exp(v) - expected reward epoch for `v`
// s - startVotingRound of signing policy for `r`
// s+ - startVotingRound od signing policy for `r + 1` (`i` must be >= `r + 1`)
// i - reward epoch of the last initialized signing policy
//
// Analysis of all combinations. Assume i >= r. Otherwise REVERT.
//     exp(v) < r  |      REVERT
// -----------------------------------------------------------------------------------------------------------
//     exp(v) == r | v >= s    OK
//                 | v < s     REVERT
// -----------------------------------------------------------------------------------------------------------
//     exp(v) > r  |  v < s    REVERT
//                 -------------------------------------------------------------------------------------------
//                 |  v >= s            |  i = r        OK (increase threshold)
//                 |                    ----------------------------------------------------------------------
//                 |                    |  i > r      | v >= s+       REVERT (new signing policy must be used)
//                 |                    |             | v < s+        OK
//
////////////// Start of code /////////////////////////////////////////////////////////////////////////////////
            // free memory pointer
            let memPtr := mload(0x40)
            // NOTE: the struct is packed in reverse order of bytes

            // stateData loaded into memory to slot M_5_stateData
            mstore(add(memPtr, M_5_stateData), sload(stateData.slot))

            ///////////// Extracting signing policy metadata /////////////
            if lt(calldatasize(), add(SELECTOR_BYTES, METADATA_BYTES)) {
                revertWithError(memPtr, ERR_INVALID_SIGN_POLICY_METADATA)
            }

            // read the metadata prefix directly from calldata, shifted to the right of bytes32
            // (the length check above guarantees the METADATA_BYTES are all within calldata)
            let metadata := shr(sub(256, mul(8, METADATA_BYTES)), calldataload(SELECTOR_BYTES))
            let rewardEpochId := structValue(
                metadata,
                MD_BOFF_rewardEpochId,
                MD_MASK_rewardEpochId
            )

            let signingPolicyLength := add(
                SIGNING_POLICY_PREFIX_BYTES,
                mul(
                    structValue(
                        metadata,
                        MD_BOFF_numberOfVoters,
                        MD_MASK_numberOfVoters
                    ),
                    ADDRESS_AND_WEIGHT_BYTES
                )
            )

            // The calldata must be of length at least 4 function selector + signingPolicyLength + 1 protocolId
            if lt(
                calldatasize(),
                add(SELECTOR_BYTES, add(signingPolicyLength, PROTOCOL_ID_BYTES))
            ) {
                revertWithError(memPtr, ERR_INVALID_SIGN_POLICY_LENGTH)
            }

            ///////////// Verifying signing policy /////////////
            // signing policy hash temporarily stored to slot M_2
            // (computed in the M_9 digest scratch region — stateData at M_5 stays live)
            mstore(
                add(memPtr, M_2_signingPolicyHashTmp),
                calculateSigningPolicyHash(
                    add(memPtr, M_9_digestScratch),
                    SELECTOR_BYTES,
                    signingPolicyLength,
                    srcChainId
                )
            )

            //  toSigningPolicyHashPrivate[rewardEpochId] -> existingSigningPolicyHash
            mstore(memPtr, rewardEpochId) // key (rewardEpochId)
            mstore(add(memPtr, M_1), toSigningPolicyHashPrivate.slot)

            // store existing signing policy hash to slot M_3 temporarily
            mstore(
                add(memPtr, M_3_existingSigningPolicyHashTmp),
                sload(keccak256(memPtr, 64))
            )

            // From here on we have calldatasize() > 4 + signingPolicyLength

            ///////////// Verifying signing policy /////////////
            if iszero(
                eq(
                    mload(add(memPtr, M_2_signingPolicyHashTmp)),
                    mload(add(memPtr, M_3_existingSigningPolicyHashTmp))
                )
            ) {
                revertWithError(memPtr, ERR_SIGNING_POLICY_HASH_MISMATCH)
            }

            // Extracting protocolId, votingRoundId and isSecureRandom
            // 1 bytes - protocolId
            // 4 bytes - votingRoundId
            // 1 bytes - isSecureRandom (bool)
            // 32 bytes - merkleRoot
            // message length: 38

            let protocolId := shr(
                sub(256, mul(8, PROTOCOL_ID_BYTES)), // move to the rightmost position
                calldataload(add(SELECTOR_BYTES, signingPolicyLength))
            )

            let signatureStart := 0 // First index of signatures in calldata
            let threshold := structValue(
                metadata,
                MD_BOFF_threshold,
                MD_MASK_threshold
            )

            // Caller-chosen threshold override in BIPS of the policy's total normalized weight,
            // set only by verifyCustomSignatureWithThreshold's transient slot for the duration
            // of its self-call (0 on every top-level call).
            // SECURITY: gated to protocolId == 1 — the pure verification path, which stores
            // nothing and only returns — so an override can never lower the quorum for Mode-1
            // policy relay or Mode-2 finalization even though the wrapper forwards arbitrary
            // caller calldata. (The cross-epoch thresholdIncreaseBIPS bump below is unreachable
            // for protocolId == 1: its messageRewardEpochId always equals rewardEpochId.)
            if eq(protocolId, 1) {
                let overrideBIPS := tload(TSLOT_THRESHOLD_OVERRIDE)
                if gt(overrideBIPS, 0) {
                    // The policy metadata carries only the threshold, so sum the total weight
                    // from calldata (shared with checkThresholdConsistency). Setter/Mode-1 policies
                    // additionally bound totalWeight to 16 bits; even an opaque initial policy is
                    // bounded by MAX_VOTERS and the uint16 weight encoding, so this product is safe.
                    // Use floor division with the strict weight > threshold comparison. This is
                    // exactly equivalent to:
                    // weight * THRESHOLD_BIPS > totalWeight * overrideBIPS.
                    // Rounding up here would apply two conservative steps and make valid
                    // fractional BIPS thresholds (including 9999 BIPS with all weight) impossible.
                    threshold := div(
                        mul(calculateTotalWeight(metadata, SELECTOR_BYTES), overrideBIPS),
                        THRESHOLD_BIPS
                    )
                }
            }

            ///////////// Preparation of message hash /////////////
            // protocolId > 0 means we are relaying or checking the validity of signatures (Mode 2)
            // The signed hash is the message hash and it gets prepared into slot 32
            if gt(protocolId, 0) {
                let memPtrGP0 := mload(0x40)
                signatureStart := add(
                    SELECTOR_BYTES,
                    add(signingPolicyLength, MESSAGE_BYTES)
                )
                if lt(calldatasize(), signatureStart) {
                    revertWithError(memPtrGP0, ERR_TOO_SHORT_MESSAGE)
                }

                calldatacopy(
                    memPtrGP0,
                    add(SELECTOR_BYTES, signingPolicyLength),
                    MESSAGE_BYTES
                )

                let votingRoundId := structValue(
                    shr(
                        sub(256, mul(8, MESSAGE_NO_MR_BYTES)),
                        mload(memPtrGP0)
                    ),
                    MSG_NMR_BOFF_votingRoundId,
                    MSG_NMR_MASK_votingRoundId
                )
                // Check if merkleRootsPrivate[protocolId][votingRoundId] is set
                // NOTE: M1 is already consumed. Hence using M_3 and M_4
                mstore(add(memPtrGP0, M_3), protocolId) // key 1 (protocolId)
                mstore(add(memPtrGP0, M_4), merkleRootsPrivate.slot) // merkleRoot slot
                mstore(add(memPtrGP0, M_4), keccak256(add(memPtrGP0, M_3), 64))
                mstore(add(memPtrGP0, M_3), votingRoundId) // key 2 (votingRoundId)

                if gt(sload(keccak256(add(memPtrGP0, M_3), 64)), 0) {
                    revertWithError(memPtrGP0, ERR_ALREADY_RELAYED)
                }

                if eq(protocolId, 1) {
                    // votingRoundId should be 0
                    if votingRoundId {
                        revertWithError(memPtrGP0, ERR_WRONG_MESSAGE_FORMAT)
                    }
                }

                // isSecureRandom is a bool, and it carries meaning only for the random-number
                // protocol: 0 or 1 there, 0 for every other protocol id (protocolId == 1
                // included). Enforced once here, ahead of every sink, so no downstream path has
                // to normalize a byte and no non-canonical value can reach the random leaf, the
                // stored quality bit, or the bool field of ProtocolMessageRelayed.
                {
                    let maxIsSecureRandom := 0
                    if eq(
                        protocolId,
                        structValue(
                            mload(add(memPtrGP0, M_5_stateData)),
                            SD_BOFF_randomNumberProtocolId,
                            SD_MASK_randomNumberProtocolId
                        )
                    ) {
                        maxIsSecureRandom := 1
                    }
                    if gt(
                        structValue(
                            shr(
                                sub(256, mul(8, MESSAGE_NO_MR_BYTES)),
                                mload(memPtrGP0)
                            ),
                            MSG_NMR_BOFF_isSecureRandom,
                            MSG_NMR_MASK_isSecureRandom
                        ),
                        maxIsSecureRandom
                    ) {
                        revertWithError(memPtrGP0, ERR_WRONG_MESSAGE_FORMAT2)
                    }
                }

                // the expected reward epoch id
                // for direct message signing (protocolId == 1)
                let messageRewardEpochId := rewardEpochId

                if iszero(eq(protocolId, 1)) {
                    messageRewardEpochId := rewardEpochIdFromVotingRoundId(
                        mload(add(memPtrGP0, M_5_stateData)),
                        votingRoundId
                    )
                }

                // Given a signing policy for reward epoch R one can sign either messages
                // in reward epochs R or later
                if lt(messageRewardEpochId, rewardEpochId) {
                    revertWithError(memPtrGP0, ERR_WRONG_SIGN_POLICY_REWARD_EPOCH)
                }

                // The message must not be too old
                // This limits the influence of participants in old signing policies
                if lt(
                    add(
                        messageRewardEpochId,
                        structValue(
                            mload(add(memPtrGP0, M_5_stateData)),
                            SD_BOFF_messageFinalizationWindowInRewardEpochs,
                            SD_MASK_messageFinalizationWindowInRewardEpochs
                        )
                    ),
                    structValue(
                        mload(add(memPtrGP0, M_5_stateData)),
                        SD_BOFF_lastInitializedRewardEpoch,
                        SD_MASK_lastInitializedRewardEpoch
                    )
                ){
                    revertWithError(memPtrGP0, ERR_MESSAGE_TOO_OLD)
                }

                let startingVotingRoundId := structValue(
                    metadata,
                    MD_BOFF_startingVotingRoundId,
                    MD_MASK_startingVotingRoundId
                )
                // in case the reward epoch id start gets delayed -> signing policy for earlier
                // reward epoch must be provided
                if and(iszero(eq(protocolId, 1)), lt(votingRoundId, startingVotingRoundId)) {
                    revertWithError(memPtrGP0, ERR_DELAYED_SIGN_POLICY)
                }

                if gt(messageRewardEpochId, rewardEpochId) {
                    let lastInitializedRewardEpoch :=
                        structValue(
                            mload(add(memPtrGP0, M_5_stateData)),
                            SD_BOFF_lastInitializedRewardEpoch,
                            SD_MASK_lastInitializedRewardEpoch
                        )
                    if gt(lastInitializedRewardEpoch, rewardEpochId) {
                        mstore(add(memPtrGP0, M_3), add(rewardEpochId, 1)) // key (rewardEpochId + 1)
                        mstore(add(memPtrGP0, M_4), startingVotingRoundIds.slot) // startingVotingRoundIds slot
                        let nextStartingVotingRoundId := sload(keccak256(add(memPtrGP0, M_3), 64))
                        // if votingRoundId >= nextStartingVotingRoundId, revert
                        if gt(add(votingRoundId, 1), nextStartingVotingRoundId) {
                            revertWithError(memPtrGP0, ERR_MUST_USE_NEW_SIGN_POLICY)
                        }
                    }
                    if eq(lastInitializedRewardEpoch, rewardEpochId) {
                        // Integer division rounds the scaled threshold down. Combined with the strict
                        // weight > threshold acceptance test, this differs from the exact rational
                        // threshold by less than one normalized weight unit.
                        threshold := div(
                            mul(
                                threshold,
                                structValue(
                                    mload(add(memPtrGP0, M_5_stateData)),
                                    SD_BOFF_thresholdIncreaseBIPS,
                                    SD_MASK_thresholdIncreaseBIPS
                                )
                            ),
                            THRESHOLD_BIPS
                        )
                    }

                    // At this point we have situation:
                    // - messageRewardEpochId is not initialized -> increased threshold
                    // - messageRewardEpochId is initialized -> votingRoundId < nextStartingVotingRoundId
                    // consequently the threshold can stay the same
                }
                // all revert conditions are checked

                // Prepare the signed digest into slot M_1.
                // Chain-domain binding: the digest commits to the configured source in a
                // single keccak over the raw content: M_1 <- keccak256(sourceChainId ‖ message).
                // The 70-byte preimage is assembled in the M_9 digest scratch region (same as the
                // signing-policy hash), so every fixed slot stays intact.
                mstore(add(memPtrGP0, M_9_digestScratch), srcChainId)
                calldatacopy(
                    add(memPtrGP0, add(M_9_digestScratch, 0x20)),
                    add(SELECTOR_BYTES, signingPolicyLength),
                    MESSAGE_BYTES
                )
                mstore(
                    add(memPtrGP0, M_1),
                    keccak256(add(memPtrGP0, M_9_digestScratch), add(0x20, MESSAGE_BYTES))
                )
            }

            // protocolId == 0 means we are relaying new signing policy (Mode 1)
            // The signed hash is the signing policy hash and it gets prepared into slot 32

            if eq(protocolId, 0) {
                // Check if signing policy relay is enabled

                if gt(
                    structValue(
                        mload(add(mload(0x40), M_5_stateData)),
                        SD_BOFF_noSigningPolicyRelay,
                        SD_MASK_noSigningPolicyRelay
                    ),
                    0
                ) {
                    revertWithError(mload(0x40), ERR_SIGN_POLICY_RELAY_DISABLED)
                }

                if lt(
                    calldatasize(),
                    add(
                        SELECTOR_BYTES,
                        add(
                            signingPolicyLength,
                            add(PROTOCOL_ID_BYTES, METADATA_BYTES)
                        )
                    )
                ) {
                    revertWithError(mload(0x40), ERR_NO_NEW_SIGN_POLICY_SIZE)
                }

                // New metadata
                calldatacopy(
                    mload(0x40),
                    add(
                        SELECTOR_BYTES,
                        add(PROTOCOL_ID_BYTES, signingPolicyLength)
                    ),
                    METADATA_BYTES
                )

                let newMetadata := shr(
                    sub(256, mul(8, METADATA_BYTES)),
                    mload(mload(0x40))
                )
                let newNumberOfVoters := structValue(
                    newMetadata,
                    MD_BOFF_numberOfVoters,
                    MD_MASK_numberOfVoters
                )
                // must be at least one voter
                if eq(newNumberOfVoters, 0) {
                    revertWithError(mload(0x40), ERR_SIGNING_POLICY_EMPTY)
                }
                // must be at most MAX_VOTERS
                if gt(newNumberOfVoters, MAX_VOTERS) {
                    revertWithError(mload(0x40), ERR_TOO_MANY_VOTERS)
                }

                let newSigningPolicyLength := add(
                    SIGNING_POLICY_PREFIX_BYTES,
                    mul(newNumberOfVoters, ADDRESS_AND_WEIGHT_BYTES)
                )

                signatureStart := add(
                    SELECTOR_BYTES,
                    add(
                        signingPolicyLength,
                        add(PROTOCOL_ID_BYTES, newSigningPolicyLength)
                    )
                )

                if lt(calldatasize(), signatureStart) {
                    revertWithError(mload(0x40), ERR_WRONG_SIZE_FOR_NEW_SIGN_POLICY)
                }

                let newSigningPolicyRewardEpochId := structValue(
                    newMetadata,
                    MD_BOFF_rewardEpochId,
                    MD_MASK_rewardEpochId
                )

                let tmpLastInitializedRewardEpochId := structValue(
                    mload(add(mload(0x40), M_5_stateData)),
                    SD_BOFF_lastInitializedRewardEpoch,
                    SD_MASK_lastInitializedRewardEpoch
                )

                // should the old signing policy reward epoch id be the last intialized one
                if iszero(
                    eq(
                        tmpLastInitializedRewardEpochId,
                        rewardEpochId
                    )
                ) {
                    revertWithError(mload(0x40), ERR_NOT_WITH_LAST_INITIALIZED)
                }

                // Should be next reward epoch id
                if iszero(
                    eq(
                        add(1, tmpLastInitializedRewardEpochId),
                        newSigningPolicyRewardEpochId
                    )
                ) {
                    revertWithError(mload(0x40), ERR_NOT_NEXT_REWARD_EPOCH)
                }

                // Check the threshold consistency
                checkThresholdConsistency(
                    mload(0x40),
                    newMetadata,
                    add(
                        SELECTOR_BYTES,
                        add(PROTOCOL_ID_BYTES, signingPolicyLength)
                    )
                )

                // computed in the M_9 digest scratch region — stateData at M_5 (read by the
                // assignStruct update just below) stays live
                let newSigningPolicyHash := calculateSigningPolicyHash(
                    add(mload(0x40), M_9_digestScratch),
                    add(
                        SELECTOR_BYTES,
                        add(signingPolicyLength, PROTOCOL_ID_BYTES)
                    ),
                    newSigningPolicyLength,
                    srcChainId
                )
                // Update temporary stateData. If the weight of signatures if
                // over threshold, then this will be written to storage
                mstore(
                    add(mload(0x40), M_5_stateData),
                    assignStruct(
                        mload(add(mload(0x40), M_5_stateData)),
                        SD_BOFF_lastInitializedRewardEpoch,
                        SD_MASK_lastInitializedRewardEpoch,
                        newSigningPolicyRewardEpochId
                    )
                )

                // These two signing-policy writes precede the signature-aggregate acceptance check.
                // Every insufficient-weight path reaches the final transaction revert, which unwinds
                // both writes and the event below. Changes to the control flow must preserve this
                // atomic rollback invariant.
                // startingVotingRoundId[newSigningPolicyRewardEpochId] = newMetadata.startingVotingRoundId
                mstore(mload(0x40), newSigningPolicyRewardEpochId)
                mstore(add(mload(0x40), M_1), startingVotingRoundIds.slot)
                sstore(
                    keccak256(mload(0x40), 64),
                    structValue(
                        newMetadata,
                        MD_BOFF_startingVotingRoundId,
                        MD_MASK_startingVotingRoundId
                    )
                )

                // toSigningPolicyHashPrivate[newSigningPolicyRewardEpochId] = newSigningPolicyHash
                mstore(mload(0x40), newSigningPolicyRewardEpochId)
                mstore(add(mload(0x40), M_1), toSigningPolicyHashPrivate.slot)
                sstore(keccak256(mload(0x40), 64), newSigningPolicyHash)
                // Prepare the hash on slot 32 for signature verification
                mstore(add(mload(0x40), M_1), newSigningPolicyHash)
                // IMPORTANT: assumes that if threshold is not sufficient, the transaction will be reverted

                // emit event
                // use temporarily M_3 to store event signature
                mstore(add(mload(0x40), M_3), "SigningPolicyRelayed(uint256)")
                log2(mload(0x40), 0, keccak256(add(mload(0x40), M_3), 29), newSigningPolicyRewardEpochId)
            }

            // Assumptions here:
            // - memPtr (slot M_1) contains either protocol message merkle root hash or new signing policy hash
            // - signatureStart points to the first signature in calldata
            // - We are sure that calldatasize() >= signatureStart

            // Use M_2 temporarily to extract number of signatures
            // Note that M_1 is used for the hash
            if lt(
                calldatasize(),
                add(signatureStart, NUMBER_OF_SIGNATURES_BYTES)
            ) {
                revertWithError(memPtr, ERR_NO_SIGNATURE_COUNT)
            }

            calldatacopy(
                add(memPtr, M_2),
                signatureStart,
                NUMBER_OF_SIGNATURES_BYTES
            )
            let numberOfSignatures := and(
                shr(
                    NUMBER_OF_SIGNATURES_RIGHT_SHIFT_BITS,
                    mload(add(memPtr, M_2))
                ),
                NUMBER_OF_SIGNATURES_MASK
            )
            signatureStart := add(signatureStart, NUMBER_OF_SIGNATURES_BYTES)
            // Stash signatureStart for the random-proof trailer (read deep in the random branch
            // where keeping it on the stack would risk stack-too-deep)
            mstore(add(memPtr, M_8_signatureStart), signatureStart)
            if lt(
                calldatasize(),
                add(
                    signatureStart,
                    mul(numberOfSignatures, SIGNATURE_WITH_INDEX_BYTES)
                )
            ) {
                revertWithError(memPtr, ERR_NOT_ENOUGH_SIGNATURES)
            }

            // Prefixed hash calculation
            // 4-bytes padded prefix into slot 0
            mstore(memPtr, "0000\x19Ethereum Signed Message:\n32")
            // Prefixed hash into slot 0, skipping 4-bytes of 0-prefix
            mstore(memPtr, keccak256(add(memPtr, 4), 60))

            // Processing signatures. Memory map:
            // memPtr (slot 0)  | prefixedHash
            // M_1              | v
            // M_2              | r, signer
            // M_3              | s, expectedSigner + weight
            // M_4              | index

            for {
                let numberOfVoters := structValue(
                    metadata,
                    MD_BOFF_numberOfVoters,
                    MD_MASK_numberOfVoters
                )
                let i := 0
                // accumulated weight of signatures
                let weight := 0
                // enforces increasing order of indices in signatures
                let nextUnusedIndex := 0
                let memPtrFor := mload(0x40)
            } lt(i, numberOfSignatures) {
                i := add(i, 1)
            } {
                // clear v - only the last byte will change
                mstore(add(memPtrFor, M_1), 0)

                calldatacopy(
                    add(memPtrFor, add(M_1, sub(32, SIGNATURE_V_BYTES))),
                    add(signatureStart, mul(i, SIGNATURE_WITH_INDEX_BYTES)), // signature position
                    SIGNATURE_WITH_INDEX_BYTES
                ) // 63 ... last byte of slot +32
                // Note that those things get set
                // - slot M_1 - the rightmost byte of 'v' gets set
                // - slot M_2    - r
                // - slot M_3    - s
                // - slot M_4   - index (only the top 2 bytes)
                let index := shr(
                    SIGNATURE_INDEX_RIGHT_SHIFT_BITS,
                    mload(add(memPtrFor, M_4))
                )

                // Index sanity checks in regard to signing policy.
                // Signing policies are not re-checked for zero-address or duplicate voters
                // (the trusted setter, or for relayed policies the signed policy hash, owns that). The
                // strictly-increasing index below prevents the same policy SLOT from being counted twice.
                // It does not prevent one ADDRESS from occupying multiple indices; threshold soundness is
                // therefore conditional on the trusted policy-ingestion path supplying unique voters.
                // A zero-address "voter" cannot be matched because ecrecover never yields address(0)
                // (enforced by the returndatasize / zero-signer checks below).
                if gt(add(index, 1), numberOfVoters) {
                    revertWithError(memPtrFor, ERR_INDEX_OUT_OF_RANGE)
                }

                if lt(index, nextUnusedIndex) {
                    revertWithError(memPtrFor, ERR_INDEX_OUT_OF_ORDER)
                }
                nextUnusedIndex := add(index, 1)

                // Reject non-canonical ECDSA signatures (defence-in-depth; strict index
                // ordering already neutralizes malleability double-counting). v must be 27 or 28,
                // and s must lie in the lower half of the curve order (EIP-2 low-s).
                if iszero(or(
                    eq(and(mload(add(memPtrFor, M_1)), 0xff), 27),
                    eq(and(mload(add(memPtrFor, M_1)), 0xff), 28)
                )) {
                    revertWithError(memPtrFor, ERR_BAD_V)
                }
                if gt(
                    mload(add(memPtrFor, M_3)),
                    0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                ) {
                    revertWithError(memPtrFor, ERR_BAD_S)
                }

                // ecrecover call. Address goes to slot 64, it is 0 padded
                if iszero(
                    staticcall(
                        not(0),
                        0x01,
                        memPtrFor,
                        0x80,
                        add(memPtrFor, M_2),
                        32
                    )
                ) {
                    revertWithError(memPtrFor, ERR_ECRECOVER_ERROR)
                }
                if iszero(eq(returndatasize(),32)) {
                    revertWithError(memPtrFor, ERR_ECRECOVER_RETURNED_BAD_DATA)
                }
                // Require an explicit nonzero recovered signer in addition to the return-data check.
                if iszero(mload(add(memPtrFor, M_2))) {
                    revertWithError(memPtrFor, ERR_ZERO_SIGNER)
                }
                // extract expected signer address to slot no 96
                mstore(add(memPtrFor, M_3), 0) // zeroing slot for expected address

                calldatacopy(
                    add(memPtrFor, sub(add(M_3, ADDRESS_OFFSET), WEIGHT_BYTES)),
                    add(
                        add(SELECTOR_BYTES, SIGNING_POLICY_PREFIX_BYTES),
                        mul(index, ADDRESS_AND_WEIGHT_BYTES)
                    ),
                    ADDRESS_AND_WEIGHT_BYTES
                )

                // Check if the recovered signer is the expected signer
                if iszero(
                    eq(
                        mload(add(memPtrFor, M_2)),
                        shr(mul(8, WEIGHT_BYTES), mload(add(memPtrFor, M_3))) // keep the address only
                    )
                ) {
                    revertWithError(memPtrFor, ERR_WRONG_SIGNATURE)
                }

                weight := add(
                    weight,
                    and(mload(add(memPtrFor, M_3)), WEIGHT_MASK)
                )

                if gt(weight, threshold) {
                    if eq(protocolId, 0) {
                        // Store updated stateData (lastInitializedRewardEpoch)
                        sstore(
                            stateData.slot,
                            mload(add(memPtrFor, M_5_stateData))
                        )
                        // in case protocolId == 0, the new signing policy is already stored
                        // and event emitted
                        return(0,0)
                    }

                    if gt(protocolId, 0) {
                        // M_6_merkleRoot <- Merkle root
                        calldatacopy(
                            add(memPtrFor, M_6_merkleRoot),
                            add(
                                add(SELECTOR_BYTES, signingPolicyLength),
                                sub(MESSAGE_BYTES, 32) // last 32 bytes are merkleRoot
                            ),
                            32
                        )
                        if eq(protocolId, 1) {
                            // This is the only relay() path that returns non-empty data
                            // (35 bytes: 32-byte merkleRoot/hash + 3-byte rewardEpochId). Every other
                            // path returns 0 bytes or reverts, so _verifyCustomSignature uses the 35-byte
                            // length as the discriminator for this path — preserve it if changing returns.
                            mstore(memPtrFor, mload(add(memPtrFor, M_6_merkleRoot)))
                            mstore(
                                add(memPtrFor, M_1),
                                shl(sub(256, mul(8, REWARD_EPOCH_ID_BYTES)), rewardEpochId)
                            )
                            return (memPtrFor, add(32, REWARD_EPOCH_ID_BYTES))
                        }

                        // Reject a zero Merkle root: it would break isFinalized and the
                        // already-relayed sentinel, and allow repeated event spam for the round).
                        if iszero(mload(add(memPtrFor, M_6_merkleRoot))) {
                            revertWithError(memPtrFor, ERR_ZERO_MERKLE_ROOT)
                        }

                        let votingRoundId := extractVotingRoundIdFromMessage(
                            signingPolicyLength
                        )

                        // writing into the map
                        mstore(memPtrFor, protocolId) // key 1 (protocolId)
                        mstore(add(memPtrFor, M_1), merkleRootsPrivate.slot) // merkleRoot slot

                        // parent map location in slot for next hashing
                        mstore(add(memPtrFor, M_1), keccak256(memPtrFor, 64))
                        mstore(memPtrFor, votingRoundId) // key 2 (votingRoundId)
                        // merkleRoot stored at merkleRootsPrivate[protocolId][votingRoundId]
                        sstore(
                            keccak256(memPtrFor, 64),
                            mload(add(memPtrFor, M_6_merkleRoot))
                        ) // set Merkle Root

                        // if protocolId != stateData.randomNumberProtocolId
                        // just emit an event
                        if iszero(
                            eq(
                                protocolId,
                                structValue(
                                    mload(add(memPtrFor, M_5_stateData)),
                                    SD_BOFF_randomNumberProtocolId,
                                    SD_MASK_randomNumberProtocolId
                                )
                            )
                        ) {
                            calldatacopy(
                                memPtrFor,
                                add(SELECTOR_BYTES, signingPolicyLength),
                                MESSAGE_NO_MR_BYTES
                            )
                            mstore(
                                memPtrFor,
                                shr(
                                    sub(256, mul(8, MESSAGE_NO_MR_BYTES)),
                                    mload(memPtrFor)
                                )
                            )

                            // Here we setup M_5 to value of isSecureRandom from message
                            // while in M_6 we have Merkle root
                            // Outside the random generating protocol message parsing requires
                            // isSecureRandom to be 0, so the emitted bool is always false here.
                            // These two fields are used for the emitted event
                            mstore(add(memPtrFor, M_5_isSecureRandom),
                                structValue(
                                    mload(memPtrFor),
                                    MSG_NMR_BOFF_isSecureRandom,
                                    MSG_NMR_MASK_isSecureRandom
                                )
                            )
                            mstore(add(memPtrFor, M_3), "ProtocolMessageRelayed(uint8,uin")
                            mstore(add(memPtrFor, M_4), "t32,bool,bytes32)")
                            log3(
                                add(memPtrFor, M_5_isSecureRandom), 64, keccak256(add(memPtrFor, M_3), 49),
                                protocolId, votingRoundId
                            )
                            return(0,0)
                        }

                        // if protocolId == stateData.randomNumberProtocolId
                        if eq(
                            protocolId,
                            structValue(
                                mload(add(memPtrFor, M_5_stateData)),
                                SD_BOFF_randomNumberProtocolId,
                                SD_MASK_randomNumberProtocolId
                            )
                        ) {
                            // Read isSecureRandom. Message parsing already constrained it to
                            // {0,1} for this protocol, so no normalization is needed here and
                            // the value fed to the leaf is exactly the signed one.
                            calldatacopy(
                                memPtrFor,
                                add(SELECTOR_BYTES, signingPolicyLength),
                                MESSAGE_NO_MR_BYTES
                            )
                            let isSecure := structValue(
                                shr(sub(256, mul(8, MESSAGE_NO_MR_BYTES)), mload(memPtrFor)),
                                MSG_NMR_BOFF_isSecureRandom,
                                MSG_NMR_MASK_isSecureRandom
                            )

                            // Verify the random Merkle proof against the signed merkleRoot and store
                            // toRandomNumberPrivate[votingRoundId] (always, so historical lookups work).
                            // The trailer (randomNumber || proof) starts right after the signatures.
                            processRandomMerkleProof(
                                memPtrFor,
                                add(
                                    mload(add(memPtrFor, M_8_signatureStart)),
                                    mul(numberOfSignatures, SIGNATURE_WITH_INDEX_BYTES)
                                ),
                                add(memPtrFor, M_6_merkleRoot),
                                votingRoundId,
                                isSecure
                            )

                            // historical secure-random bit (always, for getRandomNumberHistorical)
                            if isSecure {
                                setIsSecureRandomBit(add(memPtrFor, M_3), votingRoundId)
                            }

                            // Advance the live random pointer only for a newer round,
                            // so a stale (within-window) older round cannot regress the reported "current" random.
                            // Because the stored pointer starts at 0, configuration must ensure that the first
                            // accepted random-protocol round is greater than 0 for the pointer and secure flag
                            // to be updated.
                            if gt(
                                votingRoundId,
                                structValue(
                                    mload(add(memPtrFor, M_5_stateData)),
                                    SD_BOFF_randomVotingRoundId,
                                    SD_MASK_randomVotingRoundId
                                )
                            ) {
                                sstore(
                                    stateData.slot,
                                    assignStruct(
                                        assignStruct(
                                            mload(add(memPtrFor, M_5_stateData)),
                                            SD_BOFF_randomVotingRoundId,
                                            SD_MASK_randomVotingRoundId,
                                            votingRoundId
                                        ),
                                        SD_BOFF_isSecureRandom,
                                        SD_MASK_isSecureRandom,
                                        isSecure
                                    )
                                )
                            }

                            // emit ProtocolMessageRelayed(protocolId, votingRoundId, isSecureRandom, merkleRoot)
                            // data: isSecureRandom (M_5) + merkleRoot (still in M_6)
                            mstore(add(memPtrFor, M_5_isSecureRandom), isSecure)
                            mstore(add(memPtrFor, M_3), "ProtocolMessageRelayed(uint8,uin")
                            mstore(add(memPtrFor, M_4), "t32,bool,bytes32)")
                            log3(
                                add(memPtrFor, M_5_isSecureRandom), 64, keccak256(add(memPtrFor, M_3), 49),
                                protocolId, votingRoundId
                            )

                            // Emit RandomNumberRelayed(votingRoundId, randomNumber, isSecureRandom).
                            // data: randomNumber (M_6) + isSecureRandom (M_7); indexed topic: votingRoundId
                            calldatacopy(
                                add(memPtrFor, M_6_merkleRoot),
                                add(
                                    mload(add(memPtrFor, M_8_signatureStart)),
                                    mul(numberOfSignatures, SIGNATURE_WITH_INDEX_BYTES)
                                ),
                                32
                            )
                            mstore(add(memPtrFor, M_7_randomNumber), isSecure)
                            mstore(add(memPtrFor, M_3), "RandomNumberRelayed(uint32,uint2")
                            mstore(add(memPtrFor, M_4), "56,bool)")
                            log2(
                                add(memPtrFor, M_6_merkleRoot), 64, keccak256(add(memPtrFor, M_3), 40),
                                votingRoundId
                            )
                            return(0,0)
                        } // if protocolId == stateData.randomNumberProtocolId
                    } // if protocolId > 0
                    // this should never happen as particular cases are handled above and returns
                    // are done from there
                    revertWithError(mload(0x40), ERR_UNREACHABLE_CODE)
                }
            } // for

            // NO CODE SHOULD BE ADDED HERE
        } // assembly
        revert NotEnoughWeight();
    }

    /**
     * @inheritdoc IRelay
     */
    function verify(uint256 _protocolId, uint256 _votingRoundId, bytes32 _leaf, bytes32[] calldata _proof)
        external payable
        returns (bool)
    {
        // Read-delegation boundary: rounds below startingVotingRoundIdForInitialRewardEpochId are served by
        // the old relay (here and in merkleRoots/isFinalized/getRandomNumberHistorical). The initial
        // signing policy is supplied as an opaque hash, so deployment configuration must ensure its encoded
        // startVotingRoundId equals this boundary; otherwise locally stored roots can be shadowed or a
        // finalization gap can be created at the cutover.
        if (address(oldRelay) != address(0) && _votingRoundId < startingVotingRoundIdForInitialRewardEpochId) {
            // Fail closed if the old relay returns false rather than reverting.
            // For an intended supported Relay chain, every source is setter-mode and fee-free:
            // setter-mode initialization rejects fee configs, fee mutators (where present)
            // require relay mode, and setter mode cannot be cleared. Forward no value and refund
            // the full msg.value, matching the zero-fee/refund contract of the local path below.
            // Interface checks establish mode and timing, not implementation provenance. An
            // arbitrary contract in this slot answers the delegated verify itself and is covered
            // by the migration trust assumption (see docs/relay-security-review.md). A supported
            // source that unexpectedly enforces a nonzero fee rejects this zero-value call.
            //
            // Never delegate a round the old relay did not finalize. Its stored root is zero
            // there, and Merkle folding returns the leaf unchanged for an empty proof, so a zero
            // leaf would verify against the zero root. Mirrors the local path's NotFinalized
            // guard below; a source that cannot answer this fails closed by reverting.
            require(oldRelay.isFinalized(_protocolId, _votingRoundId), NotFinalized());
            bool ok = oldRelay.verify(_protocolId, _votingRoundId, _leaf, _proof);
            require(ok, OldRelayVerificationFailed());
            if (msg.value > 0) {
                /* solhint-disable avoid-low-level-calls */
                (bool oldRefundOk, ) = msg.sender.call{value: msg.value}("");
                /* solhint-enable avoid-low-level-calls */
                require(oldRefundOk, RefundFailed());
            }
            return true;
        } else {
            require(_protocolId > 1, InvalidProtocolId());
            // Owner-governed allowlist (e.g. DVN adapters): exempt callers pay no fee. The
            // old-relay delegation path above needs no exemption — it is free for every caller.
            uint256 fee = feeExemptAddress[msg.sender] ? 0 : protocolFee[_protocolId];
            address token = feeToken;
            if (token == address(0)) {
                require(msg.value >= fee, TooLowFee());
            } else {
                // Token mode (mirrors on chains without a spendable native token): the fee is
                // paid exclusively in the configured ERC-20, so any attached value would strand.
                require(msg.value == 0, MsgValueNotAllowed());
            }
            // Never verify against an uninitialized (zero) Merkle root.
            bytes32 root = merkleRootsPrivate[_protocolId][_votingRoundId];
            require(root != bytes32(0), NotFinalized());
            require(_proof.verifyCalldata(root, _leaf), MerkleProofInvalid());
            // Native mode: forward only the fee to the collection address and refund any
            // overpayment. Token mode: pull the exact fee straight to the collection address
            // (no refund path). verify() performs no state writes itself. The configured token
            // and value recipients remain external trust/availability boundaries, and their
            // callbacks can enter other public Relay paths.
            if (token == address(0)) {
                if (fee > 0) {
                    /* solhint-disable avoid-low-level-calls */
                    //slither-disable-next-line arbitrary-send-eth
                    (bool feeOk, ) = feeCollectionAddress.call{value: fee}("");
                    /* solhint-enable avoid-low-level-calls */
                    require(feeOk, FeeTransferFailed());
                }
                uint256 refund = msg.value - fee;
                if (refund > 0) {
                    /* solhint-disable avoid-low-level-calls */
                    (bool refundOk, ) = msg.sender.call{value: refund}("");
                    /* solhint-enable avoid-low-level-calls */
                    require(refundOk, RefundFailed());
                }
            } else if (fee > 0) {
                IERC20(token).safeTransferFrom(msg.sender, feeCollectionAddress, fee);
            }
        }

        return true;
    }

    /**
     * @inheritdoc IRelay
     */
    function protocolFeeInWei(
        uint256 _protocolId
    )
        external view
        returns (uint256)
    {
        // This getter's unit is wei. Fail closed in token mode, where protocolFee is expressed
        // in token base units and cannot safely be used to size msg.value.
        require(feeToken == address(0), FeeTokenActive());
        return protocolFee[_protocolId];
    }

    /**
     * @inheritdoc IRelay
     */
    function getFeeConfigs()
        external view
        returns (FeeConfig[] memory _feeConfigs)
    {
        uint256 count = feeProtocolIdsPrivate.length();
        _feeConfigs = new FeeConfig[](count);
        for (uint256 i = 0; i < count; i++) {
            uint256 protocolId = feeProtocolIdsPrivate.pos(i);
            _feeConfigs[i] = FeeConfig(uint8(protocolId), protocolFee[protocolId]);
        }
    }

    /**
     * @inheritdoc IRelay
     */
    function isFinalized(uint256 _protocolId, uint256 _votingRoundId)
        external view
        returns (bool)
    {
        if (address(oldRelay) != address(0) && _votingRoundId < startingVotingRoundIdForInitialRewardEpochId) {
            return oldRelay.isFinalized(_protocolId, _votingRoundId);
        }
        // A nonzero stored root is the finalized sentinel. relay() rejects zero roots, so there is no
        // "relayed but not finalized" ambiguity.
        return merkleRootsPrivate[_protocolId][_votingRoundId] != bytes32(0);
    }

    /**
     * @inheritdoc IRelay
     */
    function merkleRoots(uint256 _protocolId, uint256 _votingRoundId)
        external view
        returns (bytes32 _merkleRoot)
    {
        if (address(oldRelay) != address(0) && _votingRoundId < startingVotingRoundIdForInitialRewardEpochId) {
            return oldRelay.merkleRoots(_protocolId, _votingRoundId);
        }
        require(signingPolicySetter != address(0), NoAccessToMerkleRoots());
        return merkleRootsPrivate[_protocolId][_votingRoundId];
    }

    /**
     * @inheritdoc RandomNumberV2Interface
     */
    function getRandomNumber()
        external view
        returns (
            uint256 _randomNumber,
            bool _isSecureRandom,
            uint256 _randomTimestamp
        )
    {
        // Return the relayed (Merkle-proven) random value for the latest random round.
        // Before the first random relay this returns (0, false, ts); consumers must gate on
        // _isSecureRandom (getRandomNumberHistorical instead reverts for an absent round).
        _randomNumber = toRandomNumberPrivate[stateData.randomVotingRoundId];
        _isSecureRandom = stateData.isSecureRandom;
        _randomTimestamp =
            stateData.firstVotingRoundStartTs +
            uint256(stateData.randomVotingRoundId + 1) *
            stateData.votingEpochDurationSeconds;
    }

    /**
     * @inheritdoc RandomNumberV2Interface
     */
    function getRandomNumberHistorical(uint256 _votingRoundId)
        external view
        returns (
            uint256 _randomNumber,
            bool _isSecureRandom,
            uint256 _randomTimestamp
        )
    {
        if (address(oldRelay) != address(0) && _votingRoundId < startingVotingRoundIdForInitialRewardEpochId) {
            return oldRelay.getRandomNumberHistorical(_votingRoundId);
        }
        // Gate presence on the finalized nonzero Merkle root, not on the random value, so a valid
        // relayed random value of 0 is not treated as absent.
        require(merkleRootsPrivate[stateData.randomNumberProtocolId][_votingRoundId] != bytes32(0), NoRandomNumber());
        _randomNumber = toRandomNumberPrivate[_votingRoundId];
        _isSecureRandom =
            (isSecureRandomMap[_votingRoundId / 256] >> (255 - _votingRoundId % 256)) & bytes32(uint256(1))
                == bytes32(uint256(1));
        _randomTimestamp =
            stateData.firstVotingRoundStartTs +
            uint256(_votingRoundId + 1) *
            stateData.votingEpochDurationSeconds;
    }

    /**
     * @inheritdoc IRelay
     */
    function getVotingRoundId(uint256 _timestamp) external view returns (uint256) {
        require(_timestamp >= stateData.firstVotingRoundStartTs, HistoryBeforeStart());
        return (_timestamp - stateData.firstVotingRoundStartTs) / stateData.votingEpochDurationSeconds;
    }

    /**
     * @inheritdoc IRelay
     */
    function toSigningPolicyHash(uint256 _rewardEpochId) external view returns (bytes32) {
        if (address(oldRelay) != address(0) && _rewardEpochId < initialRewardEpochId) {
            return oldRelay.toSigningPolicyHash(_rewardEpochId);
        }
        require(signingPolicySetter != address(0), NoAccessToSigningPolicyHashes());
        return toSigningPolicyHashPrivate[_rewardEpochId];
    }

    /**
     * @inheritdoc IRelay
     */
    function lastInitializedRewardEpochData()
        external view
        returns (
            uint32 _lastInitializedRewardEpoch,
            uint32 _startingVotingRoundIdForLastInitializedRewardEpoch
        )
    {
        _lastInitializedRewardEpoch = stateData.lastInitializedRewardEpoch;
        _startingVotingRoundIdForLastInitializedRewardEpoch =
            uint32(startingVotingRoundIds[_lastInitializedRewardEpoch]);
    }

    /**
     * FULL REPLACE of the fee configuration — shared by initialize() seeding (where the
     * clearing pass is a no-op) and setProtocolFees(): clears the previous table, sets the
     * token, applies the supplied table, and emits the single self-contained ProtocolFeesSet
     * event whose latest occurrence is therefore the whole fee state. Fees not restated read
     * 0 afterwards, so amounts can never be silently carried over in a possibly different
     * denomination. The enumeration set stays in lockstep with the mapping
     * (id in set ⟺ protocolFee[id] != 0); a zero fee is rejected because "free" is expressed
     * by omitting the protocol, and a duplicated protocol id is rejected so the emitted
     * table is unambiguous — both keep the event canonical.
     */
    function _setProtocolFees(
        address _feeToken,
        FeeConfig[] memory _feeConfigs
    )
        internal
    {
        while (feeProtocolIdsPrivate.length() > 0) {
            uint256 clearedId = feeProtocolIdsPrivate.pos(feeProtocolIdsPrivate.length() - 1);
            feeProtocolIdsPrivate.remove(clearedId);
            delete protocolFee[clearedId];
        }
        feeToken = _feeToken;
        for (uint256 i = 0; i < _feeConfigs.length; i++) {
            uint8 protocolId = _feeConfigs[i].protocolId;
            require(protocolId > 1, InvalidProtocolId());
            require(_feeConfigs[i].fee > 0, ProtocolFeeZero());
            protocolFee[protocolId] = _feeConfigs[i].fee;
            // The table was cleared above, so add() returns false iff this call listed the
            // same protocol id twice.
            require(feeProtocolIdsPrivate.add(protocolId), DuplicateProtocolId());
        }
        emit ProtocolFeesSet(_feeToken, _feeConfigs);
    }

    function _verifyCustomSignature(
        bytes calldata _relayMessage,
        bytes32 _messageHash
    ) internal returns (uint256 _rewardEpochId) {
        // Restrict the self-call to relay(). Without this the caller picks any selector on this
        // contract, and the only thing standing between that and an arbitrary internal entry
        // point is the 35-byte return discriminator below — a property of today's relay() return
        // shapes, not an access rule. Any future self-call target (or any method that happens to
        // return 35 bytes) would silently widen this path; the selector check does not.
        require(
            _relayMessage.length >= SELECTOR_BYTES && bytes4(_relayMessage[:SELECTOR_BYTES]) == IRelay.relay.selector,
            NotRelayCall()
        );
        /* solhint-disable avoid-low-level-calls */
        //slither-disable-next-line arbitrary-send-eth
        (bool success, bytes memory returnData) = address(this).call(_relayMessage);
        /* solhint-enable avoid-low-level-calls */
        require(success, VerificationFailed());
        // The 35-byte return length (32-byte hash plus 3-byte reward epoch id) uniquely identifies
        // relay()'s protocolId == 1 path; every other path returns no data or reverts. Changes to
        // relay() return formats must preserve this discriminator or replace it with a typed one.
        require(returnData.length == 35, WrongVerificationData());
        bytes32 returnHash;
        uint256 returnRewardEpochId;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            returnHash := mload(add(returnData, 0x20))
            returnRewardEpochId := shr(sub(256, mul(8, REWARD_EPOCH_ID_BYTES)), mload(add(returnData, 0x40)))
        }
        require(bytes32(returnHash) == _messageHash, InvalidConfigHash());
        return returnRewardEpochId;
    }
}

contracts/protocol/interface/IIRelay.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.9;

import { IRelay } from "../../userInterfaces/IRelay.sol";
import { IOwnableWithTimelock } from "../../userInterfaces/IOwnableWithTimelock.sol";

/**
 * Relay internal interface: the trusted signing-policy setter path plus the owner-governance
 * surface. Every owner setter is annotated `onlyOwnerWithTimelock` in the implementation —
 * with a nonzero timelock duration a call queues for permissionless execution after its ETA
 * (see IOwnableWithTimelock), with zero it applies immediately.
 */
interface IIRelay is IRelay, IOwnableWithTimelock {

    struct SigningPolicy {
        uint24 rewardEpochId;       // Reward epoch id.
        uint32 startVotingRoundId;  // First voting round id of validity.
                                    // Usually it is the first voting round of reward epoch rID.
                                    // It can be later,
                                    // if the confirmation of the signing policy on Flare blockchain gets delayed.
        uint16 threshold;           // Confirmation threshold (absolute value of noramalised weights).
        uint256 seed;               // Random seed.
        address[] voters;           // The list of eligible voters in the canonical order.
        uint16[] weights;           // The corresponding list of normalised signing weights of eligible voters.
                                    // Normalisation is done by compressing the weights from 32-byte values to 2 bytes,
                                    // while approximately keeping the weight relations.
    }

    /// A verify() fee-exemption update entry for `setFeeExemptions`.
    struct FeeExemption {
        address account;    // The account whose exemption is set.
        bool exempt;        // True grants the exemption, false revokes it.
    }

    /**
     * Sets the signing policy.
     * @param _signingPolicy Signing policy.
     * @return Returns signing policy hash.
     * @dev This method can only be called by the signing policy setter (on Flare: FlareSystemsManager),
     *      which is trusted. The signing policy setter MUST ensure the signing policy is well-formed; in
     *      particular it MUST guarantee that there are no zero-address voters and no duplicate voters, that
     *      the voters are given in the canonical order, and that the weights are correctly normalised.
     *      These properties are intentionally NOT re-validated on-chain; correctness relies on
     *      the trusted setter.
     */
    function setSigningPolicy(SigningPolicy memory _signingPolicy) external returns (bytes32);

    /**
     * Replaces the COMPLETE verify() fee configuration — the fee token and the entire fee
     * table — in one atomic call. The previous table is cleared first, so a protocol not
     * listed in `_feeConfigs` is free (fee 0) after the call; fees can never be silently
     * carried over as amounts in a different denomination. The self-contained
     * `ProtocolFeesSet(feeToken, feeConfigs)` event mirrors this: its latest occurrence fully
     * describes the current fee state. Relay mode only — a setter-mode (home) deployment
     * charges no fee and reverts with `FeeConfigNotAllowed`.
     * @param _feeToken The ERC-20 the fee is paid in from now on; zero means native-coin
     * fees. Must be a standard exact-transfer ERC-20 — fee-on-transfer or rebasing tokens are
     * unsupported (verify() assumes the pull delivers exactly the fee).
     * @param _feeConfigs The complete (protocolId, fee) table, denominated per `_feeToken`;
     * every protocol id must be greater than 1 and unique (`DuplicateProtocolId`), and every
     * fee nonzero (`ProtocolFeeZero` — a free protocol is expressed by omission).
     */
    function setProtocolFees(
        address _feeToken,
        FeeConfig[] calldata _feeConfigs
    )
        external;

    /**
     * Grants or revokes verify() fee exemptions (e.g. DVN adapters). Relay mode only — a
     * setter-mode (home) deployment charges no fee and reverts with `FeeExemptionsNotAllowed`.
     * @param _exemptions The (account, exempt) entries to apply; accounts must be nonzero.
     */
    function setFeeExemptions(
        FeeExemption[] calldata _exemptions
    )
        external;

    /**
     * Points collected verify() fees at a new recipient. Relay mode only — a setter-mode
     * (home) deployment collects no fees and reverts with `FeeConfigNotAllowed`.
     * @param _feeCollectionAddress The new fee recipient; must be nonzero (a zero recipient
     * would burn every collected fee).
     */
    function setFeeCollectionAddress(
        address _feeCollectionAddress
    )
        external;

    /**
     * Repoints the trusted signing-policy setter (e.g. after a FlareSystemsManager
     * redeployment). Setter mode only — the deployment mode is fixed at initialize, so a
     * relay-mode deployment can never gain a setter (`SigningPolicySetterNotAllowed`) and a
     * setter-mode one can never clear it (`SigningPolicySetterZero`).
     * @param _signingPolicySetter The new signing-policy setter; must be nonzero.
     */
    function setSigningPolicySetter(
        address _signingPolicySetter
    )
        external;

}

contracts/userInterfaces/IOwnableWithTimelock.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9;

/**
 * @title IOwnableWithTimelock
 * @notice Generic interface for ownable timelocked call execution.
 * @dev Three properties callers must plan around, none visible in the ABI.
 *
 *      A guarded call **either applies or queues**, and both return success.
 *      A void guarded call returns empty ABI data in each case, so the return
 *      value cannot distinguish them either. Read back
 *      `getExecuteTimelockedCallTimestamp` or the target's own getter to tell
 *      which happened.
 *
 *      **A queued call whose migration data invokes another guarded function is
 *      not executable**: execution self-calls the proxy and consumes the
 *      `executing` flag, so the nested call tries to queue and reverts on the
 *      owner check. A zero duration takes the immediate branch instead, so the
 *      same data rehearses green on testnet and fails on a timelocked mainnet.
 *      Guard migration entry points on owner-or-self, not on the timelock.
 *
 *      **Queued calls survive `transferOwnership`.** They are keyed by
 *      calldata hash alone, with no proposer, so a call queued by the
 *      previous owner remains executable after the transfer unless
 *      cancelled first: anyone can execute that exact operation, carrying
 *      its original owner authorization. `transferOwnership` is itself a
 *      guarded call, so with a nonzero duration the transfer is visible for
 *      the delay before it applies, and that window is when the outstanding
 *      queue must be cleared. With a zero duration there is no window: the
 *      transfer applies at once and the queue carries over unexamined.
 *      The queue is not enumerable on-chain, so clearing it means replaying
 *      `CallTimelocked` and cancelling what is still pending.
 */
interface IOwnableWithTimelock {

    /**
     * @notice Emitted when a call is timelocked and can be executed later.
     *         An upsert keyed by `encodedCallHash`: re-queuing identical
     *         calldata resets the pending ETA and emits this event again, so
     *         the latest `allowedAfterTimestamp` per hash is authoritative
     *         and two identical calls are never pending concurrently.
     * @param encodedCall ABI encoded call data.
     * @param encodedCallHash Hash of encoded call.
     * @param allowedAfterTimestamp Earliest timestamp when call is executable.
     */
    event CallTimelocked(
        bytes encodedCall,
        bytes32 encodedCallHash,
        uint256 allowedAfterTimestamp
    );

    /**
     * @notice Emitted when a timelocked call is executed.
     * @param encodedCallHash Hash of encoded call.
     */
    event TimelockedCallExecuted(
        bytes32 encodedCallHash
    );

    /**
     * @notice Emitted when a timelocked call is canceled.
     * @param encodedCallHash Hash of encoded call.
     */
    event TimelockedCallCanceled(
        bytes32 encodedCallHash
    );

    /**
     * @notice Emitted when timelock duration is updated.
     * @param timelockDurationSeconds New timelock duration in seconds.
     */
    event TimelockDurationSet(
        uint256 timelockDurationSeconds
    );

    /**
     * @notice Reverts when the encoded call has no queued timelock entry.
     */
    error TimelockInvalidSelector();

    /**
     * @notice Reverts when timelocked call execution is attempted too early.
     */
    error TimelockNotAllowedYet();

    /**
     * @notice Reverts when requested timelock duration exceeds maximum.
     */
    error TimelockDurationTooLong();

    /**
     * @notice Reverts when a call is queued with a nonzero value. Execution
     *         replays only the recorded calldata (never value), so queued
     *         value would be trapped in the contract.
     */
    error TimelockValueNotAllowed();

    /**
     * @notice Reverts on any `renounceOwnership` call. The role cannot be
     *         given up, only moved with `transferOwnership` — itself a guarded
     *         call, so it queues and waits whenever a nonzero duration is set.
     */
    error RenounceDisabled();

    /**
     * @notice Executes a queued call once its recorded ETA has passed.
     * @param _encodedCall ABI encoded call data.
     * @dev Permissionless after the ETA recorded when the call was queued (not
     *      the current timelock duration).
     */
    function executeTimelockedCall(
        bytes calldata _encodedCall
    )
        external;

    /**
     * @notice Cancels a queued timelocked call.
     * @param _encodedCall ABI encoded call data.
     */
    function cancelTimelockedCall(
        bytes calldata _encodedCall
    )
        external;

    /**
     * @notice Sets the timelock duration for owner-controlled calls, through the
     *         current owner-timelock path (this call is itself protected).
     * @param _timelockDurationSeconds Timelock duration in seconds.
     */
    function setTimelockDuration(
        uint256 _timelockDurationSeconds
    )
        external;

    /**
     * @notice Returns timestamp when a timelocked call may be executed.
     * @param _encodedCall ABI encoded call data.
     * @return _allowedAfterTimestamp Earliest execution timestamp.
     */
    function getExecuteTimelockedCallTimestamp(
        bytes calldata _encodedCall
    )
        external view
        returns (uint256 _allowedAfterTimestamp);

    /**
     * @notice Returns the configured timelock duration in seconds.
     * @return Timelock duration in seconds.
     */
    function getTimelockDurationSeconds() external view returns (uint256);
}

contracts/userInterfaces/IRelay.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9;

import { RandomNumberV2Interface } from "./LTS/RandomNumberV2Interface.sol";

/**
 * Relay interface.
 */
interface IRelay is RandomNumberV2Interface {

    struct FeeConfig {
        uint8 protocolId;   // Protocol id for which the fee is set
        uint256 fee;        // Fee in native wei, or in base units of the configured fee
                            // token when one is set (see feeToken)
    }

    struct RelayInitialConfig {
        uint32 initialRewardEpochId;                           // The initial reward epoch id.
        uint32 startingVotingRoundIdForInitialRewardEpochId;   // The starting voting round id for the initial
                                                               // reward epoch.
        bytes32 initialSigningPolicyHash;                      // The initial signing policy hash.
        uint8 randomNumberProtocolId;                          // The protocol id of the random number protocol.
        uint32 firstVotingRoundStartTs;                        // The timestamp of the first voting round start.
        uint8 votingEpochDurationSeconds;                      // The duration of a voting epoch in seconds.
        uint32 firstRewardEpochStartVotingRoundId;             // The start voting round id of the first reward epoch.
        uint16 rewardEpochDurationInVotingEpochs;              // The duration of a reward epoch in voting epochs.
        uint16 thresholdIncreaseBIPS;                          // The threshold increase in BIPS for signing with
                                                               // old signing policy.
        uint32 messageFinalizationWindowInRewardEpochs;        // The window of reward epochs for finalizing
                                                               // the protocol messages.
        address payable feeCollectionAddress;                  // Fee collection address
        FeeConfig[] feeConfigs;                                // Fee configurations
        address feeToken;                                      // ERC-20 the verify() fee is paid in;
                                                               // zero = native coin. For chains without
                                                               // a (spendable) native token. Relay mode
                                                               // only; must be zero on a home deploy.
        address[] feeExemptAddresses;                          // Accounts exempt from the verify() fee at
                                                               // deployment (e.g. DVN adapters). Relay mode
                                                               // only; must be empty on a home deploy.
        uint256 sourceChainId;                                 // Source network id bound into every
                                                               // policy hash and signed digest. Explicit and
                                                               // nonzero on EVERY deployment; a home deploy
                                                               // (signingPolicySetter set) forces it to
                                                               // equal block.chainid.
        uint256 timelockDurationSeconds;                       // Initial owner-timelock duration applied to
                                                               // every guarded owner call — fee settings,
                                                               // upgrades, this duration and ownership
                                                               // transfer (see IOwnableWithTimelock);
                                                               // at most 7 days. Zero disables the
                                                               // timelock: guarded calls then apply
                                                               // immediately instead of queueing.
    }

    // Event is emitted when a new signing policy is initialized by the signing policy setter.
    event SigningPolicyInitialized(
        uint24 indexed rewardEpochId,   // Reward epoch id
        uint32 startVotingRoundId,      // First voting round id of validity.
                                        // Usually it is the first voting round of reward epoch rewardEpochId.
                                        // It can be later,
                                        // if the confirmation of the signing policy on Flare blockchain gets delayed.
        uint16 threshold,               // Confirmation threshold (absolute value of noramalised weights).
        uint256 seed,                   // Random seed.
        address[] voters,               // The list of eligible voters in the canonical order.
        uint16[] weights,               // The corresponding list of normalised signing weights of eligible voters.
                                        // Normalisation is done by compressing the weights from 32-byte values to
                                        // 2 bytes, while approximately keeping the weight relations.
        bytes signingPolicyBytes,       // The full signing policy byte encoded.
        uint64 timestamp                // Timestamp when this happened
    );

    // Event is emitted when a signing policy is relayed.
    // It contains minimalistic data in order to save gas. Data about the signing policy are
    // extractable from the calldata, assuming prefered usage of direct top-level call to relay().
    event SigningPolicyRelayed(
        uint256 indexed rewardEpochId        // Reward epoch id
    );

    // Event is emitted when a protocol message is relayed.
    // isSecureRandom is always a canonical bool: the relayed message must carry 0 or 1 for the
    // random-number protocol and 0 for every other protocol id, so this field never carries a
    // value a strict ABI decoder would reject. Outside the random-number protocol it is false.
    event ProtocolMessageRelayed(
        uint8 indexed protocolId,           // Protocol id
        uint32 indexed votingRoundId,       // Voting round id
        bool isSecureRandom,                // Secure random flag
        bytes32 merkleRoot                  // Merkle root of the protocol message
    );

    // Event is emitted when a random number is relayed (random-number protocol).
    event RandomNumberRelayed(
        uint32 indexed votingRoundId,       // Voting round id of the random
        uint256 randomNumber,               // The relayed (Merkle-proven) random number value
        bool isSecureRandom                 // Whether the random is secure
    );

    /// The verify() fee configuration was set — once at every relay-mode deployment (seeded
    /// config) and on every setProtocolFees call. The event is SELF-CONTAINED: it carries the
    /// fee token (zero = native coin) and the complete fee table; every protocol not listed
    /// has fee 0. The latest event therefore fully describes the current fee configuration.
    event ProtocolFeesSet(
        address indexed feeToken,
        FeeConfig[] feeConfigs
    );

    /// A verify() fee exemption was set — at deployment (seeded config) or by the owner.
    event FeeExemptionSet(
        address indexed account,
        bool exempt
    );

    /// The verify() fee-collection recipient was set — at deployment (seeded config) or by
    /// the owner.
    event FeeCollectionAddressSet(
        address indexed feeCollectionAddress
    );

    /// The trusted signing-policy setter was set — at deployment or by the owner (e.g. after
    /// a FlareSystemsManager redeployment).
    event SigningPolicySetterSet(
        address indexed signingPolicySetter
    );


    // ---- Typed failure ABI. relay() raises these from its assembly via 4-byte selectors.
    error AlreadyRelayed();
    error BadS();
    error BadV();
    error DelayedSignPolicy();
    /// A protocol id appears more than once in a supplied fee table — the self-contained
    /// ProtocolFeesSet event must be unambiguous.
    error DuplicateProtocolId();
    error EcrecoverError();
    error EcrecoverReturnedBadData();
    error FeeCollectionAddressZero();
    error FeeConfigNotAllowed();
    /// An initial fee-exempt address is the zero address.
    error FeeExemptAddressZero();
    /// Initial fee-exempt addresses supplied on a setter-mode (home) deploy, which charges no fee.
    error FeeExemptionsNotAllowed();
    /// protocolFeeInWei() was called while a fee token is active. Token-denominated fees
    /// are expressed in token base units; use protocolFee() and feeToken() in this mode.
    error FeeTokenActive();
    error FeeTransferFailed();
    error HistoryBeforeStart();
    error IncorrectMerkleProof();
    error IndexOutOfOrder();
    error IndexOutOfRange();
    error InitialSigningPolicyHashZero();
    error InvalidConfigHash();
    error InvalidInitialStartingVotingRoundId();
    error InvalidProtocolId();
    error InvalidRandomNumberProof();
    error InvalidRandomNumberProtocolId();
    error InvalidSignPolicyLength();
    error InvalidSignPolicyMetadata();
    error InvalidVotingRoundId();
    error MerkleProofInvalid();
    error MessageTooOld();
    /// Native value was sent to verify() while a fee token is active — the fee is then paid
    /// exclusively in that token (via allowance), so any attached value would strand.
    error MsgValueNotAllowed();
    error MustUseNewSignPolicy();
    error NoAccessToMerkleRoots();
    error NoAccessToSigningPolicyHashes();
    error NoNewSignPolicySize();
    error NoRandomNumber();
    error NoSignatureCount();
    error NotEnoughSignatures();
    error NotEnoughWeight();
    error NotFinalized();
    error NotNextRewardEpoch();
    /// verifyCustomSignature / verifyCustomSignatureWithThreshold were given calldata that does
    /// not select relay(). The self-call is restricted to relay() so it can never become a
    /// general-purpose internal entry point.
    error NotRelayCall();
    error NotWithLastInitialized();
    error OldRelayIncompatible();
    /// Old-relay migration is home-only. A relay-mode mirror uses its local fee and exemption
    /// configuration and seeds a fresh source snapshot instead of delegating pre-boundary reads.
    error OldRelayNotAllowedInRelayMode();
    error OldRelayVerificationFailed();
    error OldRelayWrongFirstRewardEpochStart();
    error OldRelayWrongRewardEpochDuration();
    error OldRelayWrongStartTs();
    error OldRelayWrongVotingEpochDuration();
    error OnlySigningPolicySetterRole();
    /// A configured protocol fee is zero. With full-replace fee semantics a free protocol is
    /// expressed by omitting it, so every listed (protocolId, fee) entry must be nonzero.
    error ProtocolFeeZero();
    error RefundFailed();
    error RewardEpochDurationZero();
    error SignPolicyRelayDisabled();
    error SigningPolicyEmpty();
    error SigningPolicyHashMismatch();
    /// Updating the signing-policy setter on a relay-mode deployment (the mode is fixed at
    /// deploy, so a relay-mode deployment can never gain a setter).
    error SigningPolicySetterNotAllowed();
    /// The signing-policy setter update is the zero address (the mode cannot be cleared).
    error SigningPolicySetterZero();
    error SourceChainIdMismatchOnHomeDeploy();
    /// The configured source network id is zero.
    error SourceChainIdZero();
    error ThresholdIncreaseTooSmall();
    error ThresholdTooHigh();
    error ThresholdTooLow();
    error TooLowFee();
    error TooManyVoters();
    error TooShortMessage();
    error TotalWeightTooBig();
    error UnreachableCode();
    error VerificationFailed();
    error VotersWeightsSizeMismatch();
    error VotingEpochDurationZero();
    error WrongMessageFormat();
    /// The protocol message's isSecureRandom byte is not a canonical bool for its protocol id:
    /// it must be 0 or 1 for the random-number protocol and 0 for every other protocol id.
    error WrongMessageFormat2();
    error WrongSignPolicyRewardEpoch();
    error WrongSignature();
    error WrongSizeForNewSignPolicy();
    error WrongVerificationData();
    error ZeroMerkleRoot();
    error ZeroSigner();

    /**
     * Checks the relay message for sufficient weight of signatures for the _messageHash
     * signed for protocol message Merkle root of the form (1, 0, 0, _messageHash).
     * If the check is successful, reward epoch id of the signing policy is returned.
     * Otherwise the function reverts.
     * **SECURITY:** This is a generic signature-quorum oracle. Relay verifies EIP-191
     *           signatures over `keccak256(sourceChainId ‖ (1, 0, 0, _messageHash))` using
     *           the signing policy encoded in `_relayMessage`. `sourceChainId` identifies the
     *           configured signing source; it does not bind the destination chain, this Relay
     *           instance, the consuming contract, an operation, or a nonce. The same signatures
     *           can therefore be replayed against another Relay with the same source-domain and
     *           accepted signing policy, including a Relay on another destination chain. Callers
     *           must domain-separate `_messageHash` for their application, including every replay
     *           boundary they require (for example destination chain id, consuming contract,
     *           operation and nonce).
     *           Calldata whose leading four bytes are not the `relay()` selector is rejected
     *           with `NotRelayCall`, so this path cannot reach any other function on the contract.
     * @param _relayMessage Full calldata for the `relay()` self-call, including its 4-byte selector.
     * @param _messageHash The hash of the message.
     * @return _rewardEpochId The reward epoch id of the signing policy.
     */
    function verifyCustomSignature(
        bytes calldata _relayMessage,
        bytes32 _messageHash
    )
        external
        returns (uint256 _rewardEpochId);

    /**
     * Same check as `verifyCustomSignature`, but against a caller-chosen signature-weight
     * threshold instead of the signing policy's own. The override applies ONLY to this
     * verification (the protocolId == 1 path, which stores nothing); protocol
     * finalization and signing-policy relay always use the policy threshold.
     * The same domain-separation caveat as `verifyCustomSignature` applies.
     * NOTE: an override below the signing policy threshold weakens only this caller's acceptance
     * rule — the result then means "more than the requested fraction of the weight signed",
     * not that the protocol's quorum was reached.
     * @param _relayMessage Full calldata for the `relay()` self-call, including its 4-byte selector.
     * @param _messageHash The hash of the message.
     * @param _thresholdBIPS The threshold in BIPS of the signing policy's total normalized
     * weight (e.g. 5000 = 50%); 0 uses the signing policy's own threshold (the
     * `Fdc2RequestHeader.thresholdBIPS` convention). The effective threshold is
     * `floor(totalWeight * _thresholdBIPS / 10000)` and is compared with strict
     * inequality. This is equivalent to requiring
     * `signedWeight * 10000 > totalWeight * _thresholdBIPS`, so 5000 requires strictly
     * more than 50% of the weight. Values of 10000 and above are unsatisfiable and
     * revert with `ThresholdTooHigh`.
     * @return _rewardEpochId The reward epoch id of the signing policy.
     */
    function verifyCustomSignatureWithThreshold(
        bytes calldata _relayMessage,
        bytes32 _messageHash,
        uint16 _thresholdBIPS
    )
        external
        returns (uint256 _rewardEpochId);

    /**
     * Finalization function for new signing policies and protocol messages.
     * It can be used as finalization contract on Flare chain or as relay contract on other EVM chain.
     * Can be called in two modes. It expects calldata that is parsed in a custom manner.
     * Hence the transaction calls should assemble relevant calldata in the 'data' field.
     * Depending on the data provided, the contract operates in two modes:
     * (1) Relaying signing policy. The structure of the calldata is:
     *        function signature (4 bytes) + active signing policy
     *             + 0 (1 byte) + new signing policy
     *             + signature count (2 bytes) + indexed ECDSA signatures (67 bytes each).
     *     Each policy has variable length `43 + 22 * numberOfVoters`, so the
     *     complete calldata length depends on both voter counts.
     * (2) Relaying signed message. The structure of the calldata is:
     *        function signature (4 bytes) + signing policy
     *           + signed message (38 bytes) + signature count (2 bytes)
     *           + indexed ECDSA signatures (67 bytes each).
     *     For the configured random-number protocol, the signatures are followed by a
     *     random number (32 bytes) and zero or more Merkle-proof nodes (32 bytes each).
     *     This case splits into two subcases:
     *     - protocolId = 1: Message id must be of the form (protocolId, 0, 0, merkleRoot).
     *       The validity of the signatures of sufficient weight is checked and if
     *       successful, raw return data contains the merkleRoot from the message (32 bytes)
     *       followed by the reward epoch id of the signing policy (3 bytes). No state is written.
     *     - protocolId > 1: The validity of the signatures of sufficient weight is checked and if
     *       it is valid, the merkleRoot is published for protocolId and votingRoundId.
     *     Signature indices must be strictly increasing, and accepted weight must strictly
     *     exceed the applicable threshold.
     * Reverts if relaying is not successful.
     */
    function relay() external returns (bytes memory);

    /**
     * Verifies the leaf (or intermediate node) with the Merkle proof against the Merkle root
     * for given protocol id and voting round id.
     * A fee may need to be paid. It is protocol specific.
     * Payment medium depends on the configuration (see feeToken):
     * - No fee token set (all home deployments, default on mirrors): the fee is paid in native
     *   coin via msg.value. Overpayment above the protocol fee is refunded to the caller via a
     *   value-bearing call, so a contract caller MUST be able to receive ETH (or send exactly
     *   the fee); otherwise verify() reverts.
     * - Fee token set (mirror deployments on chains without a spendable native token): the exact
     *   fee is pulled via the token's transferFrom to the fee-collection address, so the caller
     *   MUST approve at least the fee beforehand. msg.value MUST be zero (MsgValueNotAllowed);
     *   there is no refund path.
     * A successful verification delegated to a configured old relay (home deployments only,
     * rounds below the migration boundary) is free: no value is forwarded and the caller's
     * entire msg.value is refunded. The round must be finalized on that source too, otherwise
     * the call reverts NotFinalized — an unfinalized round has a zero root there, which an
     * empty proof over a zero leaf would otherwise satisfy. Migration configuration must use an
     * intended supported setter-mode Relay chain, whose verification fees remain zero.
     * **NOTE:** A leaf equal to the (finalized, non-zero) root verifies with an empty proof —
     *           a standard Merkle property. Off-chain leaf encoding MUST be domain-separated from internal
     *           and root node hashes so an internal node cannot be presented as a differently-typed leaf.
     * @param _protocolId The protocol id.
     * @param _votingRoundId The voting round id.
     * @param _leaf The leaf (or intermediate node) to verify.
     * @param _proof The Merkle proof.
     * @return True if the verification is successful.
     */
    function verify(uint256 _protocolId, uint256 _votingRoundId, bytes32 _leaf, bytes32[] calldata _proof)
        external payable
        returns (bool);

    /**
     * Returns the address of the signing policy setter.
     * If the address is zero, the contract is used as a pure relay,
     * otherwise the contract operates in setter (home) mode.
     */
    function signingPolicySetter() external view returns (address);

    /**
     * Returns the signing policy hash for given reward epoch id.
     * The function is reverted if signingPolicySetter is NOT set, hence on all
     * deployments where the contract is used as a pure relay.
     * The returned hash is source-bound: keccak256(sourceChainId ‖ encoded policy bytes) —
     * one keccak over the 32-byte source chain id followed by the raw 43 + 22 * n byte encoding, no
     * padding. Off-chain code comparing against a locally computed policy hash must use the same scheme.
     * Epochs served by an `oldRelay` fallback return that contract's configured hash format.
     * @param _rewardEpochId The reward epoch id.
     * @return _signingPolicyHash The signing policy hash.
     */
    function toSigningPolicyHash(uint256 _rewardEpochId) external view returns (bytes32 _signingPolicyHash);

    /**
     * Returns true if there is finalization for a given protocol id and voting round id.
     * @param _protocolId The protocol id.
     * @param _votingRoundId The voting round id.
     */
    function isFinalized(uint256 _protocolId, uint256 _votingRoundId) external view returns (bool);

    /**
     * Returns the Merkle root for given protocol id and voting round id.
     * The function is reverted if signingPolicySetter is NOT set, hence on all
     * deployments where the contract is used as a pure relay.
     * @param _protocolId The protocol id.
     * @param _votingRoundId The voting round id.
     * @return _merkleRoot The Merkle root.
     */
    function merkleRoots(uint256 _protocolId, uint256 _votingRoundId) external view returns (bytes32 _merkleRoot);

    /**
     * Returns the start voting round id for given reward epoch id.
     * @param _rewardEpochId The reward epoch id.
     * @return _startingVotingRoundId The start voting round id.
     */
    function startingVotingRoundIds(uint256 _rewardEpochId) external view returns (uint256 _startingVotingRoundId);

    /**
     * Returns the voting round id for given timestamp.
     * @param _timestamp The timestamp.
     * @return _votingRoundId The voting round id.
     */
    function getVotingRoundId(uint256 _timestamp) external view returns (uint256 _votingRoundId);

    /**
     * Returns last initialized reward epoch data.
     * @return _lastInitializedRewardEpoch Last initialized reward epoch.
     * @return _startingVotingRoundIdForLastInitializedRewardEpoch Starting voting round id for it.
     */
    function lastInitializedRewardEpochData()
        external view
        returns (
            uint32 _lastInitializedRewardEpoch,
            uint32 _startingVotingRoundIdForLastInitializedRewardEpoch
        );

    /**
     * Returns fee collection address.
     */
    function feeCollectionAddress() external view returns (address payable);

    /**
     * Returns the fee for one verification of a given protocol id, in native wei — or in
     * base units of the configured fee token when one is set (see feeToken).
     * @param _protocolId The protocol id.
     */
    function protocolFee(uint256 _protocolId) external view returns (uint256);

    /**
     * Returns the ERC-20 token the verify() fee is paid in, or the zero address when fees
     * are paid in the native coin (all home deployments, default on mirrors). A configured
     * token must be a standard exact-transfer ERC-20; fee-on-transfer or rebasing tokens
     * are unsupported.
     */
    function feeToken() external view returns (address);

    /**
     * Returns the complete fee table: every protocol id with a nonzero verify() fee and that
     * fee, denominated per feeToken() (native wei when it is zero). Order is unspecified.
     */
    function getFeeConfigs() external view returns (FeeConfig[] memory _feeConfigs);

    /**
     * Returns the native-coin fee in wei for one verification of a given protocol id.
     * @dev Reverts with FeeTokenActive when a fee token is set, so token-denominated amounts
     * cannot be exposed through a getter whose unit is wei.
     * @param _protocolId The protocol id.
     */
    function protocolFeeInWei(uint256 _protocolId) external view returns (uint256);

    /**
     * Returns whether `account` may call `verify()` without paying the protocol fee.
     */
    function feeExemptAddress(address account) external view returns (bool);

    /**
     * Returns the configured source-network id: the network whose
     * voter quorum this Relay verifies. Equals block.chainid on home deployments.
     */
    function sourceChainId() external view returns (uint256);

    /**
     * Returns the state data.
     * @return randomNumberProtocolId The protocol id of the random number protocol.
     * @return firstVotingRoundStartTs The timestamp of the first voting round start.
     * @return votingEpochDurationSeconds The duration of a voting epoch in seconds.
     * @return firstRewardEpochStartVotingRoundId The start voting round id of the first reward epoch.
     * @return rewardEpochDurationInVotingEpochs The duration of a reward epoch in voting epochs.
     * @return thresholdIncreaseBIPS The threshold increase in BIPS for signing with old signing policy.
     * @return randomVotingRoundId The random voting round id.
     * @return isSecureRandom The secure random flag.
     * @return lastInitializedRewardEpoch The last initialized reward epoch.
     * @return noSigningPolicyRelay The flag indicating no signing policy relay.
     * @return messageFinalizationWindowInRewardEpochs The window of reward epochs for finalizing the
     *  protocol messages.
     */
    function stateData()
        external
        view
        returns (
            uint8 randomNumberProtocolId,
            uint32 firstVotingRoundStartTs,
            uint8 votingEpochDurationSeconds,
            uint32 firstRewardEpochStartVotingRoundId,
            uint16 rewardEpochDurationInVotingEpochs,
            uint16 thresholdIncreaseBIPS,
            uint32 randomVotingRoundId,
            bool isSecureRandom,
            uint32 lastInitializedRewardEpoch,
            bool noSigningPolicyRelay,
            uint32 messageFinalizationWindowInRewardEpochs
        );

}

contracts/userInterfaces/LTS/RandomNumberV2Interface.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.9;

/**
 * Random number V2 long term support interface.
 */
interface RandomNumberV2Interface {
    /**
     * Returns the current random number, its timestamp and the flag indicating if it is secure.
     * @return _randomNumber The current random number.
     * @return _isSecureRandom The flag indicating if the random number is secure.
     * @return _randomTimestamp The timestamp of the random number.
     */
    function getRandomNumber()
        external view
        returns (
            uint256 _randomNumber,
            bool _isSecureRandom,
            uint256 _randomTimestamp
        );

    /**
     * Returns the historical random number for a given _votingRoundId,
     * its timestamp and the flag indicating if it is secure.
     * If no finalization in the _votingRoundId, the function reverts.
     * @param _votingRoundId The voting round id.
     * @return _randomNumber The current random number.
     * @return _isSecureRandom The flag indicating if the random number is secure.
     * @return _randomTimestamp The timestamp of the random number.
     */
    function getRandomNumberHistorical(uint256 _votingRoundId)
        external view
        returns (
            uint256 _randomNumber,
            bool _isSecureRandom,
            uint256 _randomTimestamp
        );
}

contracts/utils/implementation/OwnableWithTimelock.sol

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

import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {IOwnableWithTimelock} from "../../userInterfaces/IOwnableWithTimelock.sol";

/**
 * @title OwnableWithTimelock
 * @notice Ownable extension that timelocks selected owner calls using a dedicated storage slot.
 * @dev Upgradeable: built on `OwnableUpgradeable`; the concrete contract calls
 *      `__Ownable_init` from its `initialize`. Ownership transfer is guarded like every other
 *      owner call, so while a nonzero duration is configured no owner action can take effect
 *      without passing through the public queue-and-wait window; a zero duration disarms the
 *      timelock for every guarded call, transfers included. The one owner power that is
 *      immediate even with the timelock armed is `cancelTimelockedCall`,
 *      which can only withdraw a pending action, never enact one — the outgoing owner keeps it
 *      until execution and may cancel a queued transfer with it. There is no propose/accept
 *      handshake and no pending-owner state: when the call applies the role moves in one
 *      write, and a reverted execution moves nothing.
 *      Callers must validate the nonzero target because an incorrect target cannot be
 *      recovered by this contract. Its own state lives at a fixed ERC-7201 slot, independent
 *      of the inherited namespaced storage.
 *
 *      Queued calls are keyed by calldata hash alone: they carry no proposer and are not
 *      cleared by `transferOwnership`, so a call queued by a previous owner stays executable
 *      under the new owner — anyone can execute that exact operation, carrying its original
 *      owner authorization. Cancel every outstanding queued call before transferring
 *      ownership; the queue is not enumerable on-chain, so finding them means replaying
 *      `CallTimelocked` off-chain.
 */
abstract contract OwnableWithTimelock is OwnableUpgradeable, IOwnableWithTimelock {

    /// @custom:storage-location erc7201:utils.OwnableWithTimelock.State
    struct State {
        bool executing;
        uint256 timelockDurationSeconds;
        mapping(bytes32 encodedCallHash => uint256 allowedAfterTimestamp) timelockedCalls;
    }

    uint256 internal constant MAX_TIMELOCK_DURATION_SECONDS = 7 days;

    // erc7201 builtin not recognized by slither's parser; the constant is initialized at declaration
    //slither-disable-next-line uninitialized-state
    bytes32 internal constant STATE_POSITION = bytes32(erc7201("utils.OwnableWithTimelock.State"));

    modifier onlyOwnerWithTimelock() {
        if (_timeToExecuteTimelockedCall()) {
            _beforeExecuteTimelockedCall();
            _;
        } else {
            _recordTimelockedCall(msg.data);
        }
    }

    /// @inheritdoc IOwnableWithTimelock
    function executeTimelockedCall(
        bytes calldata _encodedCall
    )
        external
        virtual
    {
        State storage state = getState();
        bytes32 encodedCallHash = keccak256(_encodedCall);
        uint256 allowedAfterTimestamp = state.timelockedCalls[encodedCallHash];
        require(allowedAfterTimestamp != 0, TimelockInvalidSelector());
        require(block.timestamp >= allowedAfterTimestamp, TimelockNotAllowedYet());
        delete state.timelockedCalls[encodedCallHash];
        state.executing = true;
        //solhint-disable-next-line avoid-low-level-calls
        (bool success,) = address(this).call(_encodedCall);
        state.executing = false;
        emit TimelockedCallExecuted(encodedCallHash);
        _passReturnOrRevert(success);
    }

    /// @inheritdoc IOwnableWithTimelock
    function cancelTimelockedCall(
        bytes calldata _encodedCall
    )
        external
        virtual
        onlyOwner
    {
        State storage state = getState();
        bytes32 encodedCallHash = keccak256(_encodedCall);
        require(state.timelockedCalls[encodedCallHash] != 0, TimelockInvalidSelector());
        emit TimelockedCallCanceled(encodedCallHash);
        delete state.timelockedCalls[encodedCallHash];
    }

    /// @inheritdoc IOwnableWithTimelock
    function setTimelockDuration(
        uint256 _timelockDurationSeconds
    )
        external
        virtual
        onlyOwnerWithTimelock
    {
        State storage state = getState();
        require(_timelockDurationSeconds <= MAX_TIMELOCK_DURATION_SECONDS, TimelockDurationTooLong());
        state.timelockDurationSeconds = _timelockDurationSeconds;
        emit TimelockDurationSet(_timelockDurationSeconds);
    }

    /**
     * @notice Transfers ownership, under the timelock like every other guarded call.
     * @dev Not `super.transferOwnership`: on the execute path the call arrives as a self-call
     *      from `executeTimelockedCall`, `_beforeExecuteTimelockedCall` deliberately skips the
     *      owner check, and `Ownable`'s own `onlyOwner` would then reject `msg.sender ==
     *      address(this)`. The internal `_transferOwnership` has no such check, so the
     *      zero-address guard is reapplied here.
     *
     *      With a zero duration this still applies immediately, matching every other guarded
     *      setter. While a transfer is queued the caller remains the owner and may cancel it.
     *      Queued calls are not bound to an owner generation and survive the transfer; cancel
     *      every outstanding one first.
     * @param _newOwner The new owner. Must be nonzero; an incorrect target cannot be recovered.
     */
    function transferOwnership(
        address _newOwner
    )
        public override
        onlyOwnerWithTimelock
    {
        require(_newOwner != address(0), OwnableInvalidOwner(address(0)));
        _transferOwnership(_newOwner);
    }

    /// @inheritdoc IOwnableWithTimelock
    function getTimelockDurationSeconds()
        public
        view
        virtual
        returns (uint256)
    {
        State storage state = getState();
        return state.timelockDurationSeconds;
    }

    /// @inheritdoc IOwnableWithTimelock
    function getExecuteTimelockedCallTimestamp(
        bytes calldata _encodedCall
    )
        public
        view
        virtual
        returns (uint256 _allowedAfterTimestamp)
    {
        State storage state = getState();
        bytes32 encodedCallHash = keccak256(_encodedCall);
        _allowedAfterTimestamp = state.timelockedCalls[encodedCallHash];
        require(_allowedAfterTimestamp != 0, TimelockInvalidSelector());
    }

    /**
     * @notice Disabled to prevent permanently frozen administration; rotate
     *         governance through `transferOwnership`.
     */
    function renounceOwnership()
        public
        pure
        override
    {
        revert RenounceDisabled();
    }

    function _beforeExecuteTimelockedCall()
        internal
        virtual
    {
        State storage state = getState();
        if (state.executing) {
            assert(msg.sender == address(this));
            state.executing = false;
        } else {
            _checkOwner();
        }
    }

    /// @dev An upsert keyed solely by `keccak256(_encodedCall)`: queuing
    ///      calldata that is already pending replaces its ETA — including
    ///      pushing a matured call's ETA forward — and emits a regular
    ///      `CallTimelocked`, indistinguishable from a fresh queueing. The
    ///      latest emitted (and stored) ETA is the authoritative one, and two
    ///      identical calls can never be pending concurrently. Only the owner
    ///      queues, so an overwrite is always governance's own act — a double
    ///      submission or a deliberate re-schedule — never a third party's.
    function _recordTimelockedCall(
        bytes calldata _encodedCall
    )
        internal
        virtual
    {
        State storage state = getState();
        _checkOwner();
        // Execution replays only calldata via a zero-value self-call, so value
        // sent when queuing would be trapped; duration 0 still forwards it.
        require(msg.value == 0, TimelockValueNotAllowed());
        bytes32 encodedCallHash = keccak256(_encodedCall);
        uint256 allowedAt = block.timestamp + state.timelockDurationSeconds;
        state.timelockedCalls[encodedCallHash] = allowedAt;
        emit CallTimelocked(_encodedCall, encodedCallHash, allowedAt);
    }

    function _timeToExecuteTimelockedCall()
        internal
        view
        virtual
        returns (bool)
    {
        State storage state = getState();
        return state.executing || state.timelockDurationSeconds == 0;
    }

    function _passReturnOrRevert(
        bool _success
    )
        internal
        pure
        virtual
    {
        //solhint-disable-next-line no-inline-assembly
        assembly ("memory-safe") {
            let size := returndatasize()
            let ptr := mload(0x40)
            mstore(0x40, add(ptr, size))
            returndatacopy(ptr, 0, size)
            if _success {
                return(ptr, size)
            }
            revert(ptr, size)
        }
    }

    function getState()
        internal
        pure
        returns (State storage _state)
    {
        bytes32 position = STATE_POSITION;
        //solhint-disable-next-line no-inline-assembly
        assembly {
            _state.slot := position
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC1967.sol

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

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

dependencies/@openzeppelin-contracts-5.7.0/interfaces/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

dependencies/@openzeppelin-contracts-5.7.0/interfaces/draft-IERC1822.sol

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

pragma solidity >=0.4.16;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

dependencies/@openzeppelin-contracts-5.7.0/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)

pragma solidity >=0.4.16;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

dependencies/@openzeppelin-contracts-5.7.0/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * @custom:stateless
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/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);
}

dependencies/@openzeppelin-contracts-5.7.0/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

dependencies/@openzeppelin-contracts-5.7.0/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        bool success = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        bool success = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // only check if target is a contract if the call was successful and the return data is empty
        // otherwise we already know that it was a contract
        if (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/Arrays.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.24;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            while (end - begin > 0x20) {
                // Use first element as pivot
                uint256 pivot = _mload(begin);
                // Position where the pivot should be at the end of the loop
                uint256 pos = begin;

                for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                    if (comp(_mload(it), pivot)) {
                        // If the value stored at the iterator's position comes before the pivot, we increment the
                        // position of the pivot and move the value there.
                        pos += 0x20;
                        _swap(pos, it);
                    }
                }

                _swap(begin, pos); // Swap pivot into place

                // Recurse on the smaller partition, iterate on the larger one.
                uint256 middle = pos + 0x20;
                if (pos - begin < end - middle) {
                    _quickSort(begin, pos, comp);
                    begin = middle;
                } else {
                    _quickSort(middle, end, comp);
                    end = pos;
                }
            }
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new address array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(address[] memory array, uint256 start) internal pure returns (address[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new address array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        address[] memory result = new address[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new bytes32 array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new bytes32 array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        bytes32[] memory result = new bytes32[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new uint256 array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new uint256 array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        uint256[] memory result = new uint256[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(address[] memory array, uint256 start) internal pure returns (address[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        address[] memory array,
        uint256 pos,
        address[] memory replacement
    ) internal pure returns (address[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        address[] memory array,
        uint256 pos,
        address[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (address[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        bytes32[] memory array,
        uint256 pos,
        bytes32[] memory replacement
    ) internal pure returns (bytes32[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        bytes32[] memory array,
        uint256 pos,
        bytes32[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (bytes32[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        uint256[] memory array,
        uint256 pos,
        uint256[] memory replacement
    ) internal pure returns (uint256[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        uint256[] memory array,
        uint256 pos,
        uint256[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (uint256[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytesSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getStringSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(bytes[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(string[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/Comparators.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

dependencies/@openzeppelin-contracts-5.7.0/utils/LowLevelCall.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/SlotDerivation.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for *;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/cryptography/Hashes.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/cryptography/MerkleProof.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     * @dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = Hashes.commutativeKeccak256(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = hasher(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = Hashes.commutativeKeccak256(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = hasher(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/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);
}

dependencies/@openzeppelin-contracts-5.7.0/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

dependencies/@openzeppelin-contracts-5.7.0/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.24;

import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * The following types are supported:
 *
 * - `bytes32` (`Bytes32Set`) since v3.3.0
 * - `address` (`AddressSet`) since v3.3.0
 * - `uint256` (`UintSet`) since v3.3.0
 * - `string` (`StringSet`) since v5.4.0
 * - `bytes` (`BytesSet`) since v5.4.0
 * - `bytes4` (`Bytes4Set`) since v5.6.0
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much
     * gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _pos(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {
        unchecked {
            end = Math.min(end, _length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes32[] memory result = new bytes32[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _pos(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // Bytes4Set

    struct Bytes4Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes4Set storage set, bytes4 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes4Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes4Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(Bytes4Set storage set, uint256 index) internal view returns (bytes4) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(Bytes4Set storage set, uint256 index) internal view returns (bytes4) {
        return bytes4(_pos(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes4Set storage set) internal view returns (bytes4[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes4[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes4Set storage set, uint256 start, uint256 end) internal view returns (bytes4[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        bytes4[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_pos(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_pos(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    struct StringSet {
        // Storage of set values
        string[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(string value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(StringSet storage set, string memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(StringSet storage set, string memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                string memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(StringSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(StringSet storage set, string memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(StringSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(StringSet storage set, uint256 index) internal view returns (string memory) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(StringSet storage set, uint256 index) internal view returns (string memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set) internal view returns (string[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            string[] memory result = new string[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    struct BytesSet {
        // Storage of set values
        bytes[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(BytesSet storage set, bytes memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(BytesSet storage set, bytes memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(BytesSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(BytesSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * IMPORTANT: Deprecated. This function's name clashes with a keyword scheduled for inclusion in Solidity. Developers
     * should use {pos} instead.
     */
    function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
        return pos(set, index);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     *
     * Replacement of the deprecated {at} function.
     */
    function pos(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set) internal view returns (bytes[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes[] memory result = new bytes[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }
}

dependencies/@openzeppelin-contracts-upgradeable-5.7.0/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        OwnableStorage storage $ = _getOwnableStorage();
        return $._owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

dependencies/@openzeppelin-contracts-upgradeable-5.7.0/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/@tenderly/hardhat-tenderly/:hardhat/=node_modules/@tenderly/hardhat-tenderly/node_modules/hardhat/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@ensdomains/address-encoder/=node_modules/flare-smart-contracts/node_modules/@ensdomains/address-encoder/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@ensdomains/ens/=node_modules/flare-smart-contracts/node_modules/@ensdomains/ens/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@ensdomains/ensjs/=node_modules/flare-smart-contracts/node_modules/@ensdomains/ensjs/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@ensdomains/resolver/=node_modules/flare-smart-contracts/node_modules/@ensdomains/resolver/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@gnosis.pm/mock-contract/=node_modules/flare-smart-contracts/node_modules/@gnosis.pm/mock-contract/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@openzeppelin/contract-loader/=node_modules/flare-smart-contracts/node_modules/@openzeppelin/contract-loader/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:@openzeppelin/test-helpers/=node_modules/flare-smart-contracts/node_modules/@openzeppelin/test-helpers/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:eth-gas-reporter/=node_modules/flare-smart-contracts/node_modules/eth-gas-reporter/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:hardhat/=node_modules/flare-smart-contracts/node_modules/hardhat/",
    "/Users/bostjan/sluzba/flare/flare-smart-contracts-v2/node_modules/flare-smart-contracts/:truffle/=node_modules/flare-smart-contracts/node_modules/truffle/",
    ":@ensdomains/=node_modules/@ensdomains/",
    ":@flarenetwork/=node_modules/@flarenetwork/",
    ":@flarenetwork/flare-periphery-contracts/flare/=dependencies/flare-periphery-0.1.38/src/flare/",
    ":@gnosis.pm/=node_modules/@gnosis.pm/",
    ":@openzeppelin-contracts-5.7.0/=dependencies/@openzeppelin-contracts-5.7.0/",
    ":@openzeppelin-contracts-upgradeable-5.7.0/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
    ":@openzeppelin/=node_modules/@openzeppelin/",
    ":@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
    ":@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.7.0/",
    ":@solidity-parser/=node_modules/flare-smart-contracts/node_modules/solhint/node_modules/@solidity-parser/",
    ":eth-gas-reporter/=node_modules/eth-gas-reporter/",
    ":flare-periphery-0.1.38/=dependencies/flare-periphery-0.1.38/src/",
    ":flare-smart-contracts/=node_modules/flare-smart-contracts/",
    ":forge-std-1.10.0/=dependencies/forge-std-1.10.0/src/",
    ":forge-std/=dependencies/forge-std-1.10.0/src/",
    ":hardhat-deploy/=node_modules/flare-smart-contracts/node_modules/hardhat-deploy/",
    ":hardhat/=node_modules/hardhat/",
    ":truffle/=node_modules/truffle/",
    "node_modules/@tenderly/hardhat-tenderly/:hardhat/=node_modules/@tenderly/hardhat-tenderly/node_modules/hardhat/",
    "node_modules/flare-smart-contracts/:@ensdomains/address-encoder/=node_modules/flare-smart-contracts/node_modules/@ensdomains/address-encoder/",
    "node_modules/flare-smart-contracts/:@ensdomains/ens/=node_modules/flare-smart-contracts/node_modules/@ensdomains/ens/",
    "node_modules/flare-smart-contracts/:@ensdomains/ensjs/=node_modules/flare-smart-contracts/node_modules/@ensdomains/ensjs/",
    "node_modules/flare-smart-contracts/:@ensdomains/resolver/=node_modules/flare-smart-contracts/node_modules/@ensdomains/resolver/",
    "node_modules/flare-smart-contracts/:@gnosis.pm/mock-contract/=node_modules/flare-smart-contracts/node_modules/@gnosis.pm/mock-contract/",
    "node_modules/flare-smart-contracts/:@openzeppelin/contract-loader/=node_modules/flare-smart-contracts/node_modules/@openzeppelin/contract-loader/",
    "node_modules/flare-smart-contracts/:@openzeppelin/test-helpers/=node_modules/flare-smart-contracts/node_modules/@openzeppelin/test-helpers/",
    "node_modules/flare-smart-contracts/:eth-gas-reporter/=node_modules/flare-smart-contracts/node_modules/eth-gas-reporter/",
    "node_modules/flare-smart-contracts/:hardhat/=node_modules/flare-smart-contracts/node_modules/hardhat/",
    "node_modules/flare-smart-contracts/:truffle/=node_modules/flare-smart-contracts/node_modules/truffle/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.