Sonic Blaze Testnet

Contract Diff Checker

Contract Name:
SupraOraclePull

Contract Source Code:

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

import "./SupraErrors.sol";
import "./Smr.sol";
import "./BytesLib.sol";
import {ISupraSValueFeed} from "./ISupraSValueFeed.sol";
import {ISupraSValueFeedVerifier} from "./ISupraSValueFeedVerifier.sol";
import {UUPSUpgradeable} from "../lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol";
import {MerkleProof} from "../lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol";
import {EnumerableSetRing} from "./EnumerableSetRing.sol";
import "../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {Ownable2StepUpgradeable} from "../lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol";


/// @title Supra Oracle Pull Model Contract
/// @notice This contract verifies DORA committee Price feeds and returns the price data to the caller
/// @notice The contract does not make assumptions about its owner, but its recommended to be a multisig wallet
contract SupraOraclePull is  UUPSUpgradeable, Ownable2StepUpgradeable {
    using EnumerableSetRing for EnumerableSetRing.EnumerableSetRing;
    /// @notice Push Based Supra Svalue Feed Storage contract
    /// @dev This is used to check if a pair is stale

    ISupraSValueFeed internal supraSValueFeedStorage;
    ISupraSValueFeedVerifier internal supraSValueVerifier;
    // Max Future time is 3sec from the current block time.
    uint256 public constant TIME_DELTA_ALLOWANCE = 3000;
    /// Conversion factor between millisecond and second
    uint256 public constant MILLISECOND_CONVERSION_FACTOR = 1000;
    EnumerableSetRing.EnumerableSetRing private merkleSet;

    event SupraSValueFeedUpdated(address supraSValueFeedStorage);
    event SupraSValueVerifierUpdated(address supraSValueVerifier);
    event PriceUpdate(uint256[] pairs, uint256[] prices, uint256[] updateMask);

    /// @notice Price Pair Feed From Oracle Committee
    struct CommitteeFeed {
        uint32 pair;
        uint128 price;
        uint64 timestamp;
        uint16 decimals;
        uint64 round;
    }

    /// @notice Oracle Committee Pair Price Feed with Merkle proofs of the pair
    struct CommitteeFeedWithProof {
        CommitteeFeed[] committee_feeds;
        bytes32[] proofs;
        bool[] flags;
    }

    /// @notice Multiple Pair Price with Merkle Proof along with Committee details
    struct PriceDetailsWithCommittee {
        uint64 committee_id;
        bytes32 root;
        // DORA committee signature on the merkle root
        uint256[2] sigs;
        CommitteeFeedWithProof committee_data;
    }

    /// @notice Proof for verifying and extracting pairs from DORA committee feeds for Multiple Committees
    struct OracleProofV2 {
        PriceDetailsWithCommittee[] data;
    }

    /// @notice Verified price data
    struct PriceData {
        // List of pairs
        uint256[] pairs;
        // List of prices
        // prices[i] is the price of pairs[i]
        uint256[] prices;
        // List of decimals
        // decimals[i] is the decimals of pairs[i]
        uint256[] decimal;
    }

    /// @notice Verified price data
    struct PriceInfo {
        // List of pairs
        uint256[] pairs;
        // List of prices
        // prices[i] is the price of pairs[i]
        uint256[] prices;
        // List of timestamp
        // timestamp[i] is the timestamp of pairs[i]
        uint256[] timestamp;
        // List of decimals
        // decimals[i] is the decimals of pairs[i]
        uint256[] decimal;
        // List of round
        // round[i] is the round of pairs[i]
        uint256[] round;
    }

    /// @dev disabling the initializers only for the implementaion contract
    constructor() {
        _disableInitializers();
    }


    /// @notice Helper function for upgradeability
    /// @dev While upgrading using UUPS proxy interface, when we call upgradeTo(address) function
    /// @dev we need to check that only owner can upgrade
    /// @param newImplementation address of the new implementation contract
    function _authorizeUpgrade(address newImplementation) internal virtual override onlyOwner {}

    function initialize(address _supraSValueFeedStorage, address _supraSValueVerifier) public initializer {
        Ownable2StepUpgradeable.__Ownable2Step_init();
        _updateSupraSValueFeedInitLevel(ISupraSValueFeed(_supraSValueFeedStorage));
        _updateSupraSValueVerifierInitLevel(ISupraSValueFeedVerifier(_supraSValueVerifier));
    }

    /// @notice Verify Oracle Pairs
    /// @dev throws error if proof is invalid
    /// @dev Stale price data is marked
    /// @param _bytesProof The oracle proof to extract the pairs from
    function verifyOracleProof(bytes calldata _bytesProof) external returns (PriceData memory) {
        OracleProofV2 memory oracle = abi.decode(_bytesProof, (OracleProofV2));
        uint256 paircnt;
        for (uint256 i; i < oracle.data.length; ++i) {
            paircnt += oracle.data[i].committee_data.committee_feeds.length;
            if (merkleSet.contains(oracle.data[i].root)) {
                continue;
            }
            requireRootVerified(oracle.data[i].root, oracle.data[i].sigs, oracle.data[i].committee_id);
            if (!merkleSet.set(oracle.data[i].root)) {
                revert RootIsZero();
            }
        }

        uint256[] memory updateMask = new uint256[](paircnt);

        PriceData memory priceData = PriceData(new uint256[](paircnt), new uint256[](paircnt), new uint256[](paircnt));

        uint256 pair_map = 0;
        uint256 maxFutureTimestamp = block.timestamp * MILLISECOND_CONVERSION_FACTOR + TIME_DELTA_ALLOWANCE;

        for (uint256 a = 0; a < oracle.data.length;) {
            verifyMultileafMerkleProof(oracle.data[a].committee_data, oracle.data[a].root);
            for (uint256 b = 0; b < oracle.data[a].committee_data.committee_feeds.length;) {

                priceData.pairs[pair_map] = oracle.data[a].committee_data.committee_feeds[b].pair;

                uint256 lastRound =
                    supraSValueFeedStorage.getRound(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));
                if (
                    oracle.data[a].committee_data.committee_feeds[b].round > lastRound
                        && oracle.data[a].committee_data.committee_feeds[b].round <= maxFutureTimestamp
                ) {
                    packData(
                        oracle.data[a].committee_data.committee_feeds[b].pair,
                        oracle.data[a].committee_data.committee_feeds[b].round,
                        oracle.data[a].committee_data.committee_feeds[b].decimals,
                        oracle.data[a].committee_data.committee_feeds[b].timestamp,
                        oracle.data[a].committee_data.committee_feeds[b].price
                    );
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 1;
                } else if (oracle.data[a].committee_data.committee_feeds[b].round > maxFutureTimestamp) {
                    revert IncorrectFutureUpdate(
                        oracle.data[a].committee_data.committee_feeds[b].round - block.timestamp * MILLISECOND_CONVERSION_FACTOR
                    );
                } else if (oracle.data[a].committee_data.committee_feeds[b].round < lastRound) {
                    ISupraSValueFeed.priceFeed memory value =
                        supraSValueFeedStorage.getSvalue(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));
                    priceData.prices[pair_map] = value.price;
                    priceData.decimal[pair_map] = value.decimals;
                    updateMask[pair_map] = 0;
                } else {
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 0;
                }

                unchecked {
                    ++b;
                    ++pair_map;
                }
            }

            unchecked {
                ++a;
            }
        }

        emit PriceUpdate(priceData.pairs, priceData.prices, updateMask);
        return priceData;
    }

    /// @notice Verify Oracle Pairs
    /// @dev throws error if proof is invalid
    /// @dev Stale price data is marked
    /// @param _bytesProof The oracle proof to extract the pairs from
    function verifyOracleProofV2(bytes calldata _bytesProof) external returns (PriceInfo memory) {
        OracleProofV2 memory oracle = abi.decode(_bytesProof, (OracleProofV2));
        uint256 paircnt = 0;
        for (uint256 i; i < oracle.data.length; ++i) {
            paircnt += oracle.data[i].committee_data.committee_feeds.length;
            if (merkleSet.contains(oracle.data[i].root)) {
                continue;
            }
            requireRootVerified(oracle.data[i].root, oracle.data[i].sigs, oracle.data[i].committee_id);
            if (!merkleSet.set(oracle.data[i].root)) {
                revert RootIsZero();
            }
        }

        uint256[] memory updateMask = new uint256[](paircnt);

        PriceInfo memory priceData = PriceInfo(
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt)
        );

        uint256 pair_map = 0;
        uint256 maxFutureTimestamp = block.timestamp * MILLISECOND_CONVERSION_FACTOR + TIME_DELTA_ALLOWANCE;

        for (uint256 a = 0; a < oracle.data.length;) {
            verifyMultileafMerkleProof(oracle.data[a].committee_data, oracle.data[a].root);
            for (uint256 b = 0; b < oracle.data[a].committee_data.committee_feeds.length;) {
                priceData.pairs[pair_map] = oracle.data[a].committee_data.committee_feeds[b].pair;

                uint256 lastRound =
                                    supraSValueFeedStorage.getRound(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));

                if (
                    oracle.data[a].committee_data.committee_feeds[b].round > lastRound
                    && oracle.data[a].committee_data.committee_feeds[b].round <= maxFutureTimestamp
                ) {
                    packData(
                        oracle.data[a].committee_data.committee_feeds[b].pair,
                        oracle.data[a].committee_data.committee_feeds[b].round,
                        oracle.data[a].committee_data.committee_feeds[b].decimals,
                        oracle.data[a].committee_data.committee_feeds[b].timestamp,
                        oracle.data[a].committee_data.committee_feeds[b].price
                    );
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.round[pair_map] = oracle.data[a].committee_data.committee_feeds[b].round;
                    priceData.timestamp[pair_map] = oracle.data[a].committee_data.committee_feeds[b].timestamp;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 1;
                } else if (oracle.data[a].committee_data.committee_feeds[b].round > maxFutureTimestamp) {
                    revert IncorrectFutureUpdate(
                        oracle.data[a].committee_data.committee_feeds[b].round - block.timestamp * MILLISECOND_CONVERSION_FACTOR
                    );
                } else if (oracle.data[a].committee_data.committee_feeds[b].round < lastRound) {
                    ISupraSValueFeed.priceFeed memory value =
                                        supraSValueFeedStorage.getSvalue(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));
                    priceData.prices[pair_map] = value.price;
                    priceData.round[pair_map] = lastRound;
                    priceData.timestamp[pair_map] = value.time;
                    priceData.decimal[pair_map] = value.decimals;
                    updateMask[pair_map] = 0;
                } else {
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.round[pair_map] = oracle.data[a].committee_data.committee_feeds[b].round;
                    priceData.timestamp[pair_map] = oracle.data[a].committee_data.committee_feeds[b].timestamp;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 0;
                }

                unchecked {
                    ++b;
                    ++pair_map;
                }
            }

            unchecked {
                ++a;
            }
        }

        emit PriceUpdate(priceData.pairs, priceData.prices, updateMask);
        return priceData;
    }


    /// @notice Verify Oracle Pairs
    /// @dev throws error if proof is invalid
    /// @dev Stale price data is marked
    /// @param oracle The oracle proof to extract the pairs from
    function verifyOracleProofV2(OracleProofV2 calldata oracle) public returns (PriceInfo memory) {
        uint256 paircnt = 0;
        for (uint256 i; i < oracle.data.length; ++i) {
            paircnt += oracle.data[i].committee_data.committee_feeds.length;
            if (merkleSet.contains(oracle.data[i].root)) {
                continue;
            }
            requireRootVerified(oracle.data[i].root, oracle.data[i].sigs, oracle.data[i].committee_id);
            if (!merkleSet.set(oracle.data[i].root)) {
                revert RootIsZero();
            }
        }

        uint256[] memory updateMask = new uint256[](paircnt);

        PriceInfo memory priceData = PriceInfo(
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt),
            new uint256[](paircnt)
        );

        uint256 pair_map = 0;
        uint256 maxFutureTimestamp = block.timestamp * MILLISECOND_CONVERSION_FACTOR + TIME_DELTA_ALLOWANCE;

        for (uint256 a = 0; a < oracle.data.length;) {
            verifyMultileafMerkleProof(oracle.data[a].committee_data, oracle.data[a].root);
            for (uint256 b = 0; b < oracle.data[a].committee_data.committee_feeds.length;) {
                priceData.pairs[pair_map] = oracle.data[a].committee_data.committee_feeds[b].pair;

                uint256 lastRound =
                                    supraSValueFeedStorage.getRound(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));

                if (
                    oracle.data[a].committee_data.committee_feeds[b].round > lastRound
                    && oracle.data[a].committee_data.committee_feeds[b].round <= maxFutureTimestamp
                ) {
                    packData(
                        oracle.data[a].committee_data.committee_feeds[b].pair,
                        oracle.data[a].committee_data.committee_feeds[b].round,
                        oracle.data[a].committee_data.committee_feeds[b].decimals,
                        oracle.data[a].committee_data.committee_feeds[b].timestamp,
                        oracle.data[a].committee_data.committee_feeds[b].price
                    );
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.round[pair_map] = oracle.data[a].committee_data.committee_feeds[b].round;
                    priceData.timestamp[pair_map] = oracle.data[a].committee_data.committee_feeds[b].timestamp;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 1;
                } else if (oracle.data[a].committee_data.committee_feeds[b].round > maxFutureTimestamp) {
                    revert IncorrectFutureUpdate(
                        oracle.data[a].committee_data.committee_feeds[b].round - block.timestamp * MILLISECOND_CONVERSION_FACTOR
                    );
                } else if (oracle.data[a].committee_data.committee_feeds[b].round < lastRound) {
                    ISupraSValueFeed.priceFeed memory value =
                                        supraSValueFeedStorage.getSvalue(uint256(oracle.data[a].committee_data.committee_feeds[b].pair));
                    priceData.prices[pair_map] = value.price;
                    priceData.round[pair_map] = lastRound;
                    priceData.timestamp[pair_map] = value.time;
                    priceData.decimal[pair_map] = value.decimals;
                    updateMask[pair_map] = 0;
                } else {
                    priceData.prices[pair_map] = oracle.data[a].committee_data.committee_feeds[b].price;
                    priceData.round[pair_map] = oracle.data[a].committee_data.committee_feeds[b].round;
                    priceData.timestamp[pair_map] = oracle.data[a].committee_data.committee_feeds[b].timestamp;
                    priceData.decimal[pair_map] = oracle.data[a].committee_data.committee_feeds[b].decimals;
                    updateMask[pair_map] = 0;
                }

                unchecked {
                    ++b;
                    ++pair_map;
                }
            }

            unchecked {
                ++a;
            }
        }

        emit PriceUpdate(priceData.pairs, priceData.prices, updateMask);
        return priceData;
    }

    /// @notice It helps to pack many data points into one single word (32 bytes)
    /// @dev This function will take the required parameters, Will shift the value to its specific position
    /// @dev For concatenating one value with another we are using unary OR operator
    /// @dev Saving the Packed data into the SupraStorage Contract
    /// @param _pair Pair identifier of the token pair
    /// @param _round Round on which DORA nodes collects and post the pair data
    /// @param _decimals Number of decimals that the price of the pair supports
    /// @param _price Price of the pair
    /// @param _time Last updated timestamp of the pair
    function packData(uint256 _pair, uint256 _round, uint256 _decimals, uint256 _time, uint256 _price) internal {
        uint256 r = uint256(_round) << 192;
        r = r | _decimals << 184;
        r = r | _time << 120;
        r = r | _price << 24;
        supraSValueFeedStorage.restrictedSetSupraStorage(_pair, bytes32(r));
    }

    /// @notice helper function to verify the multileaf merkle proof with the root
    function verifyMultileafMerkleProof(CommitteeFeedWithProof memory oracle, bytes32 root) private pure {
        bytes32[] memory leaf_hashes = new bytes32[](oracle.committee_feeds.length);
        bytes4 pair_le;
        bytes16 price_le;
        bytes8 timestamp_le;
        bytes2 decimals_le;
        bytes8 round_le;
        for (uint256 i = 0; i < oracle.committee_feeds.length; i++) {
            pair_le = BytesLib.betole_4(bytes4(abi.encodePacked(oracle.committee_feeds[i].pair)));
            price_le = BytesLib.betole_16(bytes16(abi.encodePacked(oracle.committee_feeds[i].price)));
            timestamp_le = BytesLib.betole_8(bytes8(abi.encodePacked(oracle.committee_feeds[i].timestamp)));
            decimals_le = BytesLib.betole_2(bytes2(abi.encodePacked(oracle.committee_feeds[i].decimals)));
            round_le = BytesLib.betole_8(bytes8(abi.encodePacked(oracle.committee_feeds[i].round)));
            leaf_hashes[i] = keccak256(abi.encodePacked(pair_le, price_le, timestamp_le, decimals_le, round_le));
        }
        if (MerkleProof.multiProofVerify(oracle.proofs,oracle.flags, root, leaf_hashes) == false) {
            revert InvalidProof();
        }
    }

    /// @notice Internal Function to check for zero address
    function _ensureNonZeroAddress(address contract_) private pure {
        if (contract_ == address(0)) {
            revert ZeroAddress();
        }
    }

    /// @notice Helper Function to update the supraSValueFeedStorage Contract address during contract initialization
    /// @param supraSValueFeed new supraSValueFeed
    function _updateSupraSValueFeedInitLevel(ISupraSValueFeed supraSValueFeed) private {
        _ensureNonZeroAddress(address(supraSValueFeed));
        supraSValueFeedStorage = supraSValueFeed;

        emit SupraSValueFeedUpdated(address(supraSValueFeed));
    }

    /// @notice Helper Function to update the supraSvalueVerifier Contract address during contract initialization
    /// @param supraSvalueVerifier new supraSvalueVerifier Contract address
    function _updateSupraSValueVerifierInitLevel(ISupraSValueFeedVerifier supraSvalueVerifier) private {
        _ensureNonZeroAddress(address(supraSvalueVerifier));
        supraSValueVerifier = supraSvalueVerifier;

        emit SupraSValueVerifierUpdated(address(supraSvalueVerifier));
    }

    /// @notice Helper Function to update the supraSValueFeedStorage Contract address in future
    /// @param supraSValueFeed new supraSValueFeedStorage Contract address
    function updateSupraSValueFeed(ISupraSValueFeed supraSValueFeed) external onlyOwner {
        _ensureNonZeroAddress(address(supraSValueFeed));
        supraSValueFeedStorage = supraSValueFeed;

        emit SupraSValueFeedUpdated(address(supraSValueFeed));
    }

    /// @notice Helper Function to check for the address of SupraSValueFeedVerifier contract
    function checkSupraSValueVerifier() external view returns (address) {
        return (address(supraSValueVerifier));
    }

    ///@notice Helper function to check for the address of SupraSValueFeed contract
    function checkSupraSValueFeed() external view returns (address) {
        return (address(supraSValueFeedStorage));
    }

    /// @notice Helper Function to update the supraSvalueVerifier Contract address in future
    /// @param supraSvalueVerifier new supraSvalueVerifier Contract address
    function updateSupraSValueVerifier(ISupraSValueFeedVerifier supraSvalueVerifier) external onlyOwner {
        _ensureNonZeroAddress(address(supraSvalueVerifier));
        supraSValueVerifier = supraSvalueVerifier;

        emit SupraSValueVerifierUpdated(address(supraSvalueVerifier));
    }

    /// @notice Verify root
    /// @dev Requires the provided votes to be verified using SupraSValueFeedVerifierContract contract's authority public key and BLS signature.
    /// @param root The root of the merkle tree created using the pair data
    /// @param sigs The BLS signature on the root of the merkle tree.
    /// @dev This function verifies the BLS signature by calling the SupraSValueFeedVerifierContract that uses BLS precompile contract and checks if the root matches the provided signature.
    /// @dev If the signature verification fails or if there is an issue with the BLS precompile contract call, the function reverts with an error.
    function requireRootVerified(bytes32 root, uint256[2] memory sigs, uint256 committee_id) internal view {
        (bool status,) = address(supraSValueVerifier).staticcall(
            abi.encodeCall(ISupraSValueFeedVerifier.requireHashVerified_V2, (root, sigs, committee_id))
        );
        if (!status) {
            revert DataNotVerified();
        }
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

error ZeroAddress();
error InvalidBatch();
error InvalidTransaction();
error DuplicateCluster();
error ClusterNotVerified();
error BLSInvalidPubllicKeyorSignaturePoints();
error BLSIncorrectInputMessaage();
error DataNotVerified();
error ArrayLengthMismatch();
error InvalidProof();
error DataProofMismatch();
error IncorrectFutureUpdate(uint256 FutureLengthInMsecs);
error RootIsZero();
error SentinalAlreadySet();

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

/// @title Supra SMR Block Utilities
/// @notice This library contains the data structures and functions for hashing SMR blocks.
library Smr {
    /// @notice A vote is a block with a round number.
    /// @dev The library assumes the round number is passed in little endian format
    struct Vote {
        MinBlock smrBlock;
        // SPEC: smrBlock.round.to_le_bytes()
        bytes8 roundLE;
    }

    /// @notice A partial SMR block containing the bare-minimum for hashing
    struct MinBlock {
        uint64 round;
        uint128 timestamp;
        bytes32 author;
        bytes32 qcHash;
        bytes32[] batchHashes;
    }

    /// @notice An SMR Transaction
    struct MinTxn {
        bytes32[] clusterHashes;
        bytes32 sender;
        bytes10 protocol;
        bytes1 tx_sub_type;
        // SPEC: Index of the transaction in its batch
        uint256 txnIdx;
    }

    /// @notice A partial SMR batch containing the bare-minimum for hashing
    /// @dev The library assumes that txnHashes is a list of keccak256 hashes of abi encoded SMR transaction
    struct MinBatch {
        bytes10 protocol;
        // SPEC: List of keccak256(Txn.clusterHashes, Txn.sender, Txn.protocol, Txn.tx_sub_type)
        bytes32[] txnHashes;
        // SPEC: Index of the batch in its block
        uint256 batchIdx;
    }

    /// @notice An SMR Signed Coherent Cluster
    struct SignedCoherentCluster {
        CoherentCluster cc;
        bytes qc;
        uint256 round;
        Origin origin;
    }

    /// @notice An SMR Coherent Cluster containing the price data
    struct CoherentCluster {
        bytes32 dataHash;
        uint256[] pair;
        uint256[] prices;
        uint256[] timestamp;
        uint256[] decimals;
    }

    /// @notice An SMR Txn Sender
    struct Origin {
        bytes32 _publicKeyIdentity;
        uint256 _pubMemberIndex;
        uint256 _committeeIndex;
    }

    /// @notice Hash an SMR Transaction
    /// @param txn The SMR transaction to hash
    /// @return Hash of the SMR Transaction
    function hashTxn(MinTxn memory txn) internal pure returns (bytes32) {
        bytes memory clustersConcat = abi.encodePacked(txn.clusterHashes);
        return keccak256(abi.encodePacked(clustersConcat, txn.sender, txn.protocol, txn.tx_sub_type));
    }

    /// @notice Hash an SMR Batch
    /// @param batch The SMR batch to hash
    /// @return Hash of the SMR Batch
    function hashBatch(MinBatch memory batch) internal pure returns (bytes32) {
        bytes32 txnsHash = keccak256(abi.encodePacked(batch.txnHashes));
        return keccak256(abi.encodePacked(batch.protocol, txnsHash));
    }

    /// @notice Hash an SMR Vote
    /// @param vote The SMR vote to hash
    /// @return Hash of the SMR Vote
    function hashVote(Vote memory vote) internal pure returns (bytes32) {
        bytes32 batchesHash = keccak256(abi.encodePacked(vote.smrBlock.batchHashes));
        bytes32 blockHash = keccak256(
            abi.encodePacked(
                vote.smrBlock.round, vote.smrBlock.timestamp, vote.smrBlock.author, vote.smrBlock.qcHash, batchesHash
            )
        );
        return keccak256(abi.encodePacked(blockHash, vote.roundLE));
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

library BytesLib {
    /// @notice Helper function to convert Big Endian 16 bytes Data To Little Endian or vice versa
    function betole_16(bytes16 a) internal pure returns (bytes16) {
        bytes16 b;
        for (uint256 i; i < 16; i++) {
            bytes1 c = bytes1(a << (i * 8) & bytes1(0xff));
            b = b >> 8 | c;
        }
        return b;
    }

    /// @notice Helper function to convert Big Endian 8 bytes Data To Little Endian or vice versa
    function betole_8(bytes8 a) internal pure returns (bytes8) {
        bytes8 b;
        for (uint256 i; i < 8; i++) {
            bytes1 c = bytes1(a << (i * 8) & bytes1(0xff));
            b = b >> 8 | c;
        }
        return b;
    }

    /// @notice Helper function to convert Big Endian 4 bytes Data To Little Endian or vice versa
    function betole_4(bytes4 a) internal pure returns (bytes4) {
        bytes4 b;
        for (uint256 i; i < 4; i++) {
            bytes1 c = bytes1(a << (i * 8) & bytes1(0xff));
            b = b >> 8 | c;
        }
        return b;
    }

    /// @notice Helper function to convert Big Endian 2 bytes Data To Little Endian or vice versa
    function betole_2(bytes2 a) internal pure returns (bytes2) {
        bytes2 b;
        for (uint256 i; i < 2; i++) {
            bytes1 c = bytes1(a << (i * 8) & bytes1(0xff));
            b = b >> 8 | c;
        }
        return b;
    }
}

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

interface ISupraSValueFeed {
    struct priceFeed {
        uint256 round;
        uint256 decimals;
        uint256 time;
        uint256 price;
    }

    struct derivedData {
        int256 roundDifference;
        int256 timeDifference;
        uint256 derivedPrice;
        uint256 decimals;
    }

    function restrictedSetSupraStorage(uint256 _index, bytes32 _bytes) external;

    function restrictedSetTimestamp(uint256 _tradingPair, uint256 timestamp) external;

    function getTimestamp(uint256 _tradingPair) external view returns (uint256);

    function getRound(uint256 _tradingPair) external view returns (uint256);

    function getSvalue(uint64 _pairIndex) external view returns (bytes32, bool);

    function getSvalues(uint64[] memory _pairIndexes) external view returns (bytes32[] memory, bool[] memory);

    function getDerivedSvalue(uint256 _derivedPairId) external view returns (derivedData memory);

    function getSvalue(uint256 _pairIndex) external view returns (priceFeed memory);

    function getSvalues(uint256[] memory _pairIndexes) external view returns (priceFeed[] memory);
}

pragma solidity ^0.8.24;

interface ISupraSValueFeedVerifier {
    function isPairAlreadyAddedForHCC(uint256[] calldata _pairIndexes) external view returns (bool);

    function isPairAlreadyAddedForHCC(uint256 _pairId) external view returns (bool);

    function requireHashVerified_V2(bytes32 message, uint256[2] memory signature, uint256 committee_id) external view;

    function requireHashVerified_V1(bytes memory message, uint256[2] memory signature) external view;
}

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

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822.sol";
import "../ERC1967/ERC1967Upgrade.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.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @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 ERC1967) 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 ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @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() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

    /**
     * @dev Implementation of the ERC1822 {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 virtual override notDelegated returns (bytes32) {
        return _IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

    /**
     * @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, true);
    }

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @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.
 */
library MerkleProof {
    /**
     * @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.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    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 leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(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}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    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.
     *
     * 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).
     *
     * _Available since v4.7._
     */
    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 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // 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[](totalHashes);
        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 < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    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 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // 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[](totalHashes);
        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 < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;

library  EnumerableSetRing {

    struct EnumerableSetRing {
        bytes32[] list;
        uint256 position;
        mapping(bytes32 key => uint256 position) map;
    }

    uint256 public constant MAX_BUFFER_SIZE = 1000;

    /**
     * @dev Adds a key-value pair to a Set, or updates the value for an existing
     * key. O(1).
     *
     * For Vector The operation old_value -> 0 then 0 -> new_value will be more gas consuming than old_value -> new_value.
     * Returns true if the key was added to the Set, that is if it was not
     * already present.
     */
    function set(EnumerableSetRing storage set, bytes32 value) internal returns (bool) {
        if(!contains(set,value)) {
            uint256 position = set.position;
            if (set.list.length == MAX_BUFFER_SIZE) {
                bytes32 old_value = set.list[position];
                delete set.map[old_value];
                set.list[position] = value;
            } else {
                set.list.push(value);
            }
            set.map[value] = position;
            set.position = ++set.position % MAX_BUFFER_SIZE;
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * @dev Returns true if the key is in the set. O(1).
     */
    function contains(EnumerableSetRing storage set, bytes32 key) internal view returns (bool) {
        if(set.list.length == 0) {
            return false;
        }
        uint256 position = set.map[key];
        return (set.list[position] == key);
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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(EnumerableSetRing storage set) internal view returns (bytes32[] memory) {
        return set.list;
    }

    function capacity(EnumerableSetRing storage set) internal view returns (uint256) {
        return values(set).length;
    }
}

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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @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 Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _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 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _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() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @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 {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./OwnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
    function __Ownable2Step_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable2Step_init_unchained() internal onlyInitializing {
    }
    address private _pendingOwner;

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

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: 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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967Upgrade is IERC1967 {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @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 EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

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

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    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 EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            Address.isContract(IBeacon(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        }
    }
}

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

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

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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 {
    address private _owner;

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

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

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

    /**
     * @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) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @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.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

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

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
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);
}

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

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

pragma solidity ^0.8.0;

/**
 * @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 ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

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

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

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

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../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;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):