Abstract Testnet

Contract Diff Checker

Contract Name:
QuizManager

Contract Source Code:

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

import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";

contract QuizManager is 
    Initializable,
    AccessControlUpgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable 
{
    bytes32 public constant QUIZ_MANAGER_ROLE = keccak256("QUIZ_MANAGER_ROLE");

    // -----------------------
    // GLOBAL (DEFAULT) FIELDS
    // -----------------------
    IERC20 public rewardToken;        // Default reward token
    bool public isRewardTokenSet;     // Whether the default rewardToken is set
    uint256 public prizePool;         // Global prize pool (mutable)
    uint256 public defaultPrizePool;  // Baseline to reset after each default payout

    // -----------------------
    // PER-QUIZ STRUCT
    // -----------------------
    struct Question {
        string content;             
        string correctAnswer;       
        address[] participants;     
        address[] correctPlayers;   
        address[] optedOutPlayers;  
    }

    struct Quiz {
        // Core Quiz Info
        string id;                
        uint256 createdTime;      
        uint256 completedTime;    

        // Quiz-Specific Token & Pool
        // If quizRewardToken != address(0), we MUST use this token & quizPrizePool
        // If quizRewardToken == address(0), we use the default token & global prizePool
        address quizRewardToken;  
        uint256 quizPrizePool;    

        // Quiz Data
        address[] enrolledPlayers;
        Question[] questions;     
        address[] finalWinners;
        bool isCompleted;
        bool rewardsPaid;
    }

    // -----------------------
    // STORAGE
    // -----------------------
    mapping(string => Quiz) public quizzes;
    string[] public quizIds;

    // -----------------------
    // EVENTS
    // -----------------------
    event QuizCreated(string quizId, uint256 timestamp);
    event QuizCompleted(string quizId, uint256 timestamp, address[] winners);
    event RewardDeposited(address indexed sender, uint256 amount, string quizId); 
    event RewardsPaid(string quizId, uint256 totalPaid, address[] winners);
    event PrizePoolUpdated(uint256 oldPrizePool, uint256 newPrizePool);
    event RewardTokenSet(address indexed tokenAddress);
    event EnrolledPlayersUpdated(string quizId, address[] newPlayers);
    event QuizPrizePoolUpdated(string quizId, uint256 oldPool, uint256 newPool);

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

    function initialize(uint256 _defaultPrizePool) public initializer {
        __AccessControl_init();
        __Pausable_init();
        __ReentrancyGuard_init();

        // Grant the deployer the default admin role & quiz manager role
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(QUIZ_MANAGER_ROLE, msg.sender);

        // Initialize
        defaultPrizePool = _defaultPrizePool;
        prizePool = _defaultPrizePool; // Active global prize pool
    }

    // -----------------------
    // ADMIN FUNCTIONS
    // -----------------------
    function setRewardToken(address tokenAddress) 
        external 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        require(tokenAddress != address(0), "Invalid token address");
        require(!isRewardTokenSet, "Reward token already set");

        rewardToken = IERC20(tokenAddress);
        isRewardTokenSet = true;
        emit RewardTokenSet(tokenAddress);
    }

    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
    }

    // -----------------------
    // QUIZ MANAGER FUNCTIONS
    // -----------------------

    /**
     * @notice Create a new quiz.  
     * @param quizId  Unique string ID for the quiz.
     * @param enrolledPlayers  (Optional) list of players.
     * @param quizRewardToken  If nonzero, the token for this quiz’s prize pool.
     * @param customPrizePool    If nonzero, the prize pool for this quiz’s token.
     *
     * If you set `quizRewardToken != address(0)`, then `quizPrizePool` must be > 0.  
     * If `quizRewardToken == address(0)`, then `quizPrizePool` must be == 0.  
     */
    function createQuiz(
        string calldata quizId,
        address[] calldata enrolledPlayers,
        address quizRewardToken,
        uint256 customPrizePool
    )
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        require(bytes(quizId).length > 0, "Quiz ID cannot be empty");
        require(quizzes[quizId].createdTime == 0, "Quiz ID already exists");

        // --- NEW LOGIC: close all existing quizzes that are still active.
        for (uint256 i = 0; i < quizIds.length; i++) {
            Quiz storage activeQuiz = quizzes[quizIds[i]];
            if (!activeQuiz.isCompleted) {
                // Mark it as completed
                activeQuiz.isCompleted = true;
                activeQuiz.completedTime = block.timestamp;

                // Optionally emit an event about forced closure
                // emit QuizCompleted(quizIds[i], block.timestamp, activeQuiz.finalWinners);
            }
        }

        // --- Continue existing logic for creation
        bool usingCustomToken = (quizRewardToken != address(0));
        if (usingCustomToken) {
            require(customPrizePool > 0, "Must set customPrizePool > 0 if token is specified");
        } else {
            require(customPrizePool == 0, "customPrizePool must be 0 if no custom token");
        }

        // Determine initialPrizePool
        uint256 initialPrizePool = usingCustomToken ? customPrizePool : defaultPrizePool;

        if (!usingCustomToken && quizIds.length > 0) {
            // If there's a previous quiz that is using the default token but had no winners,
            // add its leftover prizePool
            Quiz storage prevQuiz = quizzes[quizIds[quizIds.length - 1]];
            if (prevQuiz.isCompleted && 
                prevQuiz.rewardsPaid && 
                prevQuiz.finalWinners.length == 0 &&
                prevQuiz.quizRewardToken == address(0)
            ) {
                initialPrizePool += prevQuiz.quizPrizePool;
            }
        }

        // Create the new quiz
        Quiz storage newQuiz = quizzes[quizId];
        newQuiz.id = quizId;
        newQuiz.createdTime = block.timestamp;
        newQuiz.completedTime = 0;
        newQuiz.quizRewardToken = quizRewardToken;
        newQuiz.quizPrizePool = initialPrizePool;
        newQuiz.enrolledPlayers = enrolledPlayers;
        newQuiz.isCompleted = false;
        newQuiz.rewardsPaid = false;

        quizIds.push(quizId);

        emit QuizCreated(quizId, block.timestamp);
    }

    /**
     * @notice Update the list of enrolled players for a specific quiz.
     * @param quizId The unique ID of the quiz to update.
     * @param newPlayers The new list of player addresses to enroll.
     */
    function updateEnrolledPlayers(
        string calldata quizId,
        address[] calldata newPlayers
    )
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");

        // Update the enrolled players list
        quiz.enrolledPlayers = newPlayers;

        // Optionally, you can emit an event here to log the update.
        // Example:
        emit EnrolledPlayersUpdated(quizId, newPlayers);
    }


    /**
     * @notice Completes the quiz, storing final data:
     *          - finalWinners
     *          - questions (content + correct answers, etc.)
     *          - completion time
     */
    function completeQuiz(
        string calldata quizId,
        address[] calldata finalWinners,
        // Arrays of question data
        string[] calldata questionContents,
        string[] calldata correctAnswers,
        address[][] calldata questionParticipants,
        address[][] calldata questionCorrectPlayers,
        address[][] calldata questionOptedOutPlayers
    ) 
        external 
        onlyRole(QUIZ_MANAGER_ROLE) 
        whenNotPaused 
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        require(!quiz.isCompleted, "Quiz already completed");
        
        // All arrays for questions must be the same length
        uint256 questionCount = questionContents.length;
        require(questionCount == correctAnswers.length, "Mismatched Q/A arrays");
        require(questionCount == questionParticipants.length, "Mismatched participants array");
        require(questionCount == questionCorrectPlayers.length, "Mismatched correctPlayers array");
        require(questionCount == questionOptedOutPlayers.length, "Mismatched optedOutPlayers array");

        // Mark quiz completed
        quiz.isCompleted = true;
        quiz.completedTime = block.timestamp;
        quiz.finalWinners = finalWinners;

        // Populate questions
        for (uint256 i = 0; i < questionCount; i++) {
            quiz.questions.push(
                Question({
                    content: questionContents[i],
                    correctAnswer: correctAnswers[i],
                    participants: questionParticipants[i],
                    correctPlayers: questionCorrectPlayers[i],
                    optedOutPlayers: questionOptedOutPlayers[i]
                })
            );
        }

        emit QuizCompleted(quizId, block.timestamp, finalWinners);
    }

    /**
     * @notice Deposit into the GLOBAL prize pool (when using the default token).
     *         If you want to deposit into a quiz-specific pool, use `depositQuizPrizePool`.
     */
    function ownerDeposit(uint256 amount) 
        external 
        onlyRole(QUIZ_MANAGER_ROLE) 
        whenNotPaused 
    {
        require(isRewardTokenSet, "Reward token not set (global)");
        require(amount > 0, "Deposit must be > 0");

        bool success = rewardToken.transferFrom(msg.sender, address(this), amount);
        require(success, "Token transfer failed");

        emit RewardDeposited(msg.sender, amount, "GLOBAL");
    }

    /**
     * @notice Deposit specifically into a quiz’s custom prize pool (if that quiz uses a custom token).
     */
    function depositQuizPrizePool(string calldata quizId, uint256 amount)
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");

        // Ensure this quiz actually uses a custom token
        require(quiz.quizRewardToken != address(0), "Quiz uses global token/pool, cannot deposit here");
        require(amount > 0, "Deposit must be > 0");

        // Transfer that quiz’s token from sender to this contract
        IERC20 customToken = IERC20(quiz.quizRewardToken);
        bool success = customToken.transferFrom(msg.sender, address(this), amount);
        require(success, "Quiz-specific token transfer failed");

        emit RewardDeposited(msg.sender, amount, quizId);
    }

    /**
     * @notice Pays out the quiz winners. 
     *         - If the quiz has a custom token, use quiz.quizRewardToken & quiz.quizPrizePool.
     *         - Otherwise, use the global token & global prizePool.
     *
     * If there are no winners, we do NOT reset or distribute the prize pool, 
     * effectively carrying it over to the next quiz. 
     *
     * After payout (if there *are* winners):
     *    - For global, set `prizePool = defaultPrizePool`.
     *    - For quiz-specific, set `quizPrizePool = 0`.
     */
    function payoutWinners(string calldata quizId) 
        external 
        onlyRole(QUIZ_MANAGER_ROLE) 
        whenNotPaused 
        nonReentrant 
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        require(quiz.isCompleted, "Quiz not completed yet");
        require(!quiz.rewardsPaid, "Rewards already paid");
        require(quiz.quizPrizePool > 0, "Prize pool is empty");

        address[] memory winners = quiz.finalWinners;
        uint256 winnerCount = winners.length;

        // Get the appropriate token
        IERC20 tokenToUse = quiz.quizRewardToken != address(0) 
            ? IERC20(quiz.quizRewardToken) 
            : rewardToken;

        if (quiz.quizRewardToken == address(0)) {
            require(isRewardTokenSet, "No default token set");
        }

        // Mark rewards as paid
        quiz.rewardsPaid = true;

        // If no winners, keep the prize pool and exit
        if (winnerCount == 0) {
            emit RewardsPaid(quizId, 0, new address[](0));
            return;
        }

        uint256 prizePerWinner = quiz.quizPrizePool / winnerCount;
        require(quiz.quizPrizePool >= prizePerWinner * winnerCount, "Prize calculation overflow");

        // Transfer tokens to each winner
        for (uint256 i = 0; i < winnerCount; i++) {
            require(tokenToUse.transfer(winners[i], prizePerWinner), "Token transfer failed");
        }

        // Reset this quiz's prize pool after successful payout
        uint256 paidPool = quiz.quizPrizePool;
        quiz.quizPrizePool = 0;
        
        emit RewardsPaid(quizId, paidPool, winners);
    }

    /**
     * @notice Update the default prize pool baseline (only affects global usage).
     */
    function updateDefaultPrizePool(uint256 newAmount)
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        require(newAmount > 0, "Prize pool must be > 0");
        emit PrizePoolUpdated(defaultPrizePool, newAmount);
        defaultPrizePool = newAmount;
    }

    /**
     * @notice Manually sets (overwrites) the prize pool for a specific quiz.
     * @param quizId The unique ID of the quiz to update.
     * @param newPoolAmount The new prize pool amount to set.
     */
    function setQuizPrizePool(string calldata quizId, uint256 newPoolAmount)
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        require(!quiz.isCompleted, "Cannot modify prize pool after completion");

        uint256 oldPool = quiz.quizPrizePool;
        quiz.quizPrizePool = newPoolAmount;

        emit QuizPrizePoolUpdated(quizId, oldPool, newPoolAmount);
    }

    /***********************************************
     * @notice Force-completes a quiz, for admin use only.
     *         This will simply set isCompleted = true and
     *         completedTime = block.timestamp.
     *         It does NOT set finalWinners or add questions.
     ***********************************************/
    function forceCompleteQuiz(string calldata quizId)
        external
        onlyRole(QUIZ_MANAGER_ROLE)
        whenNotPaused
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        require(!quiz.isCompleted, "Quiz already completed");

        // Mark quiz completed
        quiz.isCompleted = true;
        quiz.completedTime = block.timestamp;

        // Optionally emit an event (reuse QuizCompleted or a new event)
        emit QuizCompleted(quizId, block.timestamp, quiz.finalWinners);
    }


    // -----------------------
    // VIEW FUNCTIONS
    // -----------------------
    function getQuiz(string calldata quizId)
        external
        view
        returns (Quiz memory quiz)
    {
        quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
    }

    function getAllQuizIds() external view returns (string[] memory) {
        return quizIds;
    }

    function getFinalWinners(string calldata quizId)
        external
        view
        returns (address[] memory)
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        return quiz.finalWinners;
    }

    function getQuizPrizePool(string calldata quizId) 
        external 
        view 
        returns (uint256) 
    {
        Quiz storage quiz = quizzes[quizId];
        require(quiz.createdTime > 0, "Quiz does not exist");
        return quiz.quizPrizePool;
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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;
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}

// 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
        }
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.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;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-165 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;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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;
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

Context size (optional):