Skip to content
Verified contractPartialUNLICENSED

HyperlogueCreator

Address0x631dd7199a9ab798be338ebfb7f8a1ce2c8c6098
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,394,125
Creation transaction
0xdbf6309027…9bb87db377
Libraries
src/libraries/FundedHyperlogue.sol:FundedHyperlogue0x44de…327e76src/libraries/UnfundedHyperlogue.sol:UnfundedHyperlogue0xa744…75f9f8src/libraries/TokenExchangeHyperlogue.sol:TokenExchangeHyperlogue0x4f99…5dc147

36 files

src/HyperlogueCreator.sol

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

import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {FundedHyperlogue} from "./libraries/FundedHyperlogue.sol";
import {UnfundedHyperlogue} from "./libraries/UnfundedHyperlogue.sol";
import {TokenExchangeHyperlogue} from "./libraries/TokenExchangeHyperlogue.sol";
import "./errors/Errors.sol";
import "./events/Events.sol";
import "./structs/Structs.sol";

contract HyperlogueCreator is
    Initializable,
    EIP712Upgradeable,
    UUPSUpgradeable,
    AccessControlUpgradeable,
    ReentrancyGuardUpgradeable
{
    using BitMaps for BitMaps.BitMap;
    using EnumerableSet for EnumerableSet.AddressSet;

    string public constant VERSION = "1.1.0";

    /// @custom:storage-location erc7201:HyperlogueCreator.storage
    // keccak256(abi.encode(uint256(keccak256("HyperlogueCreator.storage")) - 1)) & ~bytes32(uint256(0xff));
    bytes32 constant STORAGE_SLOT = 0x009879b60cd4b26d8537969222eb690900f0d8cb512f68723264d60fb34e2700;

    // keccak256(abi.encodePacked("MAINTAINER_ROLE"))
    bytes32 constant MAINTAINER_ROLE = 0x339759585899103d2ace64958e37e18ccb0504652c81d4a1b8aa80fe2126ab95;

    // keccak256(abi.encodePacked("MODERATOR_ROLE"))
    bytes32 constant MODERATOR_ROLE = 0x71f3d55856e4058ed06ee057d79ada615f65cdf5f9ee88181b914225088f834f;

    // keccak256(abi.encodePacked("UPGRADER_ROLE"))
    bytes32 constant UPGRADER_ROLE = 0x189ab7a9244df0848122154315af71fe140f3db0fe014031783b0946b8c9d2e3;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initializes the contract
    /// @param config The configuration for the contract initialization
    function initialize(InitializeConfig calldata config) public initializer {
        Storage storage store = getStorage();
        store.signer = config.signer;
        store.treasury = config.owner;

        uint256 maxContributionFeePercentage = 1000;
        if (config.contributionFeePercentage > maxContributionFeePercentage) {
            _revert(ContributionFeePercentageOutOfRange.selector);
        }

        store.fundedHyperlogueConfig = FundedHyperlogueConfig({
            contributionFeePercentage: config.contributionFeePercentage,
            minOffsetForSubmissionStart: config.minOffsetStartForSubmission,
            initiatorPlatformFee: config.initiatorPlatformFee,
            initiatorPeripheryPlatformFee: config.initiatorPeripheryPlatformFee,
            participantPlatformFee: config.participantPlatformFee,
            MAX_CONTRIBUTION_FEE_PERCENTAGE: maxContributionFeePercentage,
            AGENCY_FEE_PERCENTAGE_THRESHOLD: 1000,
            DEFAULT_POST_RESULTS_GRACE_OFFSET: 1 days,
            MAX_POST_RESULTS_GRACE_OFFSET: 1 weeks,
            minimumMaxParticipants: 12
        });

        store.unfundedHyperlogueConfig = UnfundedHyperlogueConfig({
            minOffsetForSubmissionStart: config.minOffsetStartForSubmission,
            initiatorPlatformFee: config.initiatorPlatformFee,
            initiatorPeripheryPlatformFee: config.initiatorPeripheryPlatformFee,
            DEFAULT_POST_RESULTS_GRACE_OFFSET: 1 days,
            MAX_POST_RESULTS_GRACE_OFFSET: 1 weeks,
            freeParticipantCount: 12,
            perExtraParticipantFee: config.perParticipantFeeForUnfundedHyperlogues,
            minimumMaxParticipants: 12
        });

        store.tokenExchangeHyperlogueConfig = TokenExchangeHyperlogueConfig({
            contributionFeePercentage: config.contributionFeePercentage,
            minOffsetForSubmissionStart: config.minOffsetStartForSubmission,
            initiatorPlatformFee: config.initiatorPlatformFee,
            initiatorPeripheryPlatformFee: config.initiatorPeripheryPlatformFee,
            participantPlatformFee: config.participantPlatformFee,
            MAX_CONTRIBUTION_FEE_PERCENTAGE: maxContributionFeePercentage,
            DEFAULT_POST_RESULTS_GRACE_OFFSET: 1 days,
            MAX_POST_RESULTS_GRACE_OFFSET: 1 weeks,
            MAX_REWARD_CLAIM_OFFSET: 180 days,
            minimumMaxParticipants: 12
        });

        __EIP712_init("HyperlogueCreator", "1.0");
        __UUPSUpgradeable_init();
        __AccessControl_init();
        __ReentrancyGuard_init();
        _grantRole(DEFAULT_ADMIN_ROLE, config.owner);
        _grantRole(MAINTAINER_ROLE, config.owner);
        _grantRole(MODERATOR_ROLE, config.owner);
        _grantRole(UPGRADER_ROLE, config.upgrader);
    }

    //-----------------------------------------------------------------------------------
    // Public functions
    //-----------------------------------------------------------------------------------

    /// @notice Creates a new Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param signature The signature of the Hyperlogue from the backend to ensure the data is valid
    /// @param hyperlogue The Hyperlogue struct
    /// @param tokenAmountToSend The amount of tokens to send to the contract. For funded ETH hyperlogues
    /// (empty payoutToken) this is the ETH amount, sent in msg.value on top of the platform fee.
    function createHyperlogue(
        string calldata id,
        bytes calldata signature,
        uint256 tokenAmountToSend,
        uint256 signatureDeadline,
        Hyperlogue memory hyperlogue
    ) public payable nonReentrant {
        Storage storage store = getStorage();
        {
            bytes32 digest = getCreateHyperlogueDigest(id, hyperlogue, signatureDeadline);
            if (!SignatureChecker.isValidSignatureNow(store.signer, digest, signature)) {
                _revert(InvalidCreateSignature.selector);
            }
            if (block.timestamp > signatureDeadline) {
                _revert(DeadlineInPast.selector);
            }
        }

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.createHyperlogue(id, hyperlogue, store, tokenAmountToSend);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            UnfundedHyperlogue.createHyperlogue(id, hyperlogue, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.createHyperlogue(id, hyperlogue, store, tokenAmountToSend);
        }
    }

    /// @notice Increases the max participants for a hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param newMaxParticipants The new maximum number of participants
    function increaseMaxParticipants(string calldata id, uint32 newMaxParticipants) public payable {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.increaseMaxParticipants(id, newMaxParticipants, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            UnfundedHyperlogue.increaseMaxParticipants(id, newMaxParticipants, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.increaseMaxParticipants(id, newMaxParticipants, store);
        }
    }

    /// @notice Allows creator to increase their contribution before submission end time
    /// @param id The id of the Hyperlogue
    /// @param additionalPayoutAmount The additional payout amount to add (excluding fees)
    /// @param tokenAmountToSend The total amount of tokens to send (including fees). For funded ETH
    /// hyperlogues this is the ETH amount, sent in msg.value on top of the periphery platform fee.
    function increaseCreatorContribution(string calldata id, uint256 additionalPayoutAmount, uint256 tokenAmountToSend)
        public
        payable
        nonReentrant
    {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.increaseCreatorContribution(id, additionalPayoutAmount, tokenAmountToSend, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            _revert(IncorrectHyperlogueType.selector);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.increaseCreatorContribution(id, additionalPayoutAmount, tokenAmountToSend, store);
        }
    }

    /// @notice Join the Hyperlogue
    /// @param id - The id of the Hyperlogue
    /// @param tokensToSend - The amount of ERC20 tokens to send. For funded ETH hyperlogues this is the
    /// ETH amount, sent in msg.value on top of the platform fee.
    /// @param signature - The signature of the Join from the backend to ensure the data is valid
    /// @param signatureDeadline - The deadline till which the signature is valid
    function joinHyperlogue(string calldata id, uint256 tokensToSend, bytes memory signature, uint256 signatureDeadline)
        public
        payable
        nonReentrant
    {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        {
            bytes32 digest = getJoinHyperlogueDigest(id, msg.sender, signatureDeadline);
            if (!SignatureChecker.isValidSignatureNow(store.signer, digest, signature)) {
                _revert(InvalidJoinSignature.selector);
            }
            if (block.timestamp > signatureDeadline) {
                _revert(DeadlineInPast.selector);
            }
        }

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.joinHyperlogue(id, tokensToSend, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            UnfundedHyperlogue.joinHyperlogue(id, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.joinHyperlogue(id, tokensToSend, store);
        }
    }

    /// @notice Claims the payout from a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param startIndex The index to start refunding from
    /// @param batchSize The number of participants to refund in this batch
    /// @param attemptCreatorRefund Whether to attempt refunding the creator
    function refundHyperlogue(string calldata id, uint256 startIndex, uint256 batchSize, bool attemptCreatorRefund)
        public
        nonReentrant
    {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];
        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.refundHyperlogue(id, startIndex, batchSize, attemptCreatorRefund, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            _revert(IncorrectHyperlogueType.selector);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.refundHyperlogue(id, startIndex, batchSize, attemptCreatorRefund, store);
        }
    }

    /// @notice Sets the payout root of a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param payoutRoot The payout root of the Hyperlogue
    /// @param signature The signature of the payout root.
    /// -  The signature must be signed by the backend signer to enforce the correct data is posted
    function postPayoutRoot(string calldata id, bytes32 payoutRoot, bytes calldata signature) public {
        Storage storage store = getStorage();
        if (!SignatureChecker.isValidSignatureNow(store.signer, getMerkleRootDigest(id, payoutRoot), signature)) {
            _revert(InvalidMerkleRootSignature.selector);
        }

        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.postPayoutRoot(id, payoutRoot, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            _revert(IncorrectHyperlogueType.selector);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.postPayoutRoot(id, payoutRoot, store);
        }
    }

    /// @notice Claims the payout from a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param amount The amount to claim
    /// @param proof The Merkle proof
    /// @param toAddress The address to send the payout to
    function claimFromHyperlogue(string memory id, uint256 amount, bytes32[] calldata proof, address toAddress)
        external
        nonReentrant
    {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.claimFromHyperlogue(store, id, amount, proof, toAddress);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            _revert(IncorrectHyperlogueType.selector);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.claimFromHyperlogue(store, id, amount, proof, toAddress);
        }
    }

    /// @notice Claims contribution and agency fees from a Hyperlogue
    /// @param id The id of the Hyperlogue to claim fees from
    /// @dev Requires that the payout root has been posted
    /// @dev Requires that the minimum number of participants has been reached
    /// @dev Transfers contribution and agency fees to the owner if not already claimed
    function claimFeesFromHyperlogue(string memory id) external nonReentrant {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.claimFeesFromHyperlogue(store, id);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            _revert(IncorrectHyperlogueType.selector);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.claimFeesFromHyperlogue(store, id);
        }
    }

    //-----------------------------------------------------------------------------------
    // Moderator functions
    //-----------------------------------------------------------------------------------

    /// @notice Rejects a Hyperlogue before submission starts
    /// @dev Only callable by MODERATOR_ROLE. Refunds creator if funded.
    /// @param id The id of the Hyperlogue to reject
    function rejectHyperlogue(string calldata id) public onlyRole(MODERATOR_ROLE) nonReentrant {
        Storage storage store = getStorage();
        Hyperlogue memory hyperlogue = store.hyperlogues[id];
        if (hyperlogue.hyperlogueType == HyperlogueType.Funded) {
            FundedHyperlogue.rejectHyperlogue(id, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.Unfunded) {
            UnfundedHyperlogue.rejectHyperlogue(id, store);
        } else if (hyperlogue.hyperlogueType == HyperlogueType.TokenExchange) {
            TokenExchangeHyperlogue.rejectHyperlogue(id, store);
        }
    }

    //-----------------------------------------------------------------------------------
    // Admin functions
    //-----------------------------------------------------------------------------------

    /// @notice Sets the signer of the contract
    /// @param _signer The new signer
    function setSigner(address _signer) public onlyRole(DEFAULT_ADMIN_ROLE) {
        getStorage().signer = _signer;
        emit SignerChanged(_signer);
    }

    function setResultPostRelayer(address _resultPostRelayer) public onlyRole(DEFAULT_ADMIN_ROLE) {
        getStorage().resultPostRelayer = _resultPostRelayer;
        emit ResultPostRelayerChanged(_resultPostRelayer);
    }

    function setTreasury(address _treasury) public onlyRole(DEFAULT_ADMIN_ROLE) {
        getStorage().treasury = _treasury;
        emit TreasuryChanged(_treasury);
    }

    function setAgencyFeePercentageThresholdForFundedHyperlogues(uint256 _agencyFeePercentageThreshold)
        public
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        getStorage().fundedHyperlogueConfig.AGENCY_FEE_PERCENTAGE_THRESHOLD = _agencyFeePercentageThreshold;
        emit AgencyFeePercentageThresholdChanged(_agencyFeePercentageThreshold);
    }

    function setMaxContributionFeePercentage(HyperlogueType hyperlogueType, uint256 _maxContributionFeePercentage)
        public
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE = _maxContributionFeePercentage;
            emit MaxContributionFeePercentageChanged(HyperlogueType.Funded, _maxContributionFeePercentage);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE = _maxContributionFeePercentage;
            emit MaxContributionFeePercentageChanged(HyperlogueType.TokenExchange, _maxContributionFeePercentage);
        } else {
            _revert(IncorrectHyperlogueType.selector);
        }
    }

    //-----------------------------------------------------------------------------------
    // Maintainer functions
    //-----------------------------------------------------------------------------------

    function setContributionFeePercentage(HyperlogueType hyperlogueType, uint32 _contributionFeePercentage)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            if (_contributionFeePercentage > store.fundedHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE) {
                _revert(ContributionFeePercentageOutOfRange.selector);
            }
            store.fundedHyperlogueConfig.contributionFeePercentage = _contributionFeePercentage;
            emit ContributionFeePercentageChanged(HyperlogueType.Funded, _contributionFeePercentage);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            if (_contributionFeePercentage > store.tokenExchangeHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE) {
                _revert(ContributionFeePercentageOutOfRange.selector);
            }
            store.tokenExchangeHyperlogueConfig.contributionFeePercentage = _contributionFeePercentage;
            emit ContributionFeePercentageChanged(HyperlogueType.TokenExchange, _contributionFeePercentage);
        } else {
            _revert(IncorrectHyperlogueType.selector);
        }
    }

    function setInitiatorPlatformFee(HyperlogueType hyperlogueType, uint96 _initiatorPlatformFee)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.initiatorPlatformFee = _initiatorPlatformFee;
            emit InitiatorPlatformFeeChanged(HyperlogueType.Funded, _initiatorPlatformFee);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.initiatorPlatformFee = _initiatorPlatformFee;
            emit InitiatorPlatformFeeChanged(HyperlogueType.Unfunded, _initiatorPlatformFee);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.initiatorPlatformFee = _initiatorPlatformFee;
            emit InitiatorPlatformFeeChanged(HyperlogueType.TokenExchange, _initiatorPlatformFee);
        }
    }

    function setParticipantPlatformFee(HyperlogueType hyperlogueType, uint96 _participantPlatformFee)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.participantPlatformFee = _participantPlatformFee;
            emit ParticipantPlatformFeeChanged(HyperlogueType.Funded, _participantPlatformFee);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.participantPlatformFee = _participantPlatformFee;
            emit ParticipantPlatformFeeChanged(HyperlogueType.TokenExchange, _participantPlatformFee);
        } else {
            _revert(IncorrectHyperlogueType.selector);
        }
    }

    function setInitiatorPeripheryPlatformFee(HyperlogueType hyperlogueType, uint96 _initiatorPeripheryPlatformFee)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.initiatorPeripheryPlatformFee = _initiatorPeripheryPlatformFee;
            emit InitiatorPeripheryPlatformFeeChanged(HyperlogueType.Funded, _initiatorPeripheryPlatformFee);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.initiatorPeripheryPlatformFee = _initiatorPeripheryPlatformFee;
            emit InitiatorPeripheryPlatformFeeChanged(HyperlogueType.Unfunded, _initiatorPeripheryPlatformFee);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.initiatorPeripheryPlatformFee = _initiatorPeripheryPlatformFee;
            emit InitiatorPeripheryPlatformFeeChanged(HyperlogueType.TokenExchange, _initiatorPeripheryPlatformFee);
        }
    }

    function setFreeParticipantsForUnfundedHyperlogues(uint32 _freeSlots) public onlyRole(MAINTAINER_ROLE) {
        getStorage().unfundedHyperlogueConfig.freeParticipantCount = _freeSlots;
        emit FreeParticipantsForUnfundedHyperloguesChanged(_freeSlots);
    }

    function setPerParticipantFeeForUnfundedHyperlogues(uint96 _paidParticipantFee) public onlyRole(MAINTAINER_ROLE) {
        getStorage().unfundedHyperlogueConfig.perExtraParticipantFee = _paidParticipantFee;
        emit PerParticipantFeeForUnfundedHyperloguesChanged(_paidParticipantFee);
    }

    function setMinOffsetForSubmissionStart(HyperlogueType hyperlogueType, uint32 _minOffsetForSubmissionStart)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.minOffsetForSubmissionStart = _minOffsetForSubmissionStart;
            emit MinOffsetStartChange(HyperlogueType.Funded, _minOffsetForSubmissionStart);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.minOffsetForSubmissionStart = _minOffsetForSubmissionStart;
            emit MinOffsetStartChange(HyperlogueType.Unfunded, _minOffsetForSubmissionStart);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.minOffsetForSubmissionStart = _minOffsetForSubmissionStart;
            emit MinOffsetStartChange(HyperlogueType.TokenExchange, _minOffsetForSubmissionStart);
        }
    }

    function setDefaultPostResultsGraceOffset(HyperlogueType hyperlogueType, uint48 _defaultPostResultsGraceOffset)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET = _defaultPostResultsGraceOffset;
            emit DefaultPostResultsGraceOffsetChanged(HyperlogueType.Funded, _defaultPostResultsGraceOffset);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET = _defaultPostResultsGraceOffset;
            emit DefaultPostResultsGraceOffsetChanged(HyperlogueType.Unfunded, _defaultPostResultsGraceOffset);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET = _defaultPostResultsGraceOffset;
            emit DefaultPostResultsGraceOffsetChanged(HyperlogueType.TokenExchange, _defaultPostResultsGraceOffset);
        }
    }

    function setMaxPostResultsGraceOffset(HyperlogueType hyperlogueType, uint48 _maxPostResultsGraceOffset)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET = _maxPostResultsGraceOffset;
            emit MaxPostResultsGraceOffsetChanged(HyperlogueType.Funded, _maxPostResultsGraceOffset);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET = _maxPostResultsGraceOffset;
            emit MaxPostResultsGraceOffsetChanged(HyperlogueType.Unfunded, _maxPostResultsGraceOffset);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET = _maxPostResultsGraceOffset;
            emit MaxPostResultsGraceOffsetChanged(HyperlogueType.TokenExchange, _maxPostResultsGraceOffset);
        }
    }

    function setMinimumMaxParticipants(HyperlogueType hyperlogueType, uint32 _minimumMaxParticipants)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        Storage storage store = getStorage();

        if (hyperlogueType == HyperlogueType.Funded) {
            store.fundedHyperlogueConfig.minimumMaxParticipants = _minimumMaxParticipants;
            emit MinimumMaxParticipantsChanged(HyperlogueType.Funded, _minimumMaxParticipants);
        } else if (hyperlogueType == HyperlogueType.Unfunded) {
            store.unfundedHyperlogueConfig.minimumMaxParticipants = _minimumMaxParticipants;
            emit MinimumMaxParticipantsChanged(HyperlogueType.Unfunded, _minimumMaxParticipants);
        } else if (hyperlogueType == HyperlogueType.TokenExchange) {
            store.tokenExchangeHyperlogueConfig.minimumMaxParticipants = _minimumMaxParticipants;
            emit MinimumMaxParticipantsChanged(HyperlogueType.TokenExchange, _minimumMaxParticipants);
        }
    }

    function setMaxRewardClaimOffsetForTokenExchangeHyperlogues(uint48 _maxRewardClaimOffset)
        public
        onlyRole(MAINTAINER_ROLE)
    {
        getStorage().tokenExchangeHyperlogueConfig.MAX_REWARD_CLAIM_OFFSET = _maxRewardClaimOffset;
        emit MaxRewardClaimOffsetChanged(_maxRewardClaimOffset);
    }

    /// @notice Sends the platform's ETH fee income to the treasury
    /// @dev ETH held for funded hyperlogues is never sent
    function claimEth() public onlyRole(MAINTAINER_ROLE) {
        Storage storage store = getStorage();
        uint256 claimable = address(this).balance - store.ethHeldForHyperlogues;
        if (claimable == 0) {
            _revert(NoEthToClaim.selector);
        }
        (bool success,) = payable(store.treasury).call{value: claimable}("");
        if (!success) {
            _revert(EthTransferFailed.selector);
        }
        emit EthClaimed(store.treasury, claimable);
    }

    //-----------------------------------------------------------------------------------
    // View functions
    //-----------------------------------------------------------------------------------

    /// @notice Gets the Hyperlogue
    function getHyperlogue(string calldata id) public view returns (Hyperlogue memory) {
        return getStorage().hyperlogues[id];
    }

    /// @notice Gets the payout root of a Hyperlogue
    function getHyperlogueRoot(string calldata id) public view returns (bytes32) {
        return getStorage().hyperloguePayoutRoots[id];
    }

    /// @notice Gets the claimed sum of a Hyperlogue
    function getHyperloguePayoutSum(string calldata id) public view returns (uint256) {
        return getStorage().hyperlogueClaimedSum[id];
    }

    /// @notice Gets the signer of the contract
    function getSigner() public view returns (address) {
        return getStorage().signer;
    }

    function getTreasury() public view returns (address) {
        return getStorage().treasury;
    }

    function getResultPostRelayer() public view returns (address) {
        return getStorage().resultPostRelayer;
    }

    function getContributionFeePercentage() public view returns (uint32 fundedFee, uint32 tokenExchangeFee) {
        Storage storage store = getStorage();
        fundedFee = store.fundedHyperlogueConfig.contributionFeePercentage;
        tokenExchangeFee = store.tokenExchangeHyperlogueConfig.contributionFeePercentage;
    }

    function getHyperlogueAmountPaid(string calldata id, address participant) public view returns (uint256) {
        return getStorage().amountSent[id][participant];
    }

    /// @notice Gets the ETH owed to users of funded hyperlogues
    function getEthHeldForHyperlogues() public view returns (uint256) {
        return getStorage().ethHeldForHyperlogues;
    }

    /// @notice Gets the platform ETH that claimEth would send to the treasury
    function getClaimableEth() public view returns (uint256) {
        return address(this).balance - getStorage().ethHeldForHyperlogues;
    }

    function getInitiatorPlatformFee()
        public
        view
        returns (uint96 fundedFee, uint96 unfundedFee, uint96 tokenExchangeFee)
    {
        Storage storage store = getStorage();
        fundedFee = store.fundedHyperlogueConfig.initiatorPlatformFee;
        unfundedFee = store.unfundedHyperlogueConfig.initiatorPlatformFee;
        tokenExchangeFee = store.tokenExchangeHyperlogueConfig.initiatorPlatformFee;
    }

    function getParticipantPlatformFee() public view returns (uint96 fundedFee, uint96 tokenExchangeFee) {
        Storage storage store = getStorage();
        fundedFee = store.fundedHyperlogueConfig.participantPlatformFee;
        tokenExchangeFee = store.tokenExchangeHyperlogueConfig.participantPlatformFee;
    }

    function getInitiatorPeripheryPlatformFee()
        public
        view
        returns (uint96 fundedFee, uint96 unfundedFee, uint96 tokenExchangeFee)
    {
        Storage storage store = getStorage();
        fundedFee = store.fundedHyperlogueConfig.initiatorPeripheryPlatformFee;
        unfundedFee = store.unfundedHyperlogueConfig.initiatorPeripheryPlatformFee;
        tokenExchangeFee = store.tokenExchangeHyperlogueConfig.initiatorPeripheryPlatformFee;
    }

    function getMinOffsetForSubmissionStart()
        public
        view
        returns (uint32 fundedOffset, uint32 unfundedOffset, uint32 tokenExchangeOffset)
    {
        Storage storage store = getStorage();
        fundedOffset = store.fundedHyperlogueConfig.minOffsetForSubmissionStart;
        unfundedOffset = store.unfundedHyperlogueConfig.minOffsetForSubmissionStart;
        tokenExchangeOffset = store.tokenExchangeHyperlogueConfig.minOffsetForSubmissionStart;
    }

    function getAgencyFeePercentageThresholdForFundedHyperlogues() public view returns (uint256) {
        return getStorage().fundedHyperlogueConfig.AGENCY_FEE_PERCENTAGE_THRESHOLD;
    }

    function getFreeParticipantsForUnfundedHyperlogues() public view returns (uint32) {
        return getStorage().unfundedHyperlogueConfig.freeParticipantCount;
    }

    function getPerParticipantFeeForUnfundedHyperlogues() public view returns (uint96) {
        return getStorage().unfundedHyperlogueConfig.perExtraParticipantFee;
    }

    function getMinimumMaxParticipants()
        public
        view
        returns (uint32 fundedMin, uint32 unfundedMin, uint32 tokenExchangeMin)
    {
        Storage storage store = getStorage();
        fundedMin = store.fundedHyperlogueConfig.minimumMaxParticipants;
        unfundedMin = store.unfundedHyperlogueConfig.minimumMaxParticipants;
        tokenExchangeMin = store.tokenExchangeHyperlogueConfig.minimumMaxParticipants;
    }

    function getParticipants(string calldata id) public view returns (address[] memory) {
        return getStorage().participants[id].values();
    }

    function isHyperlogueRejected(string calldata id) public view returns (bool) {
        return getStorage().rejected[id];
    }

    function getDefaultPostResultsGraceOffset()
        public
        view
        returns (uint48 fundedOffset, uint48 unfundedOffset, uint48 tokenExchangeOffset)
    {
        Storage storage store = getStorage();
        fundedOffset = store.fundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
        unfundedOffset = store.unfundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
        tokenExchangeOffset = store.tokenExchangeHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
    }

    function getMaxPostResultsGraceOffset()
        public
        view
        returns (uint48 fundedOffset, uint48 unfundedOffset, uint48 tokenExchangeOffset)
    {
        Storage storage store = getStorage();
        fundedOffset = store.fundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET;
        unfundedOffset = store.unfundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET;
        tokenExchangeOffset = store.tokenExchangeHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET;
    }

    function getMaxContributionFeePercentage() public view returns (uint256 fundedMax, uint256 tokenExchangeMax) {
        Storage storage store = getStorage();
        fundedMax = store.fundedHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE;
        tokenExchangeMax = store.tokenExchangeHyperlogueConfig.MAX_CONTRIBUTION_FEE_PERCENTAGE;
    }

    function getMaxRewardClaimOffsetForTokenExchangeHyperlogues() public view returns (uint48) {
        return getStorage().tokenExchangeHyperlogueConfig.MAX_REWARD_CLAIM_OFFSET;
    }

    //-----------------------------------------------------------------------------------
    // Internal functions
    //-----------------------------------------------------------------------------------

    /// @dev Returns the storage struct
    function getStorage() internal pure returns (Storage storage store) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            store.slot := slot
        }
    }

    /**
     * @notice More efficiently reverts with a bytes4 selector
     * @param selector The selector to revert with
     */
    function _revert(bytes4 selector) internal pure {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(0x0, selector)
            revert(0x0, 0x04)
        }
    }

    //-----------------------------------------------------------------------------------
    // EIP712
    //-----------------------------------------------------------------------------------
    function getCreateHyperlogueDigest(string calldata id, Hyperlogue memory hyperlogue, uint256 deadline)
        public
        view
        returns (bytes32)
    {
        return _hashTypedDataV4(
            keccak256(
                abi.encode(
                    keccak256("CreateHyperlogue(string id,Hyperlogue hyperlogue,uint256 deadline)"),
                    keccak256(bytes(id)),
                    hyperlogue,
                    deadline
                )
            )
        );
    }

    function getJoinHyperlogueDigest(string calldata id, address user, uint256 deadline)
        public
        view
        returns (bytes32)
    {
        return _hashTypedDataV4(
            keccak256(
                abi.encode(
                    keccak256("JoinHyperlogue(string id,address user,uint256 deadline)"),
                    keccak256(bytes(id)),
                    user,
                    deadline
                )
            )
        );
    }

    function getMerkleRootDigest(string calldata id, bytes32 merkleRoot) public view returns (bytes32) {
        return _hashTypedDataV4(
            keccak256(
                abi.encode(keccak256("MerkleRoot(string id,bytes32 merkleRoot)"), keccak256(bytes(id)), merkleRoot)
            )
        );
    }

    //-----------------------------------------------------------------------------------
    // UUPS
    //-----------------------------------------------------------------------------------

    function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE) {}
}

lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 reininitialization) 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 Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.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.
 */
abstract contract UUPSUpgradeable is Initializable, 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 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() {
        _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();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @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 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 ERC1967-compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    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 ERC1967.
     *
     * 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);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/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 "../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;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

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

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 */
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @custom:storage-location erc7201:openzeppelin.storage.EIP712
    struct EIP712Storage {
        /// @custom:oz-renamed-from _HASHED_NAME
        bytes32 _hashedName;
        /// @custom:oz-renamed-from _HASHED_VERSION
        bytes32 _hashedVersion;

        string _name;
        string _version;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;

    function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
        assembly {
            $.slot := EIP712StorageLocation
        }
    }

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
        __EIP712_init_unchained(name, version);
    }

    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
        EIP712Storage storage $ = _getEIP712Storage();
        $._name = name;
        $._version = version;

        // Reset prior values in storage if upgrading
        $._hashedName = 0;
        $._hashedVersion = 0;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        EIP712Storage storage $ = _getEIP712Storage();
        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
        // and the EIP712 domain is not reliable, as it will be missing name and version.
        require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");

        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Name() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._name;
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Version() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._version;
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
     */
    function _EIP712NameHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory name = _EIP712Name();
        if (bytes(name).length > 0) {
            return keccak256(bytes(name));
        } else {
            // If the name is empty, the contract may have been upgraded without initializing the new storage.
            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
            bytes32 hashedName = $._hashedName;
            if (hashedName != 0) {
                return hashedName;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
     */
    function _EIP712VersionHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory version = _EIP712Version();
        if (bytes(version).length > 0) {
            return keccak256(bytes(version));
        } else {
            // If the version is empty, the contract may have been upgraded without initializing the new storage.
            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
            bytes32 hashedVersion = $._hashedVersion;
            if (hashedVersion != 0) {
                return hashedVersion;
            } else {
                return keccak256("");
            }
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol

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

pragma solidity ^0.8.20;

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

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

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol

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

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @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);

    /**
     * @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 EIP1967 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 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 EIP1967) using
     * the https://eth.wiki/json-rpc/API#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 EIP1967 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 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 EIP1967 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 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();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 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 {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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.
     */
    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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

    /**
     * @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 AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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
     * {FailedInnerCall} 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 AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @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, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @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, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @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 {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // 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 (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @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 {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) 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 FailedInnerCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
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
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Strings.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

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

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

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

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

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

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

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

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

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

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

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

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

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol

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

pragma solidity ^0.8.20;

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

    /**
     * @dev Calldata version of {verify}
     */
    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.
     */
    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}
     */
    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.
     */
    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.
     */
    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).
     */
    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.
        if (leavesLen + proofLen != totalHashes + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // 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) {
            if (proofPos != proofLen) {
                revert MerkleProofInvalidMultiproof();
            }
            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.
     */
    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.
        if (leavesLen + proofLen != totalHashes + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // 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) {
            if (proofPos != proofLen) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Sorts the pair (a, b) and hashes the result.
     */
    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    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)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol

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

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
        return
            (error == ECDSA.RecoverError.NoError && recovered == signer) ||
            isValidERC1271SignatureNow(signer, hash, signature);
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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) {
        // (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.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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 {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

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

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/BitMaps.sol)
pragma solidity ^0.8.20;

/**
 * @dev Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential.
 * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
 *
 * BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type.
 * Hence booleans corresponding to 256 _sequential_ indices would only consume a single slot,
 * unlike the regular `bool` which would consume an entire slot for a single value.
 *
 * This results in gas savings in two ways:
 *
 * - Setting a zero value to non-zero only once every 256 times
 * - Accessing the same warm slot for every 256 _sequential_ indices
 */
library BitMaps {
    struct BitMap {
        mapping(uint256 bucket => uint256) _data;
    }

    /**
     * @dev Returns whether the bit at `index` is set.
     */
    function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        return bitmap._data[bucket] & mask != 0;
    }

    /**
     * @dev Sets the bit at `index` to the boolean `value`.
     */
    function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
        if (value) {
            set(bitmap, index);
        } else {
            unset(bitmap, index);
        }
    }

    /**
     * @dev Sets the bit at `index`.
     */
    function set(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] |= mask;
    }

    /**
     * @dev Unsets the bit at `index`.
     */
    function unset(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] &= ~mask;
    }
}

lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

/**
 * @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.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [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 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 _at(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;
    }

    // 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 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}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

src/errors/Errors.sol

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

error IfAddressOrAmountZeroBothMustBeZero();
error InvalidCreateSignature();
error HyperlogueAlreadyExists();
error HyperlogueNotExists();
error StartTimeCannotBeInPast();
error EndTimeCannotBeBeforeStartTime();
error ReleaseTimeCannotBeforeEndTime();
error ReleaseTimeCannotAfterMaxOffsetAfterSubmissionEndTime();
error HyperlogueCannotHaveZeroCreator();
error InvalidMerkleRootSignature();
error SenderNotHyperlogueCreator();
error SenderNotIdealogi();
error RootAlreadySet();
error AlreadyClaimedFromHyperlogue();
error InvalidClaimProof();
error NotYetSubmissionEndTime();
error SenderNotPassKyc();
error CannotJoinBeforeSubmissionStartTime();
error CannotJoinAfterSubmissionEndTime();
error CannotRefundBeforeSubmissionEndTime();
error CannotClaimMoreThanTotalDeposit();
error NotReachedMinimumParticipants();
error ReachedMinimumParticipants();
error AlreadyJoined();
error AgencyFeeExistWhileNoParticipantFee();
error AgencyFeeExceedsThreshold();
error ContributionFeePercentageOutOfRange();
error RootNotPosted();
error InsufficientTokensSent();
error CreateHyperlogue_AgencyFeesClaimedMustBeFalse();
error CreateHyperlogue_ContributionFeesClaimedMustBeFalse();
error CreateHyperlogue_ContributionFeePercentageMustBeZeroSoItCanBeInitialized();
error CreateHyperlogue_ContributionFeeMustBeZero();
error CreateHyperlogue_AgencyFeeMustBeZero();
error CannotRejectAfterSubmissionStartTime();
error HLAlreadyRejected();
error CannotJoinRejectedHL();
error InsufficientGasSubsidy();
error DeadlineInPast();
error MaxParticipantsReachedForHyperlogue();
error EthTransferFailed();
error FeesAlreadyClaimed();
error PayoutTokenCannotBeZero();
error MinParticipantsCannotBeZero();
error IncorrectHyperlogueType();
error NewMaxParticipantsMustBeGreaterThanCurrent();
error CannotIncreaseMaxParticipantsAfterSubmissionEndTime();
error MaxParticipantsBelowMinimumThreshold();
error InvalidJoinSignature();
error CannotIncreaseCreatorContributionAfterSubmissionEndTime();
error ParticipantAndPayoutTokenMustBeDifferent();
error RewardClaimDateBeforeMaxReleaseTime();
error RewardClaimDateExceedsMaxOffset();
error CannotClaimBeforeRewardClaimDate();
error CreatorCannotJoinHyperlogue();
error MinimumParticipantsExceedsMaxParticipants();
error NotAParticipant();
error UnexpectedETHSent();
error ZeroAdditionalPayout();
error IncorrectEthAmount();
error NoEthToClaim();

src/events/Events.sol

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

import {Hyperlogue, HyperlogueType} from "../structs/Structs.sol";

event HyperlogueCreated(string indexed id, Hyperlogue hyperlogue);

event HyperloguePayoutRootSet(string indexed id, bytes32 payoutRoot);

event ClaimedFromHyperlogue(string indexed id, address claimer, uint256 amount);

event SignerChanged(address newSigner);

event MinOffsetStartChange(HyperlogueType hyperlogueType, uint32 newMinOffset);

event ContributionFeePercentageChanged(HyperlogueType hyperlogueType, uint32 newContributionFeePercentage);

event ResultPostRelayerChanged(address newRelayer);

event RefundedHyperlogue(string indexed id, address participant, uint256 amount);

event HyperlogueRejected(string indexed id);

event JoinedHyperlogue(string indexed id, address participant, uint256 amount);

event InitiatorPlatformFeeChanged(HyperlogueType hyperlogueType, uint96 newInitiatorPlatformFee);

event ParticipantPlatformFeeChanged(HyperlogueType hyperlogueType, uint96 newEntrantPlatformFee);

event MaxContributionFeePercentageChanged(HyperlogueType hyperlogueType, uint256 newMaxContributionFeePercentage);

event AgencyFeePercentageThresholdChanged(uint256 newAgencyFeePercentageThreshold);

event DefaultPostResultsGraceOffsetChanged(HyperlogueType hyperlogueType, uint48 newDefaultPostResultsGraceOffset);

event MaxPostResultsGraceOffsetChanged(HyperlogueType hyperlogueType, uint48 newMaxPostResultsGraceOffset);

event MaxRewardClaimOffsetChanged(uint48 newMaxRewardClaimOffset);

event FreeParticipantsForUnfundedHyperloguesChanged(uint32 newNumberOfParticipants);

event PerParticipantFeeForUnfundedHyperloguesChanged(uint96 newPerParticipantFee);

event MaxParticipantsIncreased(string indexed id, uint32 oldMaxParticipants, uint32 newMaxParticipants);

event MinimumMaxParticipantsChanged(HyperlogueType hyperlogueType, uint32 newMinimum);

event TreasuryChanged(address newTreasury);

event CreatorContributionIncreased(
    string indexed id, address creator, uint256 additionalAmount, uint256 newTotalContribution, uint256 newPayoutAmount
);

event InitiatorPeripheryPlatformFeeChanged(HyperlogueType hyperlogueType, uint96 newInitiatorPeripheryPlatformFee);

event RefundFailed(string indexed id, address recipient, uint256 amount);

event AgencyFeePaid(string indexed id, address creator, uint256 amount);

event AgencyFeeTransferFailed(string indexed id, address creator, uint256 amount);

event ContributionFeePaid(string indexed id, address treasury, uint256 amount);

event EthClaimed(address treasury, uint256 amount);

src/libraries/FundedHyperlogue.sol

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

import {SafeERC20WithTaxCheck} from "../libraries/SafeERC20WithTaxCheck.sol";
import "../structs/Structs.sol";
import "../errors/Errors.sol";
import "../events/Events.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";

/// @dev library to process Funded Hyperlogues

library FundedHyperlogue {
    using EnumerableSet for EnumerableSet.AddressSet;
    using BitMaps for BitMaps.BitMap;

    /// @dev Gas forwarded to a recipient on ETH sends that must not revert the transaction.
    uint256 private constant ETH_TRANSFER_GAS_LIMIT = 50_000;

    //-----------------------------------------------------------------------------------
    // External functions
    //-----------------------------------------------------------------------------------

    /// @notice Creates a funded Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param hyperlogue The Hyperlogue struct
    /// @param store The contract storage to mutate
    /// @param tokenAmountToSend The amount of tokens to send to the contract. For ETH hyperlogues this is
    /// the ETH amount, and msg.value must equal it plus the initiator platform fee.

    function createHyperlogue(
        string calldata id,
        Hyperlogue memory hyperlogue,
        Storage storage store,
        uint256 tokenAmountToSend
    ) external {
        _checkInitiatorGas(store, false);

        if (hyperlogue.contributionFeePercentage != 0) {
            _revert(CreateHyperlogue_ContributionFeePercentageMustBeZeroSoItCanBeInitialized.selector);
        }

        /// @custom:auditor - This is important for the refund function
        if (hyperlogue.minimumParticipants == 0) {
            _revert(MinParticipantsCannotBeZero.selector);
        }

        if (hyperlogue.contributionFee != 0) {
            _revert(CreateHyperlogue_ContributionFeeMustBeZero.selector);
        }

        if (hyperlogue.agencyFee != 0) {
            _revert(CreateHyperlogue_AgencyFeeMustBeZero.selector);
        }

        if (hyperlogue.agencyFeesClaimed) {
            _revert(CreateHyperlogue_AgencyFeesClaimedMustBeFalse.selector);
        }

        if (hyperlogue.contributionFeesClaimed) {
            _revert(CreateHyperlogue_ContributionFeesClaimedMustBeFalse.selector);
        }

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueCannotHaveZeroCreator.selector);
        }

        if (hyperlogue.submissionStartTime < block.timestamp + store.fundedHyperlogueConfig.minOffsetForSubmissionStart)
        {
            _revert(StartTimeCannotBeInPast.selector);
        }

        if (hyperlogue.submissionEndTime < hyperlogue.submissionStartTime) {
            _revert(EndTimeCannotBeBeforeStartTime.selector);
        }

        // 0. If not specified, the max release timestamp by the agent is the submission end time + 1 day (default)
        // 1. If specified, the max release timestamp by the agent cannot be before the submission end time
        // 2. If specified, also cannot be greater than the max post results grace offset (1 week)
        if (hyperlogue.maxReleaseTimeByAgent == 0) {
            hyperlogue.maxReleaseTimeByAgent =
                hyperlogue.submissionEndTime + store.fundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
        } else if (hyperlogue.maxReleaseTimeByAgent < hyperlogue.submissionEndTime) {
            _revert(ReleaseTimeCannotBeforeEndTime.selector);
        }

        if (
            hyperlogue.maxReleaseTimeByAgent
                > hyperlogue.submissionEndTime + store.fundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET
        ) {
            _revert(ReleaseTimeCannotAfterMaxOffsetAfterSubmissionEndTime.selector);
        }

        if (store.hyperlogues[id].creator != address(0)) {
            _revert(HyperlogueAlreadyExists.selector);
        }

        if (hyperlogue.participantFee == 0 && hyperlogue.payoutAmount == 0) {
            _revert(IncorrectHyperlogueType.selector);
        }

        if (hyperlogue.agencyFeePercentage > store.fundedHyperlogueConfig.AGENCY_FEE_PERCENTAGE_THRESHOLD) {
            _revert(AgencyFeeExceedsThreshold.selector);
        }

        if (hyperlogue.participantFee == 0 && hyperlogue.agencyFeePercentage > 0) {
            _revert(AgencyFeeExistWhileNoParticipantFee.selector);
        }

        if (hyperlogue.maxParticipants == 0) {
            hyperlogue.maxParticipants = type(uint32).max; // Default behaviour
        } else if (hyperlogue.maxParticipants < store.fundedHyperlogueConfig.minimumMaxParticipants) {
            _revert(MaxParticipantsBelowMinimumThreshold.selector);
        }

        if (hyperlogue.minimumParticipants > hyperlogue.maxParticipants) {
            _revert(MinimumParticipantsExceedsMaxParticipants.selector);
        }

        //Transfer the tokens from the creator to the contract
        uint32 contributionFeePercentage = store.fundedHyperlogueConfig.contributionFeePercentage;
        if (hyperlogue.payoutAmount > 0) {
            uint256 minContributionFee = hyperlogue.payoutAmount * uint256(contributionFeePercentage) / PERCENTAGE_BASE;
            uint256 minToTransfer = hyperlogue.payoutAmount + minContributionFee;
            uint256 amountTransferred = _collectPayment(
                store,
                hyperlogue.payoutToken,
                tokenAmountToSend,
                minToTransfer,
                store.fundedHyperlogueConfig.initiatorPlatformFee
            );

            uint256 contributionFee = amountTransferred * uint256(contributionFeePercentage)
                / (PERCENTAGE_BASE + uint256(contributionFeePercentage));
            store.amountSent[id][hyperlogue.creator] = amountTransferred;
            hyperlogue.contributionFee = contributionFee;
            hyperlogue.payoutAmount = amountTransferred - contributionFee;
        } else {
            _requireExactEth(hyperlogue.payoutToken, store.fundedHyperlogueConfig.initiatorPlatformFee);
        }

        hyperlogue.contributionFeePercentage = contributionFeePercentage;
        store.hyperlogues[id] = hyperlogue;
        emit HyperlogueCreated(id, hyperlogue);
    }

    /// @notice Increases max participants for a funded hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param newMaxParticipants The new max participants
    /// @param store The contract storage to mutate
    function increaseMaxParticipants(string calldata id, uint32 newMaxParticipants, Storage storage store) external {
        _checkInitiatorGas(store, true);

        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator != msg.sender) {
            _revert(SenderNotHyperlogueCreator.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        if (block.timestamp >= hyperlogue.submissionEndTime) {
            _revert(CannotIncreaseMaxParticipantsAfterSubmissionEndTime.selector);
        }

        if (newMaxParticipants <= hyperlogue.maxParticipants) {
            _revert(NewMaxParticipantsMustBeGreaterThanCurrent.selector);
        }

        uint32 oldMax = hyperlogue.maxParticipants;
        hyperlogue.maxParticipants = newMaxParticipants;

        emit MaxParticipantsIncreased(id, oldMax, newMaxParticipants);
    }

    function increaseCreatorContribution(
        string calldata id,
        uint256 additionalPayoutAmount,
        uint256 tokenAmountToSend,
        Storage storage store
    ) external {
        _checkInitiatorGas(store, true);

        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator != msg.sender) {
            _revert(SenderNotHyperlogueCreator.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        if (block.timestamp >= hyperlogue.submissionEndTime) {
            _revert(CannotIncreaseCreatorContributionAfterSubmissionEndTime.selector);
        }

        if (additionalPayoutAmount == 0) {
            _revert(ZeroAdditionalPayout.selector);
        }

        uint32 contributionFeePercentage = hyperlogue.contributionFeePercentage;
        uint256 minContributionFee = additionalPayoutAmount * uint256(contributionFeePercentage) / PERCENTAGE_BASE;
        uint256 minToTransfer = additionalPayoutAmount + minContributionFee;

        uint256 amountTransferred = _collectPayment(
            store,
            hyperlogue.payoutToken,
            tokenAmountToSend,
            minToTransfer,
            store.fundedHyperlogueConfig.initiatorPeripheryPlatformFee
        );

        uint256 contributionFee = amountTransferred * uint256(contributionFeePercentage)
            / (PERCENTAGE_BASE + uint256(contributionFeePercentage));

        store.amountSent[id][msg.sender] += amountTransferred;
        hyperlogue.payoutAmount += (amountTransferred - contributionFee);
        hyperlogue.contributionFee += contributionFee;

        emit CreatorContributionIncreased(
            id, msg.sender, amountTransferred, store.amountSent[id][msg.sender], hyperlogue.payoutAmount
        );
    }

    /// @notice Join a funded Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param tokensToSend The amount of ERC20 tokens to send. For ETH hyperlogues this is the ETH amount,
    /// and msg.value must equal it plus the participant platform fee.
    /// @param store The contract storage to mutate
    function joinHyperlogue(string calldata id, uint256 tokensToSend, Storage storage store) external {
        _checkParticipantGas(store);

        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (store.rejected[id]) {
            _revert(CannotJoinRejectedHL.selector);
        }

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator == msg.sender) {
            _revert(CreatorCannotJoinHyperlogue.selector);
        }

        if (store.participants[id].contains(msg.sender)) {
            _revert(AlreadyJoined.selector);
        }

        if (block.timestamp < hyperlogue.submissionStartTime) {
            _revert(CannotJoinBeforeSubmissionStartTime.selector);
        }

        if (hyperlogue.submissionEndTime <= block.timestamp) {
            _revert(CannotJoinAfterSubmissionEndTime.selector);
        }

        if (store.participants[id].length() >= hyperlogue.maxParticipants) {
            _revert(MaxParticipantsReachedForHyperlogue.selector);
        }

        store.participants[id].add(msg.sender);

        uint256 tokensTransferred;
        if (hyperlogue.participantFee > 0 || tokensToSend > 0) {
            uint256 minContributionFee =
                hyperlogue.participantFee * hyperlogue.contributionFeePercentage / PERCENTAGE_BASE;
            uint256 minToTransfer = hyperlogue.participantFee + minContributionFee;
            tokensTransferred = _collectPayment(
                store,
                hyperlogue.payoutToken,
                tokensToSend,
                minToTransfer,
                store.fundedHyperlogueConfig.participantPlatformFee
            );

            uint256 contributionFee = tokensTransferred * uint256(hyperlogue.contributionFeePercentage)
                / (PERCENTAGE_BASE + uint256(hyperlogue.contributionFeePercentage));
            uint256 agencyFee = (tokensTransferred - contributionFee) * hyperlogue.agencyFeePercentage / PERCENTAGE_BASE;

            uint256 totalFees = agencyFee + contributionFee;

            store.hyperlogues[id].payoutAmount += tokensTransferred - totalFees;
            store.hyperlogues[id].agencyFee += agencyFee;
            store.hyperlogues[id].contributionFee += contributionFee;
            //Update the amount paid
            store.amountSent[id][msg.sender] += tokensTransferred;
        } else {
            _requireExactEth(hyperlogue.payoutToken, store.fundedHyperlogueConfig.participantPlatformFee);
        }
        emit JoinedHyperlogue(id, msg.sender, tokensTransferred);
    }

    function rejectHyperlogue(string calldata id, Storage storage store) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.submissionStartTime <= block.timestamp) {
            _revert(CannotRejectAfterSubmissionStartTime.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        store.rejected[id] = true;

        address creator = hyperlogue.creator;
        store.hyperlogueRefunded[id][creator] = true;
        uint256 initiatorShare = store.amountSent[id][creator];
        if (initiatorShare > 0) {
            _sendRefund(store, id, hyperlogue.payoutToken, creator, initiatorShare);
        }
        emit HyperlogueRejected(id);
    }

    /// @notice Refunds participants when minimum participants not reached after submission end
    /// @param id The id of the Hyperlogue
    /// @param startIndex The starting index for batch processing participants
    /// @param batchSize The number of participants to process in this batch
    /// @param attemptCreatorRefund Whether to attempt refunding the creator
    /// @param store The contract storage to mutate
    function refundHyperlogue(
        string calldata id,
        uint256 startIndex,
        uint256 batchSize,
        bool attemptCreatorRefund,
        Storage storage store
    ) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.submissionEndTime > block.timestamp) {
            _revert(CannotRefundBeforeSubmissionEndTime.selector);
        }

        uint256 participantCount = store.participants[id].length();

        if (participantCount >= hyperlogue.minimumParticipants) {
            _revert(ReachedMinimumParticipants.selector);
        }

        address creator = store.hyperlogues[id].creator;

        // Refund the creator, if not already refunded
        if (attemptCreatorRefund && !store.hyperlogueRefunded[id][creator]) {
            store.hyperlogueRefunded[id][creator] = true;
            uint256 initiatorShare = store.amountSent[id][creator];
            if (initiatorShare > 0) {
                _sendRefund(store, id, hyperlogue.payoutToken, creator, initiatorShare);
            }
        }

        uint256 endIndex = startIndex + batchSize;
        // Ensure we don't exceed the bounds of the array
        if (endIndex > participantCount) {
            endIndex = participantCount;
        }

        for (uint256 i = startIndex; i < endIndex; i++) {
            address recipient = store.participants[id].at(i);
            uint256 amountSent = store.amountSent[id][recipient];
            if (!store.hyperlogueRefunded[id][recipient] && amountSent > 0) {
                store.hyperlogueRefunded[id][recipient] = true;
                _sendRefund(store, id, hyperlogue.payoutToken, recipient, amountSent);
            }
        }
    }

    /// @notice Sets the payout root of a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param payoutRoot The payout root of the Hyperlogue
    /// @param store The contract storage to mutate
    function postPayoutRoot(string calldata id, bytes32 payoutRoot, Storage storage store) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.submissionEndTime > block.timestamp) {
            _revert(NotYetSubmissionEndTime.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        address creator = hyperlogue.creator;

        // If the max release timestmap is not yet reached, only the creator can post the root
        if (block.timestamp <= hyperlogue.maxReleaseTimeByAgent) {
            if (msg.sender != creator) {
                _revert(SenderNotHyperlogueCreator.selector);
            }
        }

        // If it is past the max agent release timestamp, the result post relayer or creator can post the root
        if (hyperlogue.maxReleaseTimeByAgent < block.timestamp) {
            if (msg.sender != store.resultPostRelayer && msg.sender != creator) {
                _revert(SenderNotIdealogi.selector);
            }
        }

        if (store.hyperloguePayoutRoots[id] != bytes32(0)) {
            _revert(RootAlreadySet.selector);
        }
        store.hyperloguePayoutRoots[id] = payoutRoot;
        emit HyperloguePayoutRootSet(id, payoutRoot);
    }

    /// @notice Claims the payout from a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param amount The amount to claim
    /// @param proof The Merkle proof
    /// @param toAddress The address to send the payout to
    function claimFromHyperlogue(
        Storage storage store,
        string memory id,
        uint256 amount,
        bytes32[] calldata proof,
        address toAddress
    ) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (!hyperlogue.contributionFeesClaimed) {
            store.hyperlogues[id].contributionFeesClaimed = true;
            if (hyperlogue.contributionFee > 0) {
                _payContributionFee(store, id, hyperlogue);
            }
        }
        if (!hyperlogue.agencyFeesClaimed) {
            store.hyperlogues[id].agencyFeesClaimed = true;
            if (hyperlogue.agencyFee > 0) {
                // A creator wallet that rejects ETH must not block winners from claiming,
                // so a failed ETH agency fee stays owed and is collectable via claimFeesFromHyperlogue.
                if (_isNativeEth(hyperlogue.payoutToken)) {
                    if (_trySendEth(store, hyperlogue.creator, hyperlogue.agencyFee)) {
                        emit AgencyFeePaid(id, hyperlogue.creator, hyperlogue.agencyFee);
                    } else {
                        store.hyperlogues[id].agencyFeesClaimed = false;
                        emit AgencyFeeTransferFailed(id, hyperlogue.creator, hyperlogue.agencyFee);
                    }
                } else {
                    _payAgencyFee(store, id, hyperlogue);
                }
            }
        }

        bytes32 root = store.hyperloguePayoutRoots[id];
        if (root == bytes32(0)) {
            _revert(RootNotPosted.selector);
        }

        address payoutAddress = toAddress != address(0) ? toAddress : msg.sender;

        if (!store.participants[id].contains(payoutAddress)) {
            _revert(NotAParticipant.selector);
        }

        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(payoutAddress, amount))));
        if (!MerkleProof.verify(proof, root, leaf)) {
            _revert(InvalidClaimProof.selector);
        }

        uint256 participantCount = store.participants[id].length();
        if (participantCount < hyperlogue.minimumParticipants) {
            _revert(NotReachedMinimumParticipants.selector);
        }
        if (store.claimedHyperlogues[payoutAddress].get(uint256(keccak256(abi.encode(id))))) {
            _revert(AlreadyClaimedFromHyperlogue.selector);
        }

        uint256 newTotalAmountClaimed = store.hyperlogueClaimedSum[id] + amount;
        if (newTotalAmountClaimed > hyperlogue.payoutAmount) {
            _revert(CannotClaimMoreThanTotalDeposit.selector);
        }

        store.claimedHyperlogues[payoutAddress].set(uint256(keccak256(abi.encode(id))));
        store.hyperlogueClaimedSum[id] = newTotalAmountClaimed;

        if (amount > 0) {
            _send(store, hyperlogue.payoutToken, payoutAddress, amount);
        }

        emit ClaimedFromHyperlogue(id, msg.sender, amount);
    }

    /// @notice Claims contribution and agency fees from a Hyperlogue
    /// @param store The storage struct from HyperlogueCreator
    /// @param id The id of the Hyperlogue to claim fees from
    /// @dev Requires that the payout root has been posted
    /// @dev Requires that the minimum number of participants has been reached
    /// @dev Transfers transaction and agency fees to the owner if not already claimed
    function claimFeesFromHyperlogue(Storage storage store, string memory id) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        bytes32 root = store.hyperloguePayoutRoots[id];
        if (root == bytes32(0)) {
            _revert(RootNotPosted.selector);
        }

        uint256 participantCount = store.participants[id].length();
        if (participantCount < hyperlogue.minimumParticipants) {
            _revert(NotReachedMinimumParticipants.selector);
        }

        if (hyperlogue.contributionFeesClaimed && hyperlogue.agencyFeesClaimed) {
            _revert(FeesAlreadyClaimed.selector);
        }

        if (!hyperlogue.contributionFeesClaimed) {
            store.hyperlogues[id].contributionFeesClaimed = true;
            if (hyperlogue.contributionFee > 0) {
                _payContributionFee(store, id, hyperlogue);
            }
        }

        if (!hyperlogue.agencyFeesClaimed) {
            store.hyperlogues[id].agencyFeesClaimed = true;
            if (hyperlogue.agencyFee > 0) {
                _payAgencyFee(store, id, hyperlogue);
            }
        }
    }

    //-----------------------------------------------------------------------------------
    // Internal functions
    //-----------------------------------------------------------------------------------

    /**
     * @notice More efficiently reverts with a bytes4 selector
     * @param selector The selector to revert with
     */
    function _revert(bytes4 selector) internal pure {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(0x0, selector)
            revert(0x0, 0x04)
        }
    }

    function _checkInitiatorGas(Storage storage store, bool trueIfPeriphery) internal view {
        if (trueIfPeriphery) {
            if (msg.value < store.fundedHyperlogueConfig.initiatorPeripheryPlatformFee) {
                _revert(InsufficientGasSubsidy.selector);
            }
        } else {
            if (msg.value < store.fundedHyperlogueConfig.initiatorPlatformFee) {
                _revert(InsufficientGasSubsidy.selector);
            }
        }
    }

    function _checkParticipantGas(Storage storage store) internal view {
        if (msg.value < store.fundedHyperlogueConfig.participantPlatformFee) {
            _revert(InsufficientGasSubsidy.selector);
        }
    }

    function _isNativeEth(address payoutToken) internal pure returns (bool) {
        return payoutToken == address(0);
    }

    /// @notice Takes payment for a funded hyperlogue and returns the amount received
    /// @dev For ETH the payment is part of msg.value, which must equal platformFee + amountToSend exactly
    function _collectPayment(
        Storage storage store,
        address payoutToken,
        uint256 amountToSend,
        uint256 minimumAmount,
        uint256 platformFee
    ) internal returns (uint256 amountReceived) {
        if (!_isNativeEth(payoutToken)) {
            return SafeERC20WithTaxCheck.safeTransferFrom(
                payoutToken, msg.sender, address(this), amountToSend, minimumAmount
            );
        }

        if (msg.value != platformFee + amountToSend) {
            _revert(IncorrectEthAmount.selector);
        }
        if (amountToSend < minimumAmount) {
            _revert(InsufficientTokensSent.selector);
        }

        store.ethHeldForHyperlogues += amountToSend;
        return amountToSend;
    }

    /// @dev For ETH hyperlogues where no payment is due, msg.value must be exactly the platform fee
    function _requireExactEth(address payoutToken, uint256 platformFee) internal view {
        if (_isNativeEth(payoutToken) && msg.value != platformFee) {
            _revert(IncorrectEthAmount.selector);
        }
    }

    /// @dev Reverts the transaction if the payment fails
    function _send(Storage storage store, address payoutToken, address to, uint256 amount) internal {
        if (!_isNativeEth(payoutToken)) {
            SafeERC20.safeTransfer(IERC20(payoutToken), to, amount);
            return;
        }

        store.ethHeldForHyperlogues -= amount;
        (bool success,) = payable(to).call{value: amount}("");
        if (!success) {
            _revert(EthTransferFailed.selector);
        }
    }

    /// @dev Forwards a fixed amount of gas and copies no return data, so the recipient cannot
    /// exhaust the caller's gas. Returns false instead of reverting when the payment fails.
    function _trySendEth(Storage storage store, address to, uint256 amount) internal returns (bool success) {
        store.ethHeldForHyperlogues -= amount;
        assembly ("memory-safe") {
            success := call(ETH_TRANSFER_GAS_LIMIT, to, amount, 0, 0, 0, 0)
        }
        if (!success) {
            store.ethHeldForHyperlogues += amount;
        }
    }

    /// @dev The caller marks the recipient as refunded before calling. A failed ETH refund is
    /// marked as not refunded again so a later refundHyperlogue call can retry it.
    function _sendRefund(
        Storage storage store,
        string memory id,
        address payoutToken,
        address recipient,
        uint256 amount
    ) internal {
        if (_isNativeEth(payoutToken)) {
            if (!_trySendEth(store, recipient, amount)) {
                store.hyperlogueRefunded[id][recipient] = false;
                emit RefundFailed(id, recipient, amount);
                return;
            }
        } else {
            SafeERC20.safeTransfer(IERC20(payoutToken), recipient, amount);
        }
        emit RefundedHyperlogue(id, recipient, amount);
    }

    function _payContributionFee(Storage storage store, string memory id, Hyperlogue memory hyperlogue) internal {
        _send(store, hyperlogue.payoutToken, store.treasury, hyperlogue.contributionFee);
        emit ContributionFeePaid(id, store.treasury, hyperlogue.contributionFee);
    }

    function _payAgencyFee(Storage storage store, string memory id, Hyperlogue memory hyperlogue) internal {
        _send(store, hyperlogue.payoutToken, hyperlogue.creator, hyperlogue.agencyFee);
        emit AgencyFeePaid(id, hyperlogue.creator, hyperlogue.agencyFee);
    }
}

src/libraries/SafeERC20WithTaxCheck.sol

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

import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

library SafeERC20WithTaxCheck {
    error SafeERC20WithTaxCheck_MinimumAmountNotMet();

    function safeTransferFrom(address token, address from, address to, uint256 amount, uint256 minimumAmount)
        internal
        returns (uint256 amountTransferred)
    {
        uint256 balanceBefore = IERC20(token).balanceOf(to);
        SafeERC20.safeTransferFrom(IERC20(token), from, to, amount);
        uint256 balanceAfter = IERC20(token).balanceOf(to);
        amountTransferred = balanceAfter - balanceBefore;
        if (amountTransferred < minimumAmount) {
            revert SafeERC20WithTaxCheck_MinimumAmountNotMet();
        }
    }
}

src/libraries/TokenExchangeHyperlogue.sol

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

import {SafeERC20WithTaxCheck} from "../libraries/SafeERC20WithTaxCheck.sol";
import "../structs/Structs.sol";
import "../errors/Errors.sol";
import "../events/Events.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";

/// @dev library to process Token Exchange Hyperlogues

library TokenExchangeHyperlogue {
    using EnumerableSet for EnumerableSet.AddressSet;
    using BitMaps for BitMaps.BitMap;

    //-----------------------------------------------------------------------------------
    // External functions
    //-----------------------------------------------------------------------------------

    /// @notice Creates a Token Exchange Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param hyperlogue The Hyperlogue struct
    /// @param store The contract storage to mutate
    /// @param tokenAmountToSend The amount of tokens to send to the contract
    function createHyperlogue(
        string memory id,
        Hyperlogue memory hyperlogue,
        Storage storage store,
        uint256 tokenAmountToSend
    ) external {
        _checkInitiatorGas(store, false);

        if (hyperlogue.contributionFeePercentage != 0) {
            _revert(CreateHyperlogue_ContributionFeePercentageMustBeZeroSoItCanBeInitialized.selector);
        }

        /// @custom:auditor - This is important for the refund function
        if (hyperlogue.minimumParticipants == 0) {
            _revert(MinParticipantsCannotBeZero.selector);
        }

        if (hyperlogue.payoutToken == address(0) || hyperlogue.participantToken == address(0)) {
            _revert(PayoutTokenCannotBeZero.selector);
        }

        if (hyperlogue.participantToken == hyperlogue.payoutToken) {
            _revert(ParticipantAndPayoutTokenMustBeDifferent.selector);
        }

        if (hyperlogue.contributionFee != 0) {
            _revert(CreateHyperlogue_ContributionFeeMustBeZero.selector);
        }

        if (hyperlogue.agencyFee != 0) {
            _revert(CreateHyperlogue_AgencyFeeMustBeZero.selector);
        }

        if (hyperlogue.agencyFeesClaimed) {
            _revert(CreateHyperlogue_AgencyFeesClaimedMustBeFalse.selector);
        }

        if (hyperlogue.contributionFeesClaimed) {
            _revert(CreateHyperlogue_ContributionFeesClaimedMustBeFalse.selector);
        }

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueCannotHaveZeroCreator.selector);
        }

        if (
            hyperlogue.submissionStartTime
                < block.timestamp + store.tokenExchangeHyperlogueConfig.minOffsetForSubmissionStart
        ) {
            _revert(StartTimeCannotBeInPast.selector);
        }

        if (hyperlogue.submissionEndTime < hyperlogue.submissionStartTime) {
            _revert(EndTimeCannotBeBeforeStartTime.selector);
        }

        // 0. If not specified, the max release timestamp by the agent is the submission end time + 1 day (default)
        // 1. If specified, the max release timestamp by the agent cannot be before the submission end time
        // 2. If specified, also cannot be greater than the max post results grace offset (1 week)
        if (hyperlogue.maxReleaseTimeByAgent == 0) {
            hyperlogue.maxReleaseTimeByAgent =
                hyperlogue.submissionEndTime + store.tokenExchangeHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
        } else if (hyperlogue.maxReleaseTimeByAgent < hyperlogue.submissionEndTime) {
            _revert(ReleaseTimeCannotBeforeEndTime.selector);
        }

        if (
            hyperlogue.maxReleaseTimeByAgent
                > hyperlogue.submissionEndTime + store.tokenExchangeHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET
        ) {
            _revert(ReleaseTimeCannotAfterMaxOffsetAfterSubmissionEndTime.selector);
        }

        if (hyperlogue.rewardClaimDate < hyperlogue.maxReleaseTimeByAgent) {
            _revert(RewardClaimDateBeforeMaxReleaseTime.selector);
        }

        if (
            hyperlogue.rewardClaimDate
                > hyperlogue.maxReleaseTimeByAgent + store.tokenExchangeHyperlogueConfig.MAX_REWARD_CLAIM_OFFSET
        ) {
            _revert(RewardClaimDateExceedsMaxOffset.selector);
        }

        if (store.hyperlogues[id].creator != address(0)) {
            _revert(HyperlogueAlreadyExists.selector);
        }

        if (hyperlogue.participantFee == 0 || hyperlogue.payoutAmount == 0) {
            _revert(IncorrectHyperlogueType.selector);
        }

        if (hyperlogue.maxParticipants == 0) {
            hyperlogue.maxParticipants = type(uint32).max; // Default behaviour
        } else if (hyperlogue.maxParticipants < store.tokenExchangeHyperlogueConfig.minimumMaxParticipants) {
            _revert(MaxParticipantsBelowMinimumThreshold.selector);
        }

        if (hyperlogue.minimumParticipants > hyperlogue.maxParticipants) {
            _revert(MinimumParticipantsExceedsMaxParticipants.selector);
        }

        //Transfer the payout tokens from the creator to the contract
        uint32 contributionFeePercentage = store.tokenExchangeHyperlogueConfig.contributionFeePercentage;
        if (hyperlogue.payoutAmount > 0) {
            uint256 minContributionFee = hyperlogue.payoutAmount * uint256(contributionFeePercentage) / PERCENTAGE_BASE;
            uint256 minToTransfer = hyperlogue.payoutAmount + minContributionFee;
            uint256 amountTransferred = SafeERC20WithTaxCheck.safeTransferFrom(
                hyperlogue.payoutToken, msg.sender, address(this), tokenAmountToSend, minToTransfer
            );

            // Store total amount sent by creator (for later fee calculation)
            store.amountSent[id][hyperlogue.creator] = amountTransferred;

            uint256 contributionFee = amountTransferred * uint256(contributionFeePercentage)
                / (PERCENTAGE_BASE + uint256(contributionFeePercentage));

            // hyperlogue.contributionFee = contributionFee;

            hyperlogue.payoutAmount = amountTransferred - contributionFee;
        }

        hyperlogue.contributionFeePercentage = contributionFeePercentage;
        store.hyperlogues[id] = hyperlogue;
        emit HyperlogueCreated(id, hyperlogue);
    }

    /// @notice Increases max participants for a Token Exchange hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param newMaxParticipants The new max participants
    /// @param store The contract storage to mutate
    function increaseMaxParticipants(string calldata id, uint32 newMaxParticipants, Storage storage store) external {
        _checkInitiatorGas(store, true);

        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator != msg.sender) {
            _revert(SenderNotHyperlogueCreator.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        if (block.timestamp >= hyperlogue.submissionEndTime) {
            _revert(CannotIncreaseMaxParticipantsAfterSubmissionEndTime.selector);
        }

        if (newMaxParticipants <= hyperlogue.maxParticipants) {
            _revert(NewMaxParticipantsMustBeGreaterThanCurrent.selector);
        }

        uint32 oldMax = hyperlogue.maxParticipants;
        hyperlogue.maxParticipants = newMaxParticipants;

        emit MaxParticipantsIncreased(id, oldMax, newMaxParticipants);
    }

    /// @notice Increases the creator contribution for a Token Exchange hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param additionalPayoutAmount The additional payout amount to add (excluding fees)
    /// @param tokenAmountToSend The total amount of tokens to send (including fees)
    /// @param store The contract storage to mutate
    function increaseCreatorContribution(
        string calldata id,
        uint256 additionalPayoutAmount,
        uint256 tokenAmountToSend,
        Storage storage store
    ) external {
        _checkInitiatorGas(store, true);

        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator != msg.sender) {
            _revert(SenderNotHyperlogueCreator.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        if (block.timestamp >= hyperlogue.submissionEndTime) {
            _revert(CannotIncreaseCreatorContributionAfterSubmissionEndTime.selector);
        }

        if (additionalPayoutAmount == 0) {
            _revert(ZeroAdditionalPayout.selector);
        }

        uint32 contributionFeePercentage = hyperlogue.contributionFeePercentage;
        uint256 minContributionFee = additionalPayoutAmount * uint256(contributionFeePercentage) / PERCENTAGE_BASE;
        uint256 minToTransfer = additionalPayoutAmount + minContributionFee;

        uint256 amountTransferred = SafeERC20WithTaxCheck.safeTransferFrom(
            hyperlogue.payoutToken, msg.sender, address(this), tokenAmountToSend, minToTransfer
        );

        store.amountSent[id][msg.sender] += amountTransferred;

        uint256 contributionFee = amountTransferred * uint256(contributionFeePercentage)
            / (PERCENTAGE_BASE + uint256(contributionFeePercentage));

        hyperlogue.payoutAmount += (amountTransferred - contributionFee);

        // hyperlogue.contributionFee += contributionFee;

        emit CreatorContributionIncreased(
            id, msg.sender, amountTransferred, store.amountSent[id][msg.sender], hyperlogue.payoutAmount
        );
    }

    /// @notice Join a Token Exchange Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param tokensToSend The amount of ERC20 tokens to send
    /// @param store The contract storage to mutate
    function joinHyperlogue(string calldata id, uint256 tokensToSend, Storage storage store) external {
        _checkParticipantGas(store);

        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (store.rejected[id]) {
            _revert(CannotJoinRejectedHL.selector);
        }

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator == msg.sender) {
            _revert(CreatorCannotJoinHyperlogue.selector);
        }

        if (store.participants[id].contains(msg.sender)) {
            _revert(AlreadyJoined.selector);
        }

        if (block.timestamp < hyperlogue.submissionStartTime) {
            _revert(CannotJoinBeforeSubmissionStartTime.selector);
        }

        if (hyperlogue.submissionEndTime <= block.timestamp) {
            _revert(CannotJoinAfterSubmissionEndTime.selector);
        }

        if (store.participants[id].length() >= hyperlogue.maxParticipants) {
            _revert(MaxParticipantsReachedForHyperlogue.selector);
        }

        store.participants[id].add(msg.sender);

        uint256 tokensTransferred;

        if (hyperlogue.participantFee > 0 || tokensToSend > 0) {
            uint256 minContributionFee =
                hyperlogue.participantFee * hyperlogue.contributionFeePercentage / PERCENTAGE_BASE;

            uint256 minToTransfer = hyperlogue.participantFee + minContributionFee;

            tokensTransferred = SafeERC20WithTaxCheck.safeTransferFrom(
                hyperlogue.participantToken, msg.sender, address(this), tokensToSend, minToTransfer
            );

            if (tokensTransferred > minToTransfer) {
                uint256 refundAmount = tokensTransferred - minToTransfer;
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), msg.sender, refundAmount);
                tokensTransferred = minToTransfer;
            }

            uint256 contributionFee = tokensTransferred * uint256(hyperlogue.contributionFeePercentage)
                / (PERCENTAGE_BASE + uint256(hyperlogue.contributionFeePercentage));

            store.hyperlogues[id].agencyFee += tokensTransferred - contributionFee;
            store.hyperlogues[id].contributionFee += contributionFee;

            store.amountSent[id][msg.sender] += tokensTransferred;
        }
        emit JoinedHyperlogue(id, msg.sender, tokensTransferred);
    }

    /// @notice Rejects a Token Exchange Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param store The contract storage to mutate
    function rejectHyperlogue(string calldata id, Storage storage store) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.submissionStartTime <= block.timestamp) {
            _revert(CannotRejectAfterSubmissionStartTime.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        store.rejected[id] = true;

        address creator = hyperlogue.creator;
        store.hyperlogueRefunded[id][creator] = true;
        uint256 initiatorShare = store.amountSent[id][creator];
        if (initiatorShare > 0) {
            SafeERC20.safeTransfer(IERC20(hyperlogue.payoutToken), creator, initiatorShare);
            emit RefundedHyperlogue(id, creator, initiatorShare);
        }
        emit HyperlogueRejected(id);
    }

    /// @notice Refunds participants when minimum participants not reached after submission end
    /// @dev For TokenExchange: Refunds creator's payoutToken and participants' participantToken
    /// @param id The id of the Hyperlogue
    /// @param startIndex The starting index for batch processing participants
    /// @param batchSize The number of participants to process in this batch
    /// @param attemptCreatorRefund Whether to attempt refunding the creator
    /// @param store The contract storage to mutate
    function refundHyperlogue(
        string calldata id,
        uint256 startIndex,
        uint256 batchSize,
        bool attemptCreatorRefund,
        Storage storage store
    ) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.submissionEndTime > block.timestamp) {
            _revert(CannotRefundBeforeSubmissionEndTime.selector);
        }

        uint256 participantCount = store.participants[id].length();

        if (participantCount >= hyperlogue.minimumParticipants) {
            _revert(ReachedMinimumParticipants.selector);
        }

        address creator = store.hyperlogues[id].creator;

        // Refund the creator, if not already refunded
        if (attemptCreatorRefund && !store.hyperlogueRefunded[id][creator]) {
            store.hyperlogueRefunded[id][creator] = true;
            uint256 initiatorShare = store.amountSent[id][creator];
            if (initiatorShare > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.payoutToken), creator, initiatorShare);
                emit RefundedHyperlogue(id, creator, initiatorShare);
            }
        }

        uint256 endIndex = startIndex + batchSize;
        // Ensure we don't exceed the bounds of the array
        if (endIndex > participantCount) {
            endIndex = participantCount;
        }

        for (uint256 i = startIndex; i < endIndex; i++) {
            address recipient = store.participants[id].at(i);
            uint256 amountSent = store.amountSent[id][recipient];
            if (!store.hyperlogueRefunded[id][recipient] && amountSent > 0) {
                store.hyperlogueRefunded[id][recipient] = true;
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), recipient, amountSent);
                emit RefundedHyperlogue(id, recipient, amountSent);
            }
        }
    }

    /// @notice Sets the payout root of a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param payoutRoot The payout root of the Hyperlogue
    /// @param store The contract storage to mutate
    function postPayoutRoot(string calldata id, bytes32 payoutRoot, Storage storage store) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.submissionEndTime > block.timestamp) {
            _revert(NotYetSubmissionEndTime.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        address creator = hyperlogue.creator;

        // If the max release timestmap is not yet reached, only the creator can post the root
        if (block.timestamp <= hyperlogue.maxReleaseTimeByAgent) {
            if (msg.sender != creator) {
                _revert(SenderNotHyperlogueCreator.selector);
            }
        }

        // If it is past the max agent release timestamp, the result post relayer or creator can post the root
        if (hyperlogue.maxReleaseTimeByAgent < block.timestamp) {
            if (msg.sender != store.resultPostRelayer && msg.sender != creator) {
                _revert(SenderNotIdealogi.selector);
            }
        }

        if (store.hyperloguePayoutRoots[id] != bytes32(0)) {
            _revert(RootAlreadySet.selector);
        }
        store.hyperloguePayoutRoots[id] = payoutRoot;
        emit HyperloguePayoutRootSet(id, payoutRoot);
    }

    /// @notice Claims the payout from a Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param amount The amount to claim
    /// @param proof The Merkle proof
    /// @param toAddress The address to send the payout to
    function claimFromHyperlogue(
        Storage storage store,
        string memory id,
        uint256 amount,
        bytes32[] calldata proof,
        address toAddress
    ) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (!hyperlogue.contributionFeesClaimed) {
            store.hyperlogues[id].contributionFeesClaimed = true;

            uint256 creatorContributionFee = store.amountSent[id][hyperlogue.creator] - hyperlogue.payoutAmount;

            if (creatorContributionFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.payoutToken), store.treasury, creatorContributionFee);
            }
            if (hyperlogue.contributionFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), store.treasury, hyperlogue.contributionFee);
            }
        }

        if (!hyperlogue.agencyFeesClaimed) {
            store.hyperlogues[id].agencyFeesClaimed = true;

            if (hyperlogue.agencyFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), hyperlogue.creator, hyperlogue.agencyFee);
            }
            emit ClaimedFromHyperlogue(id, hyperlogue.creator, hyperlogue.agencyFee);
        }

        bytes32 root = store.hyperloguePayoutRoots[id];
        if (root == bytes32(0)) {
            _revert(RootNotPosted.selector);
        }

        if (block.timestamp < hyperlogue.rewardClaimDate) {
            _revert(CannotClaimBeforeRewardClaimDate.selector);
        }

        address payoutAddress = toAddress != address(0) ? toAddress : msg.sender;

        if (!store.participants[id].contains(payoutAddress)) {
            _revert(NotAParticipant.selector);
        }

        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(payoutAddress, amount))));
        if (!MerkleProof.verify(proof, root, leaf)) {
            _revert(InvalidClaimProof.selector);
        }

        uint256 participantCount = store.participants[id].length();
        if (participantCount < hyperlogue.minimumParticipants) {
            _revert(NotReachedMinimumParticipants.selector);
        }
        if (store.claimedHyperlogues[payoutAddress].get(uint256(keccak256(abi.encode(id))))) {
            _revert(AlreadyClaimedFromHyperlogue.selector);
        }

        uint256 newTotalAmountClaimed = store.hyperlogueClaimedSum[id] + amount;
        if (newTotalAmountClaimed > hyperlogue.payoutAmount) {
            _revert(CannotClaimMoreThanTotalDeposit.selector);
        }

        store.hyperlogueClaimedSum[id] = newTotalAmountClaimed;
        store.claimedHyperlogues[payoutAddress].set(uint256(keccak256(abi.encode(id))));

        if (amount > 0) {
            SafeERC20.safeTransfer(IERC20(hyperlogue.payoutToken), payoutAddress, amount);
        }

        emit ClaimedFromHyperlogue(id, msg.sender, amount);
    }

    /// @notice Claims contribution fees and creator rewards from a Token Exchange Hyperlogue
    /// @param store The storage struct from HyperlogueCreator
    /// @param id The id of the Hyperlogue to claim fees from
    /// @dev For TokenExchange: Claims dual-token fees (payout tokens from creator, participant tokens from participants) for the treasury
    /// @dev Also transfers accumulated participant tokens to creator as rewards
    function claimFeesFromHyperlogue(Storage storage store, string memory id) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        bytes32 root = store.hyperloguePayoutRoots[id];
        if (root == bytes32(0)) {
            _revert(RootNotPosted.selector);
        }

        uint256 participantCount = store.participants[id].length();
        if (participantCount < hyperlogue.minimumParticipants) {
            _revert(NotReachedMinimumParticipants.selector);
        }

        if (hyperlogue.contributionFeesClaimed && hyperlogue.agencyFeesClaimed) {
            _revert(FeesAlreadyClaimed.selector);
        }

        if (!hyperlogue.contributionFeesClaimed) {
            store.hyperlogues[id].contributionFeesClaimed = true;

            uint256 creatorContributionFee = store.amountSent[id][hyperlogue.creator] - hyperlogue.payoutAmount;

            if (creatorContributionFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.payoutToken), store.treasury, creatorContributionFee);
            }

            if (hyperlogue.contributionFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), store.treasury, hyperlogue.contributionFee);
            }
        }

        // Transfer accumulated participant tokens to creator as rewards
        if (!hyperlogue.agencyFeesClaimed) {
            store.hyperlogues[id].agencyFeesClaimed = true;

            if (hyperlogue.agencyFee > 0) {
                SafeERC20.safeTransfer(IERC20(hyperlogue.participantToken), hyperlogue.creator, hyperlogue.agencyFee);
            }
            emit ClaimedFromHyperlogue(id, hyperlogue.creator, hyperlogue.agencyFee);
        }
    }

    //-----------------------------------------------------------------------------------
    // Internal functions
    //-----------------------------------------------------------------------------------

    /**
     * @notice More efficiently reverts with a bytes4 selector
     * @param selector The selector to revert with
     */
    function _revert(bytes4 selector) internal pure {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(0x0, selector)
            revert(0x0, 0x04)
        }
    }

    function _checkInitiatorGas(Storage storage store, bool trueIfPeriphery) internal view {
        if (trueIfPeriphery) {
            if (msg.value < store.tokenExchangeHyperlogueConfig.initiatorPeripheryPlatformFee) {
                _revert(InsufficientGasSubsidy.selector);
            }
        } else {
            if (msg.value < store.tokenExchangeHyperlogueConfig.initiatorPlatformFee) {
                _revert(InsufficientGasSubsidy.selector);
            }
        }
    }

    function _checkParticipantGas(Storage storage store) internal view {
        if (msg.value < store.tokenExchangeHyperlogueConfig.participantPlatformFee) {
            _revert(InsufficientGasSubsidy.selector);
        }
    }
}

src/libraries/UnfundedHyperlogue.sol

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

import "../structs/Structs.sol";
import "../errors/Errors.sol";
import "../events/Events.sol";

/// @dev library to process Unfunded Hyperlogues

library UnfundedHyperlogue {
    using EnumerableSet for EnumerableSet.AddressSet;

    //-----------------------------------------------------------------------------------
    // External functions
    //-----------------------------------------------------------------------------------

    /// @notice Creates an unfunded Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param hyperlogue The Hyperlogue struct
    /// @param store The contract storage to mutate
    function createHyperlogue(string calldata id, Hyperlogue memory hyperlogue, Storage storage store) external {
        _checkGas(false, 0, hyperlogue.maxParticipants, store);

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueCannotHaveZeroCreator.selector);
        }

        if (
            hyperlogue.submissionStartTime
                < block.timestamp + store.unfundedHyperlogueConfig.minOffsetForSubmissionStart
        ) {
            _revert(StartTimeCannotBeInPast.selector);
        }

        if (hyperlogue.submissionEndTime < hyperlogue.submissionStartTime) {
            _revert(EndTimeCannotBeBeforeStartTime.selector);
        }

        if (store.hyperlogues[id].creator != address(0)) {
            _revert(HyperlogueAlreadyExists.selector);
        }

        /// @custom:auditor - This is important for the refund function
        if (hyperlogue.minimumParticipants == 0) {
            _revert(MinParticipantsCannotBeZero.selector);
        }

        // 0. If not specified, the max release timestamp by the agent is the submission end time + 1 day (default)
        // 1. If specified, the max release timestamp by the agent cannot be before the submission end time
        // 2. If specified, also cannot be greater than the max post results grace offset (1 week)
        if (hyperlogue.maxReleaseTimeByAgent == 0) {
            hyperlogue.maxReleaseTimeByAgent =
                hyperlogue.submissionEndTime + store.unfundedHyperlogueConfig.DEFAULT_POST_RESULTS_GRACE_OFFSET;
        } else if (hyperlogue.maxReleaseTimeByAgent < hyperlogue.submissionEndTime) {
            _revert(ReleaseTimeCannotBeforeEndTime.selector);
        }

        if (
            hyperlogue.maxReleaseTimeByAgent
                > hyperlogue.submissionEndTime + store.unfundedHyperlogueConfig.MAX_POST_RESULTS_GRACE_OFFSET
        ) {
            _revert(ReleaseTimeCannotAfterMaxOffsetAfterSubmissionEndTime.selector);
        }

        if (hyperlogue.participantFee != 0 || hyperlogue.payoutAmount != 0) {
            _revert(IncorrectHyperlogueType.selector);
        }

        if (hyperlogue.maxParticipants == 0) {
            hyperlogue.maxParticipants = store.unfundedHyperlogueConfig.freeParticipantCount; // Default behaviour
        }

        if (hyperlogue.maxParticipants < store.unfundedHyperlogueConfig.minimumMaxParticipants) {
            _revert(MaxParticipantsBelowMinimumThreshold.selector);
        }

        if (hyperlogue.minimumParticipants > hyperlogue.maxParticipants) {
            _revert(MinimumParticipantsExceedsMaxParticipants.selector);
        }

        store.hyperlogues[id] = hyperlogue;
        emit HyperlogueCreated(id, hyperlogue);
    }

    /// @notice Increases max participants for an unfunded hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param newMaxParticipants The new max participants
    /// @param store The contract storage to mutate
    function increaseMaxParticipants(string calldata id, uint32 newMaxParticipants, Storage storage store) external {
        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator != msg.sender) {
            _revert(SenderNotHyperlogueCreator.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        if (block.timestamp >= hyperlogue.submissionEndTime) {
            _revert(CannotIncreaseMaxParticipantsAfterSubmissionEndTime.selector);
        }

        uint32 oldMax = hyperlogue.maxParticipants;

        if (newMaxParticipants <= hyperlogue.maxParticipants) {
            _revert(NewMaxParticipantsMustBeGreaterThanCurrent.selector);
        }

        uint32 additionalParticipants = newMaxParticipants - oldMax;

        _checkGas(true, oldMax, additionalParticipants, store);

        hyperlogue.maxParticipants = newMaxParticipants;

        emit MaxParticipantsIncreased(id, oldMax, newMaxParticipants);
    }

    /// @notice Join an unfunded Hyperlogue
    /// @param id The id of the Hyperlogue
    /// @param store The contract storage to mutate
    function joinHyperlogue(string calldata id, Storage storage store) external {
        if (msg.value > 0) {
            _revert(UnexpectedETHSent.selector);
        }

        Hyperlogue storage hyperlogue = store.hyperlogues[id];

        if (store.rejected[id]) {
            _revert(CannotJoinRejectedHL.selector);
        }

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.creator == msg.sender) {
            _revert(CreatorCannotJoinHyperlogue.selector);
        }

        if (block.timestamp < hyperlogue.submissionStartTime) {
            _revert(CannotJoinBeforeSubmissionStartTime.selector);
        }

        if (store.participants[id].contains(msg.sender)) {
            _revert(AlreadyJoined.selector);
        }

        if (hyperlogue.submissionEndTime < block.timestamp) {
            _revert(CannotJoinAfterSubmissionEndTime.selector);
        }

        if (store.participants[id].length() >= hyperlogue.maxParticipants) {
            _revert(MaxParticipantsReachedForHyperlogue.selector);
        }

        store.participants[id].add(msg.sender);

        emit JoinedHyperlogue(id, msg.sender, 0);
    }

    function rejectHyperlogue(string calldata id, Storage storage store) external {
        Hyperlogue memory hyperlogue = store.hyperlogues[id];

        if (hyperlogue.creator == address(0)) {
            _revert(HyperlogueNotExists.selector);
        }

        if (hyperlogue.submissionStartTime <= block.timestamp) {
            _revert(CannotRejectAfterSubmissionStartTime.selector);
        }

        if (store.rejected[id]) {
            _revert(HLAlreadyRejected.selector);
        }

        store.rejected[id] = true;

        emit HyperlogueRejected(id);
    }

    //-----------------------------------------------------------------------------------
    // Internal functions
    //-----------------------------------------------------------------------------------

    /**
     * @notice More efficiently reverts with a bytes4 selector
     * @param selector The selector to revert with
     */
    function _revert(bytes4 selector) internal pure {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(0x0, selector)
            revert(0x0, 0x04)
        }
    }

    function _checkGas(
        bool trueIfPeriphery,
        uint32 currentMaxParticipants,
        uint32 additionalParticipants,
        Storage storage store
    ) internal view {
        uint256 requiredAdditionalPayment = _calculateAdditionalPaymentForIncreasingMaxParticipants(
            currentMaxParticipants, additionalParticipants, store
        );

        if (trueIfPeriphery) {
            if (msg.value < store.unfundedHyperlogueConfig.initiatorPeripheryPlatformFee + requiredAdditionalPayment) {
                _revert(InsufficientGasSubsidy.selector);
            }
        } else {
            if (msg.value < store.unfundedHyperlogueConfig.initiatorPlatformFee + requiredAdditionalPayment) {
                _revert(InsufficientGasSubsidy.selector);
            }
        }
    }

    /// @notice Calculates ETH payment required for additional unfunded hyperlogue participant slots
    /// @dev Only charges for slots beyond free tier. Formula: (newPaidSlots - currentPaidSlots) × perParticipantFee
    /// @dev Example: Current 10, Add 10, Free 12 → Pay for 8 slots (20 total - 12 free = 8 paid, minus 0 current paid)
    /// @param currentMaxParticipants Current maximum participants (0 when creating new hyperlogue)
    /// @param additionalParticipants Number of participants to add
    /// @param store Contract storage containing free slots config and per-participant fee
    /// @return requiredPayment ETH amount required (0 if all slots are within free tier)
    function _calculateAdditionalPaymentForIncreasingMaxParticipants(
        uint32 currentMaxParticipants,
        uint32 additionalParticipants,
        Storage storage store
    ) internal view returns (uint256 requiredPayment) {
        uint32 freeSlots = store.unfundedHyperlogueConfig.freeParticipantCount;

        uint32 currentPaidSlots = currentMaxParticipants > freeSlots ? currentMaxParticipants - freeSlots : 0;

        uint32 newMaxParticipants = currentMaxParticipants + additionalParticipants;

        uint32 newPaidSlots = newMaxParticipants > freeSlots ? newMaxParticipants - freeSlots : 0;

        requiredPayment = (newPaidSlots - currentPaidSlots) * store.unfundedHyperlogueConfig.perExtraParticipantFee;
    }
}

src/structs/Structs.sol

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

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";

uint256 constant PERCENTAGE_BASE = 10_000;

struct Hyperlogue {
    HyperlogueType hyperlogueType;
    address creator;
    address payoutToken;
    /// @dev In case of funded hyperlogues, this is the total amount of tokens to be claimed as rewards by the participants
    /// @dev In case of token exchange hyperlogues, this is the total creator contribution to be distributed to the participants in the payout token
    uint256 payoutAmount;
    /// @dev In case of funded hyperlogues, this is the total amount of agency fee to be claimed by the creator
    /// @dev In case of token exchange hyperlogues, this is the total amount raised by the participants in the participant token to be claimed by the creator
    uint256 agencyFee;
    uint256 contributionFee;
    uint48 submissionStartTime;
    uint48 submissionEndTime;
    uint48 maxReleaseTimeByAgent;
    uint256 participantFee;
    uint32 minimumParticipants;
    uint32 agencyFeePercentage;
    uint32 contributionFeePercentage;
    bool contributionFeesClaimed;
    bool agencyFeesClaimed;
    uint32 maxParticipants;
    // Token Exchange specific fields
    address participantToken;
    uint48 rewardClaimDate;
}

struct Storage {
    mapping(string id => Hyperlogue) hyperlogues;
    mapping(string id => bytes32 hyperloguePayoutRoot) hyperloguePayoutRoots;
    mapping(string id => uint256) hyperlogueClaimedSum;
    mapping(string id => mapping(address => bool)) hyperlogueRefunded;
    mapping(string id => EnumerableSet.AddressSet) participants;
    mapping(string => mapping(address => uint256)) amountSent;
    mapping(string id => bool) rejected;
    mapping(address user => BitMaps.BitMap) claimedHyperlogues;
    address signer;
    address resultPostRelayer;
    address treasury;
    FundedHyperlogueConfig fundedHyperlogueConfig;
    UnfundedHyperlogueConfig unfundedHyperlogueConfig;
    TokenExchangeHyperlogueConfig tokenExchangeHyperlogueConfig;
    /// @dev Native ETH owed to users of funded hyperlogues. claimEth never sends this amount.
    /// Append new fields after this one; inserting or reordering fields above it corrupts upgraded storage.
    uint256 ethHeldForHyperlogues;
}

enum HyperlogueType {
    Funded,
    Unfunded,
    TokenExchange
}

struct InitializeConfig {
    address owner;
    address signer;
    address upgrader;
    uint32 contributionFeePercentage;
    uint32 minOffsetStartForSubmission;
    uint96 initiatorPlatformFee;
    uint96 participantPlatformFee;
    uint96 initiatorPeripheryPlatformFee;
    uint96 perParticipantFeeForUnfundedHyperlogues;
}

struct FundedHyperlogueConfig {
    uint32 contributionFeePercentage;
    uint32 minOffsetForSubmissionStart;
    uint96 initiatorPlatformFee;
    // Platform fee for initiator periphery functions outside of create (increase contribution and max participants)
    uint96 initiatorPeripheryPlatformFee;
    uint96 participantPlatformFee;
    uint256 MAX_CONTRIBUTION_FEE_PERCENTAGE;
    uint256 AGENCY_FEE_PERCENTAGE_THRESHOLD;
    uint48 DEFAULT_POST_RESULTS_GRACE_OFFSET;
    uint48 MAX_POST_RESULTS_GRACE_OFFSET;
    uint32 minimumMaxParticipants;
}

struct UnfundedHyperlogueConfig {
    uint32 minOffsetForSubmissionStart;
    uint96 initiatorPlatformFee;
    uint96 initiatorPeripheryPlatformFee;
    uint48 DEFAULT_POST_RESULTS_GRACE_OFFSET;
    uint48 MAX_POST_RESULTS_GRACE_OFFSET;
    uint32 freeParticipantCount;
    uint96 perExtraParticipantFee;
    uint32 minimumMaxParticipants;
}

struct TokenExchangeHyperlogueConfig {
    uint32 contributionFeePercentage;
    uint32 minOffsetForSubmissionStart;
    uint96 initiatorPlatformFee;
    uint96 initiatorPeripheryPlatformFee;
    uint96 participantPlatformFee;
    uint256 MAX_CONTRIBUTION_FEE_PERCENTAGE;
    uint48 DEFAULT_POST_RESULTS_GRACE_OFFSET;
    uint48 MAX_POST_RESULTS_GRACE_OFFSET;
    uint48 MAX_REWARD_CLAIM_OFFSET;
    uint32 minimumMaxParticipants;
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/libraries/FundedHyperlogue.sol": {
      "FundedHyperlogue": "0x44dEF70c250D8e785028Ed6390dF717982327e76"
    },
    "src/libraries/UnfundedHyperlogue.sol": {
      "UnfundedHyperlogue": "0xa74490aC748913a38dE490C35131122A1475f9f8"
    },
    "src/libraries/TokenExchangeHyperlogue.sol": {
      "TokenExchangeHyperlogue": "0x4f9950410ea16414d1fa0EC94B58f6E3465dC147"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/:ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/:ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.