Blockchain / Global / Address

Contract

0x1ab8bf284d78BeA863C582Be6D1A15Af36775Cce

Balance
0 SOMI
Transactions sent
1
Type
Contract · 18,845 bytes of code

OnChainDataStorage Verified

Compiler
solc 0.8.20+commit.a1b79de6
Language
Solidity
Optimization
Yes, 100 runs
EVM version
paris
License
—
Verified
2026-10-12

contracts/CoreFunctions.sol

and 20 more files

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

import "./DataTypes.sol";
import "./CoreLib.sol";
import "./EntityLib.sol";
import "./SessionLib.sol";
import "./MatchSessionLib.sol";
import "./MatchLibPlayer.sol";
import "./RecordLib.sol";
import "./LibErrors.sol";

/**
 * @title OnChainDataStorage
 * @dev Main contract for storing and managing game-related data on-chain.
 * Handles players, sessions, matches, and application data with role-based access control.
 */
contract OnChainDataStorage is AccessControlDefaultAdminRules, Pausable {
    using EntityLib for DataTypes.Player[];
    using EntityLib for DataTypes.Application;
    using EntityLib for DataTypes.ApplicationRecord[];
    using SessionLib for DataTypes.LoginSession[];
    using MatchLibSession for DataTypes.MatchSession[];
    using MatchLibPlayer for DataTypes.PlayData[];
    using RecordLib for DataTypes.Records[];

    /* -------------------------------- ROLES -------------------------------- */
    /// @notice Role identifier for moderators who can manage players and sessions
    bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE");

    /* ------------------------------- STORAGE ------------------------------- */
    // players
    /// @notice Array of all registered players
    DataTypes.Player[] private players;
    /// @notice Mapping from player address to player index (1-based)
    mapping(address => uint256) private playersByAddress; // addr → idx+1
    /// @notice Mapping from player unique ID to player index
    mapping(string => uint256) private playerByUniqueId;

    // login sessions
    /// @notice Array of all login sessions
    DataTypes.LoginSession[] private loginSessions;
    /// @notice Mapping from player index to active login session index
    mapping(uint256 => uint256) private activeLoginSessionByPlayer;
    /// @notice Array of player indices with active sessions
    uint256[] private playersWithActiveSessions;
    /// @notice Array of active login session indices
    uint256[] private activeLoginSessions;

    // application
    /// @notice Application information
    DataTypes.Application public application;
    /// @notice Array of application records/versions
    DataTypes.ApplicationRecord[] private applicationRecords;

    // match sessions / play‑data
    /// @notice Array of all match sessions
    DataTypes.MatchSession[] private matchSessions;
    /// @notice Array of active match session indices
    uint256[] private activeMatchSessions;

    /// @notice Array of all play data records
    DataTypes.PlayData[] private playDatas;

    // records
    /// @notice Array of all player records
    DataTypes.Records[] private records;
    /// @notice Mapping from unique record ID to record index
    mapping(uint256 => uint256) private recordsByUniqueId;
    /// @notice Mapping from player index to all their record IDs
    mapping(uint256 => uint256[]) private recordsByPlayer;

    /// @notice Array of banned player indices
    uint256[] private banned;
    /// @notice Mapping from player index to ban index
    mapping(uint256 => uint256) private bannedByPlayer;

    /* ------------------------------ EVENTS ----------------------------- */
    /// @notice Emitted when a player is banned
    /// @param playerId The index of the banned player
    /// @param startTime The timestamp when the ban started
    event UserBanned(uint256 indexed playerId, uint256 startTime);

    /// @notice Emitted when a player is unbanned
    /// @param playerId The index of the unbanned player
    /// @param timestamp The timestamp when the player was unbanned
    event UserUnbanned(uint256 indexed playerId, uint256 timestamp);

    /// @notice Emitted when a new player is created
    /// @param playerIndex The index of the created player
    /// @param playerAddress The address of the player
    /// @param playerID The unique ID of the player
    /// @param playerType The type of player (Human, Bot, etc.)
    event PlayerCreated(
        uint256 indexed playerIndex,
        address indexed playerAddress,
        string playerID,
        DataTypes.PlayerType playerType
    );

    /// @notice Emitted when an identifier is added to a player
    /// @param playerIndex The index of the player
    /// @param identifierType The type of identifier
    /// @param identifierValue The value of the identifier
    event PlayerIdentifierAdded(
        uint256 indexed playerIndex,
        string identifierType,
        string identifierValue
    );

    /// @notice Emitted when a player's score is updated
    /// @param playerIndex The index of the player
    /// @param newScore The new score of the player
    event PlayerScoreUpdated(uint256 indexed playerIndex, int256 newScore);

    /// @notice Emitted when a verified address is added to a player
    /// @param playerIndex The index of the player
    /// @param verifiedAddress The verified address
    event PlayerVerifiedAddressAdded(
        uint256 indexed playerIndex,
        address indexed verifiedAddress
    );

    /* ─ login events ─ */
    /// @notice Emitted when a login session is created
    /// @param sessionId The ID of the created session
    /// @param playerIndex The index of the player
    /// @param startTime The start time of the session
    /// @param device The device used for the session
    /// @param applicationId The ID of the application
    event LoginSessionCreated(
        uint256 indexed sessionId,
        uint256 indexed playerIndex,
        uint256 indexed startTime,
        DataTypes.Device device,
        uint256 applicationId
    );

    /// @notice Emitted when a login session ends
    /// @param sessionId The ID of the ended session
    /// @param endTime The end time of the session
    event LoginSessionEnded(uint256 indexed sessionId, uint256 indexed endTime);

    /// @notice Emitted when metadata is added to a login session
    /// @param sessionId The ID of the session
    /// @param key The metadata key
    /// @param value The metadata value
    event LoginSessionMetadataAdded(
        uint256 indexed sessionId,
        string key,
        string value
    );

    /* ─ match / play‑data events ─ */
    /// @notice Emitted when a match session starts
    /// @param matchSessionId The ID of the match session
    /// @param applicationId The ID of the application
    /// @param startTime The start time of the match
    /// @param multiplayer Whether the match is multiplayer
    /// @param playerIndices The indices of the players in the match
    /// @param level The level/map of the match
    event MatchSessionStarted(
        uint256 indexed matchSessionId,
        uint256 applicationId,
        uint256 indexed startTime,
        bool multiplayer,
        uint256[] playerIndices,
        string level
    );

    /// @notice Emitted when a match session ends
    /// @param matchSessionId The ID of the match session
    /// @param endTime The end time of the match
    event MatchSessionEnded(
        uint256 indexed matchSessionId,
        uint256 indexed endTime
    );

    /// @notice Emitted when a player is added to a match session
    /// @param matchSessionId The ID of the match session
    /// @param playerIndex The index of the player
    /// @param playerDataId The ID of the player's data
    event PlayerAddedToMatchSession(
        uint256 indexed matchSessionId,
        uint256 indexed playerIndex,
        uint256 playerDataId
    );

    /// @notice Emitted when player data is updated
    /// @param playerIndex The index of the player
    /// @param playDataId The ID of the play data
    /// @param endTime The end time of the play data
    /// @param score The player's score
    /// @param winLoss The win/loss status
    /// @param matchPosition The player's position in the match
    event PlayerDataUpdated(
        uint256 indexed playerIndex,
        uint256 indexed playDataId,
        uint256 endTime,
        int256 score,
        DataTypes.WinLoss winLoss,
        int256 matchPosition
    );

    /* ─ application events ─ */
    /// @notice Emitted when the application is set
    /// @param name The name of the application
    /// @param owner The owner of the application
    event ApplicationSet(string name, address indexed owner);

    /// @notice Emitted when an application record is created
    /// @param recordId The ID of the record
    /// @param applicationVersion The version of the application
    /// @param companyName The name of the company
    /// @param contractAddresses The addresses of the contracts
    event ApplicationRecordCreated(
        uint256 indexed recordId,
        string applicationVersion,
        string companyName,
        address[] contractAddresses
    );

    /// @notice Emitted when application record addresses are updated
    /// @param recordId The ID of the record
    /// @param contractAddresses The updated contract addresses
    event ApplicationRecordAddressesUpdated(
        uint256 indexed recordId,
        address[] contractAddresses
    );

    /// @notice Emitted when metadata is added to an application record
    /// @param recordId The ID of the record
    /// @param key The metadata key
    /// @param value The metadata value
    event ApplicationRecordMetadataAdded(
        uint256 indexed recordId,
        string key,
        string value
    );

    /* ─ misc ─ */
    /// @notice Emitted when metadata is added to a match session
    /// @param matchSessionId The ID of the match session
    /// @param key The metadata key
    /// @param value The metadata value
    event MatchSessionMetadataAdded(
        uint256 indexed matchSessionId,
        string key,
        string value
    );

    /// @notice Emitted when a record is set
    /// @param recordId The ID of the record
    /// @param playerIndex The ID of the player
    /// @param playDataId The ID of the play data
    /// @param score The score for the record
    /// @param key The record key
    /// @param value The record value
    /// @param otherPlayers Other players involved
    /// @param startTime The start time of the record
    event RecordSet(
        uint256 indexed recordId,
        uint256 indexed playerIndex,
        uint256 indexed playDataId,
        int256 score,
        string key,
        string value,
        uint256[] otherPlayers,
        uint256 startTime
    );

    event PlayerMetadataAdded(
        uint256 indexed playerIndex,
        string key,
        string value
    );

    event PlayerIdUpdated(uint256 indexed playerIndex, string playerID);

    /* ----------------------------- CONSTRUCTOR ----------------------------- */
    /**
     * @dev Sets up the contract with the deployer as the default admin and moderator
     */
    constructor() AccessControlDefaultAdminRules(0, msg.sender) {
        _grantRole(MODERATOR_ROLE, msg.sender);
    }

    modifier modOnlyWhenActive() {
        require(!paused(), "paused");
        require(hasRole(MODERATOR_ROLE, msg.sender), "not mod");
        _;
    }

    // /* -------------------------- ROLE MANAGEMENT --------------------------- */
    // /**
    //  * @notice Grants the moderator role to an account
    //  * @param account The address to grant the role to
    //  */
    // function grantModerator(
    //     address account
    // ) external onlyRole(DEFAULT_ADMIN_ROLE) {
    //     _grantRole(MODERATOR_ROLE, account);
    // }

    // /**
    //  * @notice Revokes the moderator role from an account
    //  * @param account The address to revoke the role from
    //  */
    // function revokeModerator(
    //     address account
    // ) external onlyRole(DEFAULT_ADMIN_ROLE) {
    //     _revokeRole(MODERATOR_ROLE, account);
    // }

    /* ---------------------------- WITHDRAW ETH ---------------------------- */
    /**
     * @notice Withdraws all ETH from the contract
     * @param recipient The address to send the ETH to
     * @dev Only callable by the admin
     */
    function withdrawETH(
        address payable recipient
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        uint256 bal = address(this).balance;
        if (bal == 0) revert NotFound(); // nothing to withdraw
        (bool ok, ) = recipient.call{value: bal}("");
        if (!ok) revert Invalid(); // low‑level send failed
    }

    /* ------------------------- APPLICATION LOGIC -------------------------- */
    /**
     * @notice Sets the application name and owner
     * @param _name The name of the application
     * @dev Only callable by the admin when not paused
     */
    function setApplication(
        string calldata _name
    ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) {
        application.setApplication(_name, msg.sender);
        emit ApplicationSet(_name, msg.sender);
    }

    /**
     * @notice Creates a new application record
     * @param _ver The version of the application
     * @param _company The company name
     * @param _contracts The contract addresses
     * @return recordId The ID of the created record
     * @dev Only callable by the admin when not paused
     */
    function createApplicationRecord(
        string calldata _ver,
        string calldata _company,
        address[] calldata _contracts
    )
        external
        whenNotPaused
        onlyRole(DEFAULT_ADMIN_ROLE)
        returns (uint256 recordId)
    {
        recordId = applicationRecords.createApplicationRecord(
            _ver,
            _company,
            _contracts
        );

        emit ApplicationRecordCreated(recordId, _ver, _company, _contracts);
    }

    /**
     * @notice Updates the contract addresses for an application record
     * @param _id The ID of the record to update
     * @param _contracts The new contract addresses
     * @dev Only callable by the admin when not paused
     */
    function updateApplicationRecordAddresses(
        uint256 _id,
        address[] calldata _contracts
    ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_id >= applicationRecords.length) revert IndexOutOfBounds();
        applicationRecords.updateApplicationRecordAddresses(_id, _contracts);
        emit ApplicationRecordAddressesUpdated(_id, _contracts);
    }

    /* --------------------------- APPPLICATION GETTERS ----------------------------- */

    /**
     * @notice Gets the index of the latest application record
     * @return The index of the latest record, or 0 if none exists
     */
    function getLatestApplicationRecord() external view returns (uint256) {
        uint256 len = applicationRecords.length;
        return len == 0 ? 0 : len - 1;
    }

    /**
     * @notice Gets an application record by index
     * @param idx The index of the record
     * @return ver The application version
     * @return company The company name
     * @return contracts_ The contract addresses
     */
    function getApplicationRecordByIndex(
        uint256 idx
    )
        external
        view
        returns (
            string memory ver,
            string memory company,
            address[] memory contracts_
        )
    {
        if (idx >= applicationRecords.length) revert IndexOutOfBounds();
        DataTypes.ApplicationRecord storage r = applicationRecords[idx];
        return (r.applicationVersion, r.companyName, r.contractAddresses);
    }

    /**
     * @notice Gets the contract addresses for an application record
     * @param idx The index of the record
     * @return The contract addresses
     */
    function getApplicationRecordAddresses(
        uint256 idx
    ) external view returns (address[] memory) {
        if (idx >= applicationRecords.length) revert IndexOutOfBounds();
        return applicationRecords[idx].contractAddresses;
    }

    /* --------------------------- PLAYER LOGIC ----------------------------- */
    /**
     * @notice Creates a new player
     * @param _pid The unique ID of the player
     * @param _ptype The type of player
     * @param _addr The address of the player
     * @return idx The index of the created player
     * @dev Only callable by moderators when not paused
     */
    function createPlayer(
        string calldata _pid,
        DataTypes.PlayerType _ptype,
        address _addr
    ) external modOnlyWhenActive returns (uint256 idx) {
        idx = players.createPlayer(
            playerByUniqueId,
            playersByAddress,
            _pid,
            _ptype,
            _addr
        );
        emit PlayerCreated(idx, _addr, _pid, _ptype);
    }

    /**
     * @notice Updates a player's score
     * @param idx The index of the player
     * @param newScore The new score
     * @dev Only callable by moderators when not paused
     */
    function updatePlayerScore(
        uint256 idx,
        int256 newScore
    ) external modOnlyWhenActive {
        if (idx >= players.length) revert IndexOutOfBounds();
        players[idx].totalScore = newScore;
        emit PlayerScoreUpdated(idx, newScore);
    }

    /**
     * @notice Adds a verified address to a player
     * @param idx The index of the player
     * @param a The address to verify
     * @dev Only callable by moderators when not paused
     */
    function addVerifiedAddress(
        uint256 idx,
        address a
    ) external modOnlyWhenActive {
        players.addVerifiedAddress(idx, a);
        emit PlayerVerifiedAddressAdded(idx, a);
    }

    /**
     * @notice Adds an identifier to a player
     * @param idx The index of the player
     * @param k The identifier key
     * @param v The identifier value
     * @dev Only callable by moderators when not paused
     */
    function addPlayerIdentifier(
        uint256 idx,
        string calldata k,
        string calldata v
    ) external modOnlyWhenActive {
        players.addPlayerIdentifier(idx, k, v);
        emit PlayerIdentifierAdded(idx, k, v);
    }

    /**
     * @notice Sets metadata for a player
     * @param idx The index of the player
     * @param k The metadata key
     * @param v The metadata value
     * @dev Only callable by moderators when not paused
     */
    function setPlayerMetadata(
        uint256 idx,
        string calldata k,
        string calldata v
    ) external modOnlyWhenActive {
        if (idx >= players.length) revert IndexOutOfBounds();

        CoreLib.addMetadata(players[idx].metadata, k, v);

        emit PlayerMetadataAdded(idx, k, v);
    }

    /* Player Getters */

    /**
     * @notice Gets a player's details by index
     * @param idx The index of the player
     * @return pid The player's unique ID
     * @return addr The player's address
     * @return ptype The player's type
     * @return score The player's total score
     * @return idKeys The player's identifier keys
     * @return idVals The player's identifier values
     * @return verifiedAddrs The player's verified addresses
     */
    function getPlayerByIndex(
        uint256 idx
    )
        external
        view
        returns (
            string memory pid,
            address addr,
            DataTypes.PlayerType ptype,
            int256 score,
            string[] memory idKeys,
            string[] memory idVals,
            address[] memory verifiedAddrs
        )
    {
        if (idx >= players.length) revert IndexOutOfBounds();
        DataTypes.Player storage p = players[idx];
        return (
            p.playerID,
            p.playerAddress,
            p.playerType,
            p.totalScore,
            p.verifiedIdKey,
            p.verifiedIdValue,
            p.verifiedAddresses
        );
    }

    /**
     * @notice Gets a player's index by address
     * @param a The player's address
     * @return The player's index
     * @dev Reverts if no player with the address exists
     */
    function getPlayerIndexByAddress(
        address a
    ) external view returns (uint256) {
        uint256 stored = playersByAddress[a];
        if (stored == 0) revert NotFound();
        return stored - 1;
    }

    // function getPlayerScore(uint256 idx) external view returns (int256) {
    //     if (idx >= players.length) revert IndexOutOfBounds();
    //     return players[idx].totalScore;
    // }

    function getPlayerUniqueId(
        uint256 idx
    ) external view returns (string memory) {
        if (idx >= players.length) revert IndexOutOfBounds();
        return players[idx].playerID;
    }

    /**
     * @notice Gets a player's index by unique ID
     * @param _pid The player's unique ID
     * @return The player's index
     * @dev Reverts if no player with the ID exists
     */
    function getPlayerIndex(
        string calldata _pid
    ) external view returns (uint256) {
        uint256 stored = playerByUniqueId[_pid];
        if (stored == 0) revert NotFound();
        return stored - 1;
    }

    /**
     * @notice Gets the total number of players
     * @return The number of players
     */
    function getPlayerCount() external view returns (uint256) {
        return players.length;
    }

    /**
     * @notice Gets a player's index by verified identifier
     * @param k The identifier key
     * @param v The identifier value
     * @return The player's index
     * @dev Reverts if no player with the identifier exists
     */
    function getPlayerByVerifiedId(
        string calldata k,
        string calldata v
    ) external view returns (uint256) {
        for (uint256 i; i < players.length; ++i) {
            DataTypes.Player storage p = players[i];
            for (uint256 j; j < p.verifiedIdKey.length; ++j) {
                if (
                    keccak256(bytes(p.verifiedIdKey[j])) ==
                    keccak256(bytes(k)) &&
                    keccak256(bytes(p.verifiedIdValue[j])) ==
                    keccak256(bytes(v))
                ) {
                    return i;
                }
            }
        }
        revert NotFound();
    }

    /**
     * @notice Updates a player's unique ID (username)
     * @param idx The index of the player
     * @param newPid The new unique ID
     * @dev Only callable by moderators when not paused
     */
    function updatePlayerUniqueId(
        uint256 idx,
        string calldata newPid
    ) external modOnlyWhenActive {
        if (idx >= players.length) revert IndexOutOfBounds();

        // Revert if newPid is already used
        if (playerByUniqueId[newPid] != 0) revert AlreadyExists();

        string memory oldPid = players[idx].playerID;
        delete playerByUniqueId[oldPid];

        players[idx].playerID = newPid;

        // Store new mapping (+1 for 1-based indexing)
        playerByUniqueId[newPid] = idx + 1;
        emit PlayerIdUpdated(idx, newPid);
    }

    /* Login Sessions */

    /**
     * @notice Creates a login session for a player
     * @param idx The index of the player
     * @param appId The application ID
     * @param start The start time of the session
     * @param devc The device information
     * @return sid The ID of the created session
     * @dev Only callable by moderators when not paused
     */
    function loginSessionCreate(
        uint256 idx,
        uint256 appId,
        uint256 start,
        DataTypes.Device devc
    ) external modOnlyWhenActive returns (uint256 sid) {
        if (appId >= applicationRecords.length) revert IndexOutOfBounds();
        if (idx >= players.length) revert IndexOutOfBounds();

        sid = SessionLib.loginSessionCreate(
            activeLoginSessions,
            activeLoginSessionByPlayer,
            playersWithActiveSessions,
            loginSessions,
            idx,
            appId,
            start,
            devc
        );

        emit LoginSessionCreated(sid, idx, start, devc, appId);
    }

    /**
     * @notice Ends a login session
     * @param sid The ID of the session
     * @param end The end time of the session
     * @dev Only callable by moderators when not paused
     */
    function loginSessionEnd(
        uint256 sid,
        uint256 end
    ) external modOnlyWhenActive {
        SessionLib.loginSessionEnd(
            activeLoginSessions,
            activeLoginSessionByPlayer,
            playersWithActiveSessions,
            loginSessions,
            sid,
            end
        );
        emit LoginSessionEnded(sid, end);
    }

    /**
     * @notice Sets metadata for a login session
     * @param sid The ID of the session
     * @param k The metadata key
     * @param v The metadata value
     * @dev Only callable by moderators when not paused
     */
    function setLoginSessionMetadata(
        uint256 sid,
        string calldata k,
        string calldata v
    ) external modOnlyWhenActive {
        if (sid >= loginSessions.length) revert IndexOutOfBounds();

        CoreLib.addMetadata(loginSessions[sid].metadata, k, v);

        emit LoginSessionMetadataAdded(sid, k, v);
    }

    /* Login Session Getters */

    /**
     * @notice Gets the total number of login sessions
     * @return The number of login sessions
     */
    function getLoginSessionCount() external view returns (uint256) {
        return loginSessions.length;
    }

    /**
     * @notice Gets all players with active login sessions
     * @return Array of player indices with active sessions
     */
    function getAllActiveLoginPlayers()
        external
        view
        returns (uint256[] memory)
    {
        return playersWithActiveSessions;
    }

    /**
     * @notice Gets all active login session IDs
     * @return Array of active login session IDs
     */
    function getAllActiveLoginSessionIds()
        external
        view
        returns (uint256[] memory)
    {
        return activeLoginSessions;
    }

    /**
     * @notice Gets a login session by ID
     * @param sid The ID of the session
     * @return base_ The base data of the session
     * @return meta_ The metadata of the session
     * @return device_ The device information
     * @return playerIdx The player index
     * @return matchIds_ The match IDs associated with the session
     */
    function getLoginSessionById(
        uint256 sid
    )
        external
        view
        returns (
            DataTypes.BaseData memory base_,
            DataTypes.MetaData memory meta_,
            DataTypes.Device device_,
            uint256 playerIdx,
            uint256[] memory matchIds_
        )
    {
        if (sid >= loginSessions.length) revert IndexOutOfBounds();
        DataTypes.LoginSession storage s = loginSessions[sid];
        return (s.baseData, s.metadata, s.device, s.playerIndex, s.matchIds);
    }

    /* Match Sessions */

    /**
     * @notice Starts a match session
     * @param appId The application ID
     * @param start The start time of the match
     * @param multiplayer Whether the match is multiplayer
     * @param pIdx Array of player indices
     * @param level The level/map of the match
     * @return mid The ID of the created match
     * @dev Only callable by moderators when not paused
     */
    function startMatchSession(
        uint256 appId,
        uint256 start,
        bool multiplayer,
        uint256[] calldata pIdx,
        string calldata level
    ) external modOnlyWhenActive returns (uint256 mid) {
        if (appId >= applicationRecords.length) revert IndexOutOfBounds();

        mid = MatchLibSession.startMatchSession(
            activeMatchSessions,
            loginSessions,
            matchSessions,
            playDatas,
            appId,
            start,
            multiplayer,
            pIdx,
            level
        );

        // Emit the main match session event
        emit MatchSessionStarted(mid, appId, start, multiplayer, pIdx, level);

        // Emit individual events for each player
        for (uint256 i = 0; i < pIdx.length; i++) {
            emit PlayerAddedToMatchSession(
                mid,
                pIdx[i],
                matchSessions[mid].playData[i]
            );
        }
    }

    /**
     * @notice Ends a match session
     * @param mid The ID of the match
     * @param end The end time of the match
     * @dev Only callable by moderators when not paused
     */
    function endMatchSession(
        uint256 mid,
        uint256 end
    ) external modOnlyWhenActive {
        MatchLibSession.endMatchSession(
            matchSessions,
            activeMatchSessions,
            playDatas,
            mid,
            end
        );
        emit MatchSessionEnded(mid, end);
    }

    /**
     * @notice Sets metadata for a match session
     * @param mid The ID of the match session
     * @param k The metadata key
     * @param v The metadata value
     * @dev Only callable by moderators when not paused
     */
    function setMatchSessionMetadata(
        uint256 mid,
        string calldata k,
        string calldata v
    ) external modOnlyWhenActive {
        if (mid >= matchSessions.length) revert IndexOutOfBounds();

        CoreLib.addMetadata(matchSessions[mid].metadata, k, v);

        emit MatchSessionMetadataAdded(mid, k, v);
    }

    /* Match Session Getters */

    /**
     * @notice Gets a match session by index
     * @param idx The index of the match
     * @return base_ The base data of the match
     * @return meta_ The metadata of the match
     * @return multiplayer Whether the match is multiplayer
     * @return playerIds The player indices
     * @return playDataIds The play data IDs
     * @return level The level/map of the match
     */
    function getMatchSessionByIndex(
        uint256 idx
    )
        external
        view
        returns (
            DataTypes.BaseData memory base_,
            DataTypes.MetaData memory meta_,
            bool multiplayer,
            uint256[] memory playerIds,
            uint256[] memory playDataIds,
            string memory level
        )
    {
        if (idx >= matchSessions.length) revert IndexOutOfBounds();
        DataTypes.MatchSession storage m = matchSessions[idx];
        return (
            m.baseData,
            m.metadata,
            m.multiplayer,
            m.playerIds,
            m.playData,
            m.level
        );
    }

    /**
     * @notice Gets all active match session IDs
     * @return Array of active match session IDs
     */
    function getAllActiveMatchSessionIds()
        external
        view
        returns (uint256[] memory)
    {
        return activeMatchSessions;
    }

    /**
     * @notice Gets the total number of match sessions
     * @return The number of match sessions
     */
    function getMatchSessionCount() external view returns (uint256) {
        return matchSessions.length;
    }

    /* Play Data */

    /**
     * @notice Adds a player to a match session
     * @param mid The ID of the match
     * @param pIdx The index of the player
     * @param startTime The start time for the player
     * @dev Only callable by moderators when not paused
     */
    function addPlayerToMatchSession(
        uint256 mid,
        uint256 pIdx,
        uint256 startTime
    ) external modOnlyWhenActive {
        if (pIdx >= players.length) revert IndexOutOfBounds();

        uint256 pdId = MatchLibSession.addPlayerToMatch(
            matchSessions,
            playDatas,
            mid,
            pIdx,
            startTime
        );

        emit PlayerAddedToMatchSession(mid, pIdx, pdId);
    }

    /**
     * @notice Updates play data for a player in a match session
     * @param mid The ID of the match
     * @param pIdx The index of the player
     * @param end The end time
     * @param score The player's score
     * @param wl The win/loss status
     * @param pos The player's position in the match
     * @return pdId The ID of the updated play data
     * @return playerIdx The player index
     * @dev Only callable by moderators when not paused
     */
    function updatePlayDataForMatchSession(
        uint256 mid,
        uint256 pIdx,
        uint256 end,
        int256 score,
        DataTypes.WinLoss wl,
        int256 pos
    ) external modOnlyWhenActive returns (uint256 pdId, uint256 playerIdx) {
        uint256 playId = findPlayDataId(mid, pIdx);

        (pdId, playerIdx) = MatchLibPlayer.updatePlayerData(
            playId,
            playDatas,
            end,
            score,
            wl,
            pos
        );

        emit PlayerDataUpdated(playerIdx, pdId, end, score, wl, pos);
    }

    /* Play Data Getters */

    /**
     * @notice Gets play data by index
     * @param idx The index of the play data
     * @return base_ The base data
     * @return playerIdx The player index
     * @return score The player's score
     * @return wl The win/loss status
     * @return pos The player's position
     * @return recIds The record IDs
     */
    function getPlayDataByIndex(
        uint256 idx
    )
        external
        view
        returns (
            DataTypes.BaseData memory base_,
            uint256 playerIdx,
            int256 score,
            DataTypes.WinLoss wl,
            int256 pos,
            uint256[] memory recIds
        )
    {
        if (idx >= playDatas.length) revert IndexOutOfBounds();
        DataTypes.PlayData storage pd = playDatas[idx];
        return (
            pd.baseData,
            pd.playerIndex,
            pd.score,
            pd.winLoss,
            pd.matchPosition,
            pd.records
        );
    }

    /**
     * @notice Gets the total number of play data records
     * @return The number of play data records
     */
    function getPlayDataCount() external view returns (uint256) {
        return playDatas.length;
    }

    /* ----------------------------- RECORDS -------------------------------- */
    /**
     * @notice Sets a record for a player in a match
     * @param mid The ID of the match
     * @param pIdx The index of the player
     * @param score The player's score
     * @param key The record key
     * @param value The record value
     * @param others Array of other player indices involved
     * @param start The start time of the record
     * @return rid The ID of the created record
     * @return playerId The player ID
     * @dev Only callable by moderators when not paused
     */
    function setRecord(
        uint256 mid,
        uint256 pIdx,
        int256 score,
        string calldata key,
        string calldata value,
        uint256[] calldata others,
        uint256 start
    ) external modOnlyWhenActive returns (uint256 rid, uint256 playerId) {
        uint256 pdId;
        if (mid == 0) {
            // For match ID 0, we don't need playData ID
            pdId = type(uint256).max; // Use max uint256 as a sentinel value
        } else {
            pdId = findPlayDataId(mid, pIdx);
        }

        (rid, playerId) = RecordLib.setRecord(
            pdId,
            playDatas,
            records,
            recordsByUniqueId,
            recordsByPlayer,
            score,
            key,
            value,
            others,
            start,
            pIdx
        );

        emit RecordSet(rid, playerId, pdId, score, key, value, others, start);
    }

    /**
     * @notice Batch sets multiple records in one transaction
     * @param inputs An array of RecordInput structs
     * @dev Only callable by moderators when not paused
     */
    function batchSetRecords(
        DataTypes.RecordInput[] calldata inputs
    ) external modOnlyWhenActive {
        uint256 len = inputs.length;
        for (uint256 i = 0; i < len; ++i) {
            DataTypes.RecordInput calldata input = inputs[i];

            uint256 pdId = type(uint256).max; // Use max uint256 as a sentinel value

            if (input.matchId != 0) {
                pdId = _findPlayDataId(
                    input.matchId,
                    input.playerIndex
                );
            }

            (uint256 rid, uint256 playerId) = RecordLib.setRecord(
                pdId,
                playDatas,
                records,
                recordsByUniqueId,
                recordsByPlayer,
                input.score,
                input.key,
                input.value,
                input.otherPlayers,
                input.startTime,
                input.playerIndex
            );

            emit RecordSet(
                rid,
                playerId,
                pdId,
                input.score,
                input.key,
                input.value,
                input.otherPlayers,
                input.startTime
            );
        }
    }

    /**
     * @notice Gets a record by index
     * @param idx The index of the record
     * @return id The record ID
     * @return key The record key
     * @return value The record value
     * @return score The score
     * @return start The start time
     * @return playerIdx The player index
     * @return others Other player indices involved
     */
    function getRecordsByIndex(
        uint256 idx
    )
        external
        view
        returns (
            uint256 id,
            string memory key,
            string memory value,
            int256 score,
            uint256 start,
            uint256 playerIdx,
            uint256[] memory others
        )
    {
        if (idx >= records.length) revert IndexOutOfBounds();
        DataTypes.Records storage r = records[idx];
        return (
            r.id,
            r.key,
            r.value,
            r.score,
            r.startTime,
            r.playerIndex,
            r.otherPlayer
        );
    }

    // /**
    //  * @notice Gets the total number of records
    //  * @return The number of records
    //  */
    // function recordsLength() external view returns (uint256) {
    //     return records.length;
    // }

    /**
     * @notice Gets all record IDs for a player
     * @param playerIdx The player index
     * @return ids Array of record IDs
     */
    function getRecordIdsByPlayer(
        uint256 playerIdx
    ) external view returns (uint256[] memory) {
        // Simply return the array of record IDs for this player
        // This is much more efficient than the previous implementation
        return recordsByPlayer[playerIdx];
    }

    /* ------------------------- BAN / UNBAN PLAYERS ------------------------ */
    /**
     * @notice Bans a player
     * @param idx The index of the player to ban
     * @dev Only callable by moderators
     * @dev Emits UserBanned event
     */
    function banPlayer(uint256 idx) external modOnlyWhenActive {
        if (idx >= players.length) revert IndexOutOfBounds();
        if (bannedByPlayer[idx] != 0) revert AlreadyExists();

        banned.push(idx);
        bannedByPlayer[idx] = banned.length; // Store position + 1
        emit UserBanned(idx, block.timestamp);
    }

    /**
     * @notice Unbans a player
     * @param idx The index of the player to unban
     * @dev Only callable by moderators
     * @dev Emits UserUnbanned event
     */
    function unbanPlayer(uint256 idx) external modOnlyWhenActive {
        uint256 position = bannedByPlayer[idx];
        if (position == 0) revert NotFound();

        position--; // Convert from 1-based to 0-based index
        uint256 lastIdx = banned.length - 1;

        // If not the last element, swap with last
        if (position != lastIdx) {
            uint256 lastPlayer = banned[lastIdx];
            banned[position] = lastPlayer;
            bannedByPlayer[lastPlayer] = position + 1; // Update position of swapped player
        }

        banned.pop();
        delete bannedByPlayer[idx];
        emit UserUnbanned(idx, block.timestamp);
    }

    // /**
    //  * @notice Gets a banned player by index in the banned array
    //  * @param i The index in the banned array
    //  * @return The player index
    //  */
    // function getPlayerBannedByIndex(uint256 i) external view returns (uint256) {
    //     if (i >= banned.length) revert IndexOutOfBounds();
    //     return banned[i];
    // }

    /**
     * @notice Gets all banned player indices
     * @return Array of banned player indices
     */
    function getAllBannedPlayers() external view returns (uint256[] memory) {
        return banned;
    }

    /**
     * @notice Checks if a player is banned
     * @param idx The index of the player
     * @return True if the player is banned, false otherwise
     */
    function isPlayerBanned(uint256 idx) external view returns (bool) {
        if (idx >= players.length) revert IndexOutOfBounds();
        return bannedByPlayer[idx] != 0;
    }

    /* --------------------------- INTERNAL HELPERS ------------------------- */
    /**
     * @notice Finds the play data ID for a player in a match
     * @param mid The match ID
     * @param pIdx The player index
     * @return id The play data ID
     * @dev Reverts if the player is not in the match or if match ID is invalid
     */
    function findPlayDataId(
        uint256 mid,
        uint256 pIdx
    ) public view returns (uint256 id) {
        if (mid >= matchSessions.length) revert IndexOutOfBounds();

        DataTypes.MatchSession storage ms = matchSessions[mid];

        for (uint256 i; i < ms.playerIds.length; ++i)
            if (ms.playerIds[i] == pIdx) return ms.playData[i];

        revert NotFound(); // player not in match
    }

    /**
     * @notice Internal version of findPlayDataId for contract internal use
     * @param mid The match ID
     * @param pIdx The player index
     * @return id The play data ID
     * @dev Reverts if the player is not in the match or if match ID is invalid
     */
    function _findPlayDataId(
        uint256 mid,
        uint256 pIdx
    ) internal view returns (uint256 id) {
        return findPlayDataId(mid, pIdx);
    }

    /**
     * @notice Pauses the contract
     * @dev Only callable by the admin
     */
    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
    }

    /**
     * @notice Unpauses the contract
     * @dev Only callable by the admin
     */
    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
    }
}

Other files

  • @openzeppelin/contracts/access/AccessControl.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
    
    pragma solidity ^0.8.20;
    
    import {IAccessControl} from "./IAccessControl.sol";
    import {Context} from "../utils/Context.sol";
    import {ERC165} from "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
        struct RoleData {
            mapping(address account => bool) hasRole;
            bytes32 adminRole;
        }
    
        mapping(bytes32 role => RoleData) private _roles;
    
        bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
    
        /**
         * @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);
            _;
        }
    
        /**
         * @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) {
            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) {
            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 {
            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) {
            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) {
            if (hasRole(role, account)) {
                _roles[role].hasRole[account] = false;
                emit RoleRevoked(role, account, _msgSender());
                return true;
            } else {
                return false;
            }
        }
    }
    
  • @openzeppelin/contracts/access/IAccessControl.sol
    // 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;
    }
    
  • @openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol)
    
    pragma solidity ^0.8.20;
    
    import {IAccessControlDefaultAdminRules} from "./IAccessControlDefaultAdminRules.sol";
    import {AccessControl, IAccessControl} from "../AccessControl.sol";
    import {SafeCast} from "../../utils/math/SafeCast.sol";
    import {Math} from "../../utils/math/Math.sol";
    import {IERC5313} from "../../interfaces/IERC5313.sol";
    
    /**
     * @dev Extension of {AccessControl} that allows specifying special rules to manage
     * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
     * over other roles that may potentially have privileged rights in the system.
     *
     * If a specific role doesn't have an admin role assigned, the holder of the
     * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
     *
     * This contract implements the following risk mitigations on top of {AccessControl}:
     *
     * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
     * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
     * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
     * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
     * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
     *
     * Example usage:
     *
     * ```solidity
     * contract MyToken is AccessControlDefaultAdminRules {
     *   constructor() AccessControlDefaultAdminRules(
     *     3 days,
     *     msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
     *    ) {}
     * }
     * ```
     */
    abstract contract AccessControlDefaultAdminRules is IAccessControlDefaultAdminRules, IERC5313, AccessControl {
        // pending admin pair read/written together frequently
        address private _pendingDefaultAdmin;
        uint48 private _pendingDefaultAdminSchedule; // 0 == unset
    
        uint48 private _currentDelay;
        address private _currentDefaultAdmin;
    
        // pending delay pair read/written together frequently
        uint48 private _pendingDelay;
        uint48 private _pendingDelaySchedule; // 0 == unset
    
        /**
         * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
         */
        constructor(uint48 initialDelay, address initialDefaultAdmin) {
            if (initialDefaultAdmin == address(0)) {
                revert AccessControlInvalidDefaultAdmin(address(0));
            }
            _currentDelay = initialDelay;
            _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
        }
    
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
        }
    
        /**
         * @dev See {IERC5313-owner}.
         */
        function owner() public view virtual returns (address) {
            return defaultAdmin();
        }
    
        ///
        /// Override AccessControl role management
        ///
    
        /**
         * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
         */
        function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
            if (role == DEFAULT_ADMIN_ROLE) {
                revert AccessControlEnforcedDefaultAdminRules();
            }
            super.grantRole(role, account);
        }
    
        /**
         * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
         */
        function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
            if (role == DEFAULT_ADMIN_ROLE) {
                revert AccessControlEnforcedDefaultAdminRules();
            }
            super.revokeRole(role, account);
        }
    
        /**
         * @dev See {AccessControl-renounceRole}.
         *
         * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
         * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
         * has also passed when calling this function.
         *
         * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
         *
         * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
         * thereby disabling any functionality that is only available for it, and the possibility of reassigning a
         * non-administrated role.
         */
        function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
            if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
                (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
                if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
                    revert AccessControlEnforcedDefaultAdminDelay(schedule);
                }
                delete _pendingDefaultAdminSchedule;
            }
            super.renounceRole(role, account);
        }
    
        /**
         * @dev See {AccessControl-_grantRole}.
         *
         * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
         * role has been previously renounced.
         *
         * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
         * assignable again. Make sure to guarantee this is the expected behavior in your implementation.
         */
        function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
            if (role == DEFAULT_ADMIN_ROLE) {
                if (defaultAdmin() != address(0)) {
                    revert AccessControlEnforcedDefaultAdminRules();
                }
                _currentDefaultAdmin = account;
            }
            return super._grantRole(role, account);
        }
    
        /**
         * @dev See {AccessControl-_revokeRole}.
         */
        function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
            if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
                delete _currentDefaultAdmin;
            }
            return super._revokeRole(role, account);
        }
    
        /**
         * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
         */
        function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
            if (role == DEFAULT_ADMIN_ROLE) {
                revert AccessControlEnforcedDefaultAdminRules();
            }
            super._setRoleAdmin(role, adminRole);
        }
    
        ///
        /// AccessControlDefaultAdminRules accessors
        ///
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function defaultAdmin() public view virtual returns (address) {
            return _currentDefaultAdmin;
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
            return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule);
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function defaultAdminDelay() public view virtual returns (uint48) {
            uint48 schedule = _pendingDelaySchedule;
            return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay;
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
            schedule = _pendingDelaySchedule;
            return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? (_pendingDelay, schedule) : (0, 0);
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
            return 5 days;
        }
    
        ///
        /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
        ///
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
            _beginDefaultAdminTransfer(newAdmin);
        }
    
        /**
         * @dev See {beginDefaultAdminTransfer}.
         *
         * Internal function without access restriction.
         */
        function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
            uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
            _setPendingDefaultAdmin(newAdmin, newSchedule);
            emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
            _cancelDefaultAdminTransfer();
        }
    
        /**
         * @dev See {cancelDefaultAdminTransfer}.
         *
         * Internal function without access restriction.
         */
        function _cancelDefaultAdminTransfer() internal virtual {
            _setPendingDefaultAdmin(address(0), 0);
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function acceptDefaultAdminTransfer() public virtual {
            (address newDefaultAdmin, ) = pendingDefaultAdmin();
            if (_msgSender() != newDefaultAdmin) {
                // Enforce newDefaultAdmin explicit acceptance.
                revert AccessControlInvalidDefaultAdmin(_msgSender());
            }
            _acceptDefaultAdminTransfer();
        }
    
        /**
         * @dev See {acceptDefaultAdminTransfer}.
         *
         * Internal function without access restriction.
         */
        function _acceptDefaultAdminTransfer() internal virtual {
            (address newAdmin, uint48 schedule) = pendingDefaultAdmin();
            if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
                revert AccessControlEnforcedDefaultAdminDelay(schedule);
            }
            _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
            _grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
            delete _pendingDefaultAdmin;
            delete _pendingDefaultAdminSchedule;
        }
    
        ///
        /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
        ///
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
            _changeDefaultAdminDelay(newDelay);
        }
    
        /**
         * @dev See {changeDefaultAdminDelay}.
         *
         * Internal function without access restriction.
         */
        function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
            uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
            _setPendingDelay(newDelay, newSchedule);
            emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
        }
    
        /**
         * @inheritdoc IAccessControlDefaultAdminRules
         */
        function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
            _rollbackDefaultAdminDelay();
        }
    
        /**
         * @dev See {rollbackDefaultAdminDelay}.
         *
         * Internal function without access restriction.
         */
        function _rollbackDefaultAdminDelay() internal virtual {
            _setPendingDelay(0, 0);
        }
    
        /**
         * @dev Returns the amount of seconds to wait after the `newDelay` will
         * become the new {defaultAdminDelay}.
         *
         * The value returned guarantees that if the delay is reduced, it will go into effect
         * after a wait that honors the previously set delay.
         *
         * See {defaultAdminDelayIncreaseWait}.
         */
        function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
            uint48 currentDelay = defaultAdminDelay();
    
            // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
            // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
            // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
            // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
            // using milliseconds instead of seconds.
            //
            // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
            // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
            // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
            return
                newDelay > currentDelay
                    ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
                    : currentDelay - newDelay;
        }
    
        ///
        /// Private setters
        ///
    
        /**
         * @dev Setter of the tuple for pending admin and its schedule.
         *
         * May emit a DefaultAdminTransferCanceled event.
         */
        function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
            (, uint48 oldSchedule) = pendingDefaultAdmin();
    
            _pendingDefaultAdmin = newAdmin;
            _pendingDefaultAdminSchedule = newSchedule;
    
            // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
            if (_isScheduleSet(oldSchedule)) {
                // Emit for implicit cancellations when another default admin was scheduled.
                emit DefaultAdminTransferCanceled();
            }
        }
    
        /**
         * @dev Setter of the tuple for pending delay and its schedule.
         *
         * May emit a DefaultAdminDelayChangeCanceled event.
         */
        function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
            uint48 oldSchedule = _pendingDelaySchedule;
    
            if (_isScheduleSet(oldSchedule)) {
                if (_hasSchedulePassed(oldSchedule)) {
                    // Materialize a virtual delay
                    _currentDelay = _pendingDelay;
                } else {
                    // Emit for implicit cancellations when another delay was scheduled.
                    emit DefaultAdminDelayChangeCanceled();
                }
            }
    
            _pendingDelay = newDelay;
            _pendingDelaySchedule = newSchedule;
        }
    
        ///
        /// Private helpers
        ///
    
        /**
         * @dev Defines if an `schedule` is considered set. For consistency purposes.
         */
        function _isScheduleSet(uint48 schedule) private pure returns (bool) {
            return schedule != 0;
        }
    
        /**
         * @dev Defines if an `schedule` is considered passed. For consistency purposes.
         */
        function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
            return schedule < block.timestamp;
        }
    }
    
  • @openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/IAccessControlDefaultAdminRules.sol)
    
    pragma solidity ^0.8.20;
    
    import {IAccessControl} from "../IAccessControl.sol";
    
    /**
     * @dev External interface of AccessControlDefaultAdminRules declared to support ERC-165 detection.
     */
    interface IAccessControlDefaultAdminRules is IAccessControl {
        /**
         * @dev The new default admin is not a valid default admin.
         */
        error AccessControlInvalidDefaultAdmin(address defaultAdmin);
    
        /**
         * @dev At least one of the following rules was violated:
         *
         * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
         * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
         * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
         */
        error AccessControlEnforcedDefaultAdminRules();
    
        /**
         * @dev The delay for transferring the default admin delay is enforced and
         * the operation must wait until `schedule`.
         *
         * NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
         */
        error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);
    
        /**
         * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
         * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
         * passes.
         */
        event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);
    
        /**
         * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
         */
        event DefaultAdminTransferCanceled();
    
        /**
         * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
         * delay to be applied between default admin transfer after `effectSchedule` has passed.
         */
        event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);
    
        /**
         * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
         */
        event DefaultAdminDelayChangeCanceled();
    
        /**
         * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
         */
        function defaultAdmin() external view returns (address);
    
        /**
         * @dev Returns a tuple of a `newAdmin` and an accept schedule.
         *
         * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
         * by calling {acceptDefaultAdminTransfer}, completing the role transfer.
         *
         * A zero value only in `acceptSchedule` indicates no pending admin transfer.
         *
         * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
         */
        function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);
    
        /**
         * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
         *
         * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
         * the acceptance schedule.
         *
         * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
         * function returns the new delay. See {changeDefaultAdminDelay}.
         */
        function defaultAdminDelay() external view returns (uint48);
    
        /**
         * @dev Returns a tuple of `newDelay` and an effect schedule.
         *
         * After the `schedule` passes, the `newDelay` will get into effect immediately for every
         * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
         *
         * A zero value only in `effectSchedule` indicates no pending delay change.
         *
         * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
         * will be zero after the effect schedule.
         */
        function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);
    
        /**
         * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
         * after the current timestamp plus a {defaultAdminDelay}.
         *
         * Requirements:
         *
         * - Only can be called by the current {defaultAdmin}.
         *
         * Emits a DefaultAdminRoleChangeStarted event.
         */
        function beginDefaultAdminTransfer(address newAdmin) external;
    
        /**
         * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
         *
         * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
         *
         * Requirements:
         *
         * - Only can be called by the current {defaultAdmin}.
         *
         * May emit a DefaultAdminTransferCanceled event.
         */
        function cancelDefaultAdminTransfer() external;
    
        /**
         * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
         *
         * After calling the function:
         *
         * - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
         * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
         * - {pendingDefaultAdmin} should be reset to zero values.
         *
         * Requirements:
         *
         * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
         * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
         */
        function acceptDefaultAdminTransfer() external;
    
        /**
         * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
         * into effect after the current timestamp plus a {defaultAdminDelay}.
         *
         * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
         * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
         * set before calling.
         *
         * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
         * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
         * complete transfer (including acceptance).
         *
         * The schedule is designed for two scenarios:
         *
         * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
         * {defaultAdminDelayIncreaseWait}.
         * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
         *
         * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
         *
         * Requirements:
         *
         * - Only can be called by the current {defaultAdmin}.
         *
         * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
         */
        function changeDefaultAdminDelay(uint48 newDelay) external;
    
        /**
         * @dev Cancels a scheduled {defaultAdminDelay} change.
         *
         * Requirements:
         *
         * - Only can be called by the current {defaultAdmin}.
         *
         * May emit a DefaultAdminDelayChangeCanceled event.
         */
        function rollbackDefaultAdminDelay() external;
    
        /**
         * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
         * to take effect. Default to 5 days.
         *
         * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
         * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
         * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
         * be overrode for a custom {defaultAdminDelay} increase scheduling.
         *
         * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
         * there's a risk of setting a high new delay that goes into effect almost immediately without the
         * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
         */
        function defaultAdminDelayIncreaseWait() external view returns (uint48);
    }
    
  • @openzeppelin/contracts/interfaces/IERC5313.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol)
    
    pragma solidity ^0.8.20;
    
    /**
     * @dev Interface for the Light Contract Ownership Standard.
     *
     * A standardized minimal interface required to identify an account that controls a contract
     */
    interface IERC5313 {
        /**
         * @dev Gets the address of the owner.
         */
        function owner() external view returns (address);
    }
    
  • @openzeppelin/contracts/utils/Context.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
    
    pragma solidity ^0.8.20;
    
    /**
     * @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 Context {
        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;
        }
    }
    
  • @openzeppelin/contracts/utils/Panic.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
    
    pragma solidity ^0.8.20;
    
    /**
     * @dev Helper library for emitting standardized panic codes.
     *
     * ```solidity
     * contract Example {
     *      using Panic for uint256;
     *
     *      // Use any of the declared internal constants
     *      function foo() { Panic.GENERIC.panic(); }
     *
     *      // Alternatively
     *      function foo() { Panic.panic(Panic.GENERIC); }
     * }
     * ```
     *
     * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
     *
     * _Available since v5.1._
     */
    // slither-disable-next-line unused-state
    library Panic {
        /// @dev generic / unspecified error
        uint256 internal constant GENERIC = 0x00;
        /// @dev used by the assert() builtin
        uint256 internal constant ASSERT = 0x01;
        /// @dev arithmetic underflow or overflow
        uint256 internal constant UNDER_OVERFLOW = 0x11;
        /// @dev division or modulo by zero
        uint256 internal constant DIVISION_BY_ZERO = 0x12;
        /// @dev enum conversion error
        uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
        /// @dev invalid encoding in storage
        uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
        /// @dev empty array pop
        uint256 internal constant EMPTY_ARRAY_POP = 0x31;
        /// @dev array out of bounds access
        uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
        /// @dev resource error (too large allocation or too large array)
        uint256 internal constant RESOURCE_ERROR = 0x41;
        /// @dev calling invalid internal function
        uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
    
        /// @dev Reverts with a panic code. Recommended to use with
        /// the internal constants with predefined codes.
        function panic(uint256 code) internal pure {
            assembly ("memory-safe") {
                mstore(0x00, 0x4e487b71)
                mstore(0x20, code)
                revert(0x1c, 0x24)
            }
        }
    }
    
  • @openzeppelin/contracts/utils/Pausable.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
    
    pragma solidity ^0.8.20;
    
    import {Context} from "../utils/Context.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 Pausable is Context {
        bool private _paused;
    
        /**
         * @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.
         */
        constructor() {
            _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) {
            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 {
            _paused = true;
            emit Paused(_msgSender());
        }
    
        /**
         * @dev Returns to normal state.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        function _unpause() internal virtual whenPaused {
            _paused = false;
            emit Unpaused(_msgSender());
        }
    }
    
  • @openzeppelin/contracts/utils/introspection/ERC165.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
    
    pragma solidity ^0.8.20;
    
    import {IERC165} from "./IERC165.sol";
    
    /**
     * @dev Implementation of the {IERC165} interface.
     *
     * Contracts that want to implement 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 ERC165 is IERC165 {
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
            return interfaceId == type(IERC165).interfaceId;
        }
    }
    
  • @openzeppelin/contracts/utils/introspection/IERC165.sol
    // 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);
    }
    
  • @openzeppelin/contracts/utils/math/Math.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
    
    pragma solidity ^0.8.20;
    
    import {Panic} from "../Panic.sol";
    import {SafeCast} from "./SafeCast.sol";
    
    /**
     * @dev Standard math utilities missing in the Solidity language.
     */
    library Math {
        enum Rounding {
            Floor, // Toward negative infinity
            Ceil, // Toward positive infinity
            Trunc, // Toward zero
            Expand // Away from zero
        }
    
        /**
         * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
         */
        function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                uint256 c = a + b;
                if (c < a) return (false, 0);
                return (true, c);
            }
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
         */
        function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                if (b > a) return (false, 0);
                return (true, a - b);
            }
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
         */
        function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            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 success flag (no division by zero).
         */
        function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                if (b == 0) return (false, 0);
                return (true, a / b);
            }
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
         */
        function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
            unchecked {
                if (b == 0) return (false, 0);
                return (true, a % b);
            }
        }
    
        /**
         * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
         *
         * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
         * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
         * one branch when needed, making this function more expensive.
         */
        function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
            unchecked {
                // branchless ternary works because:
                // b ^ (a ^ b) == a
                // b ^ 0 == b
                return b ^ ((a ^ b) * SafeCast.toUint(condition));
            }
        }
    
        /**
         * @dev Returns the largest of two numbers.
         */
        function max(uint256 a, uint256 b) internal pure returns (uint256) {
            return ternary(a > b, a, b);
        }
    
        /**
         * @dev Returns the smallest of two numbers.
         */
        function min(uint256 a, uint256 b) internal pure returns (uint256) {
            return ternary(a < b, a, b);
        }
    
        /**
         * @dev Returns the average of two numbers. The result is rounded towards
         * zero.
         */
        function average(uint256 a, uint256 b) internal pure returns (uint256) {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    
        /**
         * @dev Returns the ceiling of the division of two numbers.
         *
         * This differs from standard division with `/` in that it rounds towards infinity instead
         * of rounding towards zero.
         */
        function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
            if (b == 0) {
                // Guarantee the same behavior as in a regular Solidity division.
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
    
            // The following calculation ensures accurate ceiling division without overflow.
            // Since a is non-zero, (a - 1) / b will not overflow.
            // The largest possible result occurs when (a - 1) / b is type(uint256).max,
            // but the largest value we can obtain is type(uint256).max - 1, which happens
            // when a = type(uint256).max and b = 1.
            unchecked {
                return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
            }
        }
    
        /**
         * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
         * denominator == 0.
         *
         * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
         * Uniswap Labs also under MIT license.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
            unchecked {
                // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
                // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                // variables such that product = prod1 * 2²⁵⁶ + 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²⁵⁶. Also prevents denominator == 0.
                if (denominator <= prod1) {
                    Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
                }
    
                ///////////////////////////////////////////////
                // 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²⁵⁶ / 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²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
                // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
                // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
                uint256 inverse = (3 * denominator) ^ 2;
    
                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                // works in modular arithmetic, doubling the correct bits in each step.
                inverse *= 2 - denominator * inverse; // inverse mod 2⁸
                inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
                inverse *= 2 - denominator * inverse; // inverse mod 2³²
                inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
                inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
                inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
    
                // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
                // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
                // is no longer required.
                result = prod0 * inverse;
                return result;
            }
        }
    
        /**
         * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
         */
        function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
            return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
        }
    
        /**
         * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
         *
         * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
         * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
         *
         * If the input value is not inversible, 0 is returned.
         *
         * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
         * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
         */
        function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
            unchecked {
                if (n == 0) return 0;
    
                // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
                // Used to compute integers x and y such that: ax + ny = gcd(a, n).
                // When the gcd is 1, then the inverse of a modulo n exists and it's x.
                // ax + ny = 1
                // ax = 1 + (-y)n
                // ax ≡ 1 (mod n) # x is the inverse of a modulo n
    
                // If the remainder is 0 the gcd is n right away.
                uint256 remainder = a % n;
                uint256 gcd = n;
    
                // Therefore the initial coefficients are:
                // ax + ny = gcd(a, n) = n
                // 0a + 1n = n
                int256 x = 0;
                int256 y = 1;
    
                while (remainder != 0) {
                    uint256 quotient = gcd / remainder;
    
                    (gcd, remainder) = (
                        // The old remainder is the next gcd to try.
                        remainder,
                        // Compute the next remainder.
                        // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                        // where gcd is at most n (capped to type(uint256).max)
                        gcd - remainder * quotient
                    );
    
                    (x, y) = (
                        // Increment the coefficient of a.
                        y,
                        // Decrement the coefficient of n.
                        // Can overflow, but the result is casted to uint256 so that the
                        // next value of y is "wrapped around" to a value between 0 and n - 1.
                        x - y * int256(quotient)
                    );
                }
    
                if (gcd != 1) return 0; // No inverse exists.
                return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
            }
        }
    
        /**
         * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
         *
         * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
         * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
         * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
         *
         * NOTE: this function does NOT check that `p` is a prime greater than `2`.
         */
        function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
            unchecked {
                return Math.modExp(a, p - 2, p);
            }
        }
    
        /**
         * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
         *
         * Requirements:
         * - modulus can't be zero
         * - underlying staticcall to precompile must succeed
         *
         * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
         * sure the chain you're using it on supports the precompiled contract for modular exponentiation
         * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
         * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
         * interpreted as 0.
         */
        function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
            (bool success, uint256 result) = tryModExp(b, e, m);
            if (!success) {
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
            return result;
        }
    
        /**
         * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
         * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
         * to operate modulo 0 or if the underlying precompile reverted.
         *
         * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
         * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
         * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
         * of a revert, but the result may be incorrectly interpreted as 0.
         */
        function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
            if (m == 0) return (false, 0);
            assembly ("memory-safe") {
                let ptr := mload(0x40)
                // | Offset    | Content    | Content (Hex)                                                      |
                // |-----------|------------|--------------------------------------------------------------------|
                // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
                // | 0x60:0x7f | value of b | 0x<.............................................................b> |
                // | 0x80:0x9f | value of e | 0x<.............................................................e> |
                // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
                mstore(ptr, 0x20)
                mstore(add(ptr, 0x20), 0x20)
                mstore(add(ptr, 0x40), 0x20)
                mstore(add(ptr, 0x60), b)
                mstore(add(ptr, 0x80), e)
                mstore(add(ptr, 0xa0), m)
    
                // Given the result < m, it's guaranteed to fit in 32 bytes,
                // so we can use the memory scratch space located at offset 0.
                success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
                result := mload(0x00)
            }
        }
    
        /**
         * @dev Variant of {modExp} that supports inputs of arbitrary length.
         */
        function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
            (bool success, bytes memory result) = tryModExp(b, e, m);
            if (!success) {
                Panic.panic(Panic.DIVISION_BY_ZERO);
            }
            return result;
        }
    
        /**
         * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
         */
        function tryModExp(
            bytes memory b,
            bytes memory e,
            bytes memory m
        ) internal view returns (bool success, bytes memory result) {
            if (_zeroBytes(m)) return (false, new bytes(0));
    
            uint256 mLen = m.length;
    
            // Encode call args in result and move the free memory pointer
            result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
    
            assembly ("memory-safe") {
                let dataPtr := add(result, 0x20)
                // Write result on top of args to avoid allocating extra memory.
                success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
                // Overwrite the length.
                // result.length > returndatasize() is guaranteed because returndatasize() == m.length
                mstore(result, mLen)
                // Set the memory pointer after the returned data.
                mstore(0x40, add(dataPtr, mLen))
            }
        }
    
        /**
         * @dev Returns whether the provided byte array is zero.
         */
        function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
            for (uint256 i = 0; i < byteArray.length; ++i) {
                if (byteArray[i] != 0) {
                    return false;
                }
            }
            return true;
        }
    
        /**
         * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
         * towards zero.
         *
         * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
         * using integer operations.
         */
        function sqrt(uint256 a) internal pure returns (uint256) {
            unchecked {
                // Take care of easy edge cases when a == 0 or a == 1
                if (a <= 1) {
                    return a;
                }
    
                // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
                // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
                // the current value as `ε_n = | x_n - sqrt(a) |`.
                //
                // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
                // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
                // bigger than any uint256.
                //
                // By noticing that
                // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
                // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
                // to the msb function.
                uint256 aa = a;
                uint256 xn = 1;
    
                if (aa >= (1 << 128)) {
                    aa >>= 128;
                    xn <<= 64;
                }
                if (aa >= (1 << 64)) {
                    aa >>= 64;
                    xn <<= 32;
                }
                if (aa >= (1 << 32)) {
                    aa >>= 32;
                    xn <<= 16;
                }
                if (aa >= (1 << 16)) {
                    aa >>= 16;
                    xn <<= 8;
                }
                if (aa >= (1 << 8)) {
                    aa >>= 8;
                    xn <<= 4;
                }
                if (aa >= (1 << 4)) {
                    aa >>= 4;
                    xn <<= 2;
                }
                if (aa >= (1 << 2)) {
                    xn <<= 1;
                }
    
                // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
                //
                // We can refine our estimation by noticing that the middle of that interval minimizes the error.
                // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
                // This is going to be our x_0 (and ε_0)
                xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
    
                // From here, Newton's method give us:
                // x_{n+1} = (x_n + a / x_n) / 2
                //
                // One should note that:
                // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
                //              = ((x_n² + a) / (2 * x_n))² - a
                //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
                //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
                //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
                //              = (x_n² - a)² / (2 * x_n)²
                //              = ((x_n² - a) / (2 * x_n))²
                //              ≥ 0
                // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
                //
                // This gives us the proof of quadratic convergence of the sequence:
                // ε_{n+1} = | x_{n+1} - sqrt(a) |
                //         = | (x_n + a / x_n) / 2 - sqrt(a) |
                //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
                //         = | (x_n - sqrt(a))² / (2 * x_n) |
                //         = | ε_n² / (2 * x_n) |
                //         = ε_n² / | (2 * x_n) |
                //
                // For the first iteration, we have a special case where x_0 is known:
                // ε_1 = ε_0² / | (2 * x_0) |
                //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
                //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
                //     ≤ 2**(e-3) / 3
                //     ≤ 2**(e-3-log2(3))
                //     ≤ 2**(e-4.5)
                //
                // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
                // ε_{n+1} = ε_n² / | (2 * x_n) |
                //         ≤ (2**(e-k))² / (2 * 2**(e-1))
                //         ≤ 2**(2*e-2*k) / 2**e
                //         ≤ 2**(e-2*k)
                xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
                xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
                xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
                xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
                xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
                xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72
    
                // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
                // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
                // sqrt(a) or sqrt(a) + 1.
                return xn - SafeCast.toUint(xn > a / xn);
            }
        }
    
        /**
         * @dev Calculates sqrt(a), following the selected rounding direction.
         */
        function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = sqrt(a);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
            }
        }
    
        /**
         * @dev Return the log in base 2 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log2(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            uint256 exp;
            unchecked {
                exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
                value >>= exp;
                result += exp;
    
                exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
                value >>= exp;
                result += exp;
    
                exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
                value >>= exp;
                result += exp;
    
                exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
                value >>= exp;
                result += exp;
    
                exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
                value >>= exp;
                result += exp;
    
                exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
                value >>= exp;
                result += exp;
    
                exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
                value >>= exp;
                result += exp;
    
                result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
            }
        }
    
        /**
         * @dev Return the log in base 10 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         */
        function log10(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            unchecked {
                if (value >= 10 ** 64) {
                    value /= 10 ** 64;
                    result += 64;
                }
                if (value >= 10 ** 32) {
                    value /= 10 ** 32;
                    result += 32;
                }
                if (value >= 10 ** 16) {
                    value /= 10 ** 16;
                    result += 16;
                }
                if (value >= 10 ** 8) {
                    value /= 10 ** 8;
                    result += 8;
                }
                if (value >= 10 ** 4) {
                    value /= 10 ** 4;
                    result += 4;
                }
                if (value >= 10 ** 2) {
                    value /= 10 ** 2;
                    result += 2;
                }
                if (value >= 10 ** 1) {
                    result += 1;
                }
            }
            return result;
        }
    
        /**
         * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
         * Returns 0 if given 0.
         */
        function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
            unchecked {
                uint256 result = log10(value);
                return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
            }
        }
    
        /**
         * @dev Return the log in base 256 of a positive value rounded towards zero.
         * Returns 0 if given 0.
         *
         * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
         */
        function log256(uint256 value) internal pure returns (uint256) {
            uint256 result = 0;
            uint256 isGt;
            unchecked {
                isGt = SafeCast.toUint(value > (1 << 128) - 1);
                value >>= isGt * 128;
                result += isGt * 16;
    
                isGt = SafeCast.toUint(value > (1 << 64) - 1);
                value >>= isGt * 64;
                result += isGt * 8;
    
                isGt = SafeCast.toUint(value > (1 << 32) - 1);
                value >>= isGt * 32;
                result += isGt * 4;
    
                isGt = SafeCast.toUint(value > (1 << 16) - 1);
                value >>= isGt * 16;
                result += isGt * 2;
    
                result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
            }
        }
    
        /**
         * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
         */
        function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
            return uint8(rounding) % 2 == 1;
        }
    }
    
  • @openzeppelin/contracts/utils/math/SafeCast.sol
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
    // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
    
    pragma solidity ^0.8.20;
    
    /**
     * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
     * checks.
     *
     * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
     * easily result in undesired exploitation or bugs, since developers usually
     * assume that overflows raise errors. `SafeCast` restores this intuition by
     * reverting the transaction when such an operation overflows.
     *
     * Using this library instead of the unchecked operations eliminates an entire
     * class of bugs, so it's recommended to use it always.
     */
    library SafeCast {
        /**
         * @dev Value doesn't fit in an uint of `bits` size.
         */
        error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
    
        /**
         * @dev An int value doesn't fit in an uint of `bits` size.
         */
        error SafeCastOverflowedIntToUint(int256 value);
    
        /**
         * @dev Value doesn't fit in an int of `bits` size.
         */
        error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
    
        /**
         * @dev An uint value doesn't fit in an int of `bits` size.
         */
        error SafeCastOverflowedUintToInt(uint256 value);
    
        /**
         * @dev Returns the downcasted uint248 from uint256, reverting on
         * overflow (when the input is greater than largest uint248).
         *
         * Counterpart to Solidity's `uint248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         */
        function toUint248(uint256 value) internal pure returns (uint248) {
            if (value > type(uint248).max) {
                revert SafeCastOverflowedUintDowncast(248, value);
            }
            return uint248(value);
        }
    
        /**
         * @dev Returns the downcasted uint240 from uint256, reverting on
         * overflow (when the input is greater than largest uint240).
         *
         * Counterpart to Solidity's `uint240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         */
        function toUint240(uint256 value) internal pure returns (uint240) {
            if (value > type(uint240).max) {
                revert SafeCastOverflowedUintDowncast(240, value);
            }
            return uint240(value);
        }
    
        /**
         * @dev Returns the downcasted uint232 from uint256, reverting on
         * overflow (when the input is greater than largest uint232).
         *
         * Counterpart to Solidity's `uint232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         */
        function toUint232(uint256 value) internal pure returns (uint232) {
            if (value > type(uint232).max) {
                revert SafeCastOverflowedUintDowncast(232, value);
            }
            return uint232(value);
        }
    
        /**
         * @dev Returns the downcasted uint224 from uint256, reverting on
         * overflow (when the input is greater than largest uint224).
         *
         * Counterpart to Solidity's `uint224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         */
        function toUint224(uint256 value) internal pure returns (uint224) {
            if (value > type(uint224).max) {
                revert SafeCastOverflowedUintDowncast(224, value);
            }
            return uint224(value);
        }
    
        /**
         * @dev Returns the downcasted uint216 from uint256, reverting on
         * overflow (when the input is greater than largest uint216).
         *
         * Counterpart to Solidity's `uint216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         */
        function toUint216(uint256 value) internal pure returns (uint216) {
            if (value > type(uint216).max) {
                revert SafeCastOverflowedUintDowncast(216, value);
            }
            return uint216(value);
        }
    
        /**
         * @dev Returns the downcasted uint208 from uint256, reverting on
         * overflow (when the input is greater than largest uint208).
         *
         * Counterpart to Solidity's `uint208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         */
        function toUint208(uint256 value) internal pure returns (uint208) {
            if (value > type(uint208).max) {
                revert SafeCastOverflowedUintDowncast(208, value);
            }
            return uint208(value);
        }
    
        /**
         * @dev Returns the downcasted uint200 from uint256, reverting on
         * overflow (when the input is greater than largest uint200).
         *
         * Counterpart to Solidity's `uint200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         */
        function toUint200(uint256 value) internal pure returns (uint200) {
            if (value > type(uint200).max) {
                revert SafeCastOverflowedUintDowncast(200, value);
            }
            return uint200(value);
        }
    
        /**
         * @dev Returns the downcasted uint192 from uint256, reverting on
         * overflow (when the input is greater than largest uint192).
         *
         * Counterpart to Solidity's `uint192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         */
        function toUint192(uint256 value) internal pure returns (uint192) {
            if (value > type(uint192).max) {
                revert SafeCastOverflowedUintDowncast(192, value);
            }
            return uint192(value);
        }
    
        /**
         * @dev Returns the downcasted uint184 from uint256, reverting on
         * overflow (when the input is greater than largest uint184).
         *
         * Counterpart to Solidity's `uint184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         */
        function toUint184(uint256 value) internal pure returns (uint184) {
            if (value > type(uint184).max) {
                revert SafeCastOverflowedUintDowncast(184, value);
            }
            return uint184(value);
        }
    
        /**
         * @dev Returns the downcasted uint176 from uint256, reverting on
         * overflow (when the input is greater than largest uint176).
         *
         * Counterpart to Solidity's `uint176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         */
        function toUint176(uint256 value) internal pure returns (uint176) {
            if (value > type(uint176).max) {
                revert SafeCastOverflowedUintDowncast(176, value);
            }
            return uint176(value);
        }
    
        /**
         * @dev Returns the downcasted uint168 from uint256, reverting on
         * overflow (when the input is greater than largest uint168).
         *
         * Counterpart to Solidity's `uint168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         */
        function toUint168(uint256 value) internal pure returns (uint168) {
            if (value > type(uint168).max) {
                revert SafeCastOverflowedUintDowncast(168, value);
            }
            return uint168(value);
        }
    
        /**
         * @dev Returns the downcasted uint160 from uint256, reverting on
         * overflow (when the input is greater than largest uint160).
         *
         * Counterpart to Solidity's `uint160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         */
        function toUint160(uint256 value) internal pure returns (uint160) {
            if (value > type(uint160).max) {
                revert SafeCastOverflowedUintDowncast(160, value);
            }
            return uint160(value);
        }
    
        /**
         * @dev Returns the downcasted uint152 from uint256, reverting on
         * overflow (when the input is greater than largest uint152).
         *
         * Counterpart to Solidity's `uint152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         */
        function toUint152(uint256 value) internal pure returns (uint152) {
            if (value > type(uint152).max) {
                revert SafeCastOverflowedUintDowncast(152, value);
            }
            return uint152(value);
        }
    
        /**
         * @dev Returns the downcasted uint144 from uint256, reverting on
         * overflow (when the input is greater than largest uint144).
         *
         * Counterpart to Solidity's `uint144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         */
        function toUint144(uint256 value) internal pure returns (uint144) {
            if (value > type(uint144).max) {
                revert SafeCastOverflowedUintDowncast(144, value);
            }
            return uint144(value);
        }
    
        /**
         * @dev Returns the downcasted uint136 from uint256, reverting on
         * overflow (when the input is greater than largest uint136).
         *
         * Counterpart to Solidity's `uint136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         */
        function toUint136(uint256 value) internal pure returns (uint136) {
            if (value > type(uint136).max) {
                revert SafeCastOverflowedUintDowncast(136, value);
            }
            return uint136(value);
        }
    
        /**
         * @dev Returns the downcasted uint128 from uint256, reverting on
         * overflow (when the input is greater than largest uint128).
         *
         * Counterpart to Solidity's `uint128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         */
        function toUint128(uint256 value) internal pure returns (uint128) {
            if (value > type(uint128).max) {
                revert SafeCastOverflowedUintDowncast(128, value);
            }
            return uint128(value);
        }
    
        /**
         * @dev Returns the downcasted uint120 from uint256, reverting on
         * overflow (when the input is greater than largest uint120).
         *
         * Counterpart to Solidity's `uint120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         */
        function toUint120(uint256 value) internal pure returns (uint120) {
            if (value > type(uint120).max) {
                revert SafeCastOverflowedUintDowncast(120, value);
            }
            return uint120(value);
        }
    
        /**
         * @dev Returns the downcasted uint112 from uint256, reverting on
         * overflow (when the input is greater than largest uint112).
         *
         * Counterpart to Solidity's `uint112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         */
        function toUint112(uint256 value) internal pure returns (uint112) {
            if (value > type(uint112).max) {
                revert SafeCastOverflowedUintDowncast(112, value);
            }
            return uint112(value);
        }
    
        /**
         * @dev Returns the downcasted uint104 from uint256, reverting on
         * overflow (when the input is greater than largest uint104).
         *
         * Counterpart to Solidity's `uint104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         */
        function toUint104(uint256 value) internal pure returns (uint104) {
            if (value > type(uint104).max) {
                revert SafeCastOverflowedUintDowncast(104, value);
            }
            return uint104(value);
        }
    
        /**
         * @dev Returns the downcasted uint96 from uint256, reverting on
         * overflow (when the input is greater than largest uint96).
         *
         * Counterpart to Solidity's `uint96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         */
        function toUint96(uint256 value) internal pure returns (uint96) {
            if (value > type(uint96).max) {
                revert SafeCastOverflowedUintDowncast(96, value);
            }
            return uint96(value);
        }
    
        /**
         * @dev Returns the downcasted uint88 from uint256, reverting on
         * overflow (when the input is greater than largest uint88).
         *
         * Counterpart to Solidity's `uint88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         */
        function toUint88(uint256 value) internal pure returns (uint88) {
            if (value > type(uint88).max) {
                revert SafeCastOverflowedUintDowncast(88, value);
            }
            return uint88(value);
        }
    
        /**
         * @dev Returns the downcasted uint80 from uint256, reverting on
         * overflow (when the input is greater than largest uint80).
         *
         * Counterpart to Solidity's `uint80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         */
        function toUint80(uint256 value) internal pure returns (uint80) {
            if (value > type(uint80).max) {
                revert SafeCastOverflowedUintDowncast(80, value);
            }
            return uint80(value);
        }
    
        /**
         * @dev Returns the downcasted uint72 from uint256, reverting on
         * overflow (when the input is greater than largest uint72).
         *
         * Counterpart to Solidity's `uint72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         */
        function toUint72(uint256 value) internal pure returns (uint72) {
            if (value > type(uint72).max) {
                revert SafeCastOverflowedUintDowncast(72, value);
            }
            return uint72(value);
        }
    
        /**
         * @dev Returns the downcasted uint64 from uint256, reverting on
         * overflow (when the input is greater than largest uint64).
         *
         * Counterpart to Solidity's `uint64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         */
        function toUint64(uint256 value) internal pure returns (uint64) {
            if (value > type(uint64).max) {
                revert SafeCastOverflowedUintDowncast(64, value);
            }
            return uint64(value);
        }
    
        /**
         * @dev Returns the downcasted uint56 from uint256, reverting on
         * overflow (when the input is greater than largest uint56).
         *
         * Counterpart to Solidity's `uint56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         */
        function toUint56(uint256 value) internal pure returns (uint56) {
            if (value > type(uint56).max) {
                revert SafeCastOverflowedUintDowncast(56, value);
            }
            return uint56(value);
        }
    
        /**
         * @dev Returns the downcasted uint48 from uint256, reverting on
         * overflow (when the input is greater than largest uint48).
         *
         * Counterpart to Solidity's `uint48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         */
        function toUint48(uint256 value) internal pure returns (uint48) {
            if (value > type(uint48).max) {
                revert SafeCastOverflowedUintDowncast(48, value);
            }
            return uint48(value);
        }
    
        /**
         * @dev Returns the downcasted uint40 from uint256, reverting on
         * overflow (when the input is greater than largest uint40).
         *
         * Counterpart to Solidity's `uint40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         */
        function toUint40(uint256 value) internal pure returns (uint40) {
            if (value > type(uint40).max) {
                revert SafeCastOverflowedUintDowncast(40, value);
            }
            return uint40(value);
        }
    
        /**
         * @dev Returns the downcasted uint32 from uint256, reverting on
         * overflow (when the input is greater than largest uint32).
         *
         * Counterpart to Solidity's `uint32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         */
        function toUint32(uint256 value) internal pure returns (uint32) {
            if (value > type(uint32).max) {
                revert SafeCastOverflowedUintDowncast(32, value);
            }
            return uint32(value);
        }
    
        /**
         * @dev Returns the downcasted uint24 from uint256, reverting on
         * overflow (when the input is greater than largest uint24).
         *
         * Counterpart to Solidity's `uint24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         */
        function toUint24(uint256 value) internal pure returns (uint24) {
            if (value > type(uint24).max) {
                revert SafeCastOverflowedUintDowncast(24, value);
            }
            return uint24(value);
        }
    
        /**
         * @dev Returns the downcasted uint16 from uint256, reverting on
         * overflow (when the input is greater than largest uint16).
         *
         * Counterpart to Solidity's `uint16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         */
        function toUint16(uint256 value) internal pure returns (uint16) {
            if (value > type(uint16).max) {
                revert SafeCastOverflowedUintDowncast(16, value);
            }
            return uint16(value);
        }
    
        /**
         * @dev Returns the downcasted uint8 from uint256, reverting on
         * overflow (when the input is greater than largest uint8).
         *
         * Counterpart to Solidity's `uint8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         */
        function toUint8(uint256 value) internal pure returns (uint8) {
            if (value > type(uint8).max) {
                revert SafeCastOverflowedUintDowncast(8, value);
            }
            return uint8(value);
        }
    
        /**
         * @dev Converts a signed int256 into an unsigned uint256.
         *
         * Requirements:
         *
         * - input must be greater than or equal to 0.
         */
        function toUint256(int256 value) internal pure returns (uint256) {
            if (value < 0) {
                revert SafeCastOverflowedIntToUint(value);
            }
            return uint256(value);
        }
    
        /**
         * @dev Returns the downcasted int248 from int256, reverting on
         * overflow (when the input is less than smallest int248 or
         * greater than largest int248).
         *
         * Counterpart to Solidity's `int248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         */
        function toInt248(int256 value) internal pure returns (int248 downcasted) {
            downcasted = int248(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(248, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int240 from int256, reverting on
         * overflow (when the input is less than smallest int240 or
         * greater than largest int240).
         *
         * Counterpart to Solidity's `int240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         */
        function toInt240(int256 value) internal pure returns (int240 downcasted) {
            downcasted = int240(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(240, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int232 from int256, reverting on
         * overflow (when the input is less than smallest int232 or
         * greater than largest int232).
         *
         * Counterpart to Solidity's `int232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         */
        function toInt232(int256 value) internal pure returns (int232 downcasted) {
            downcasted = int232(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(232, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int224 from int256, reverting on
         * overflow (when the input is less than smallest int224 or
         * greater than largest int224).
         *
         * Counterpart to Solidity's `int224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         */
        function toInt224(int256 value) internal pure returns (int224 downcasted) {
            downcasted = int224(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(224, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int216 from int256, reverting on
         * overflow (when the input is less than smallest int216 or
         * greater than largest int216).
         *
         * Counterpart to Solidity's `int216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         */
        function toInt216(int256 value) internal pure returns (int216 downcasted) {
            downcasted = int216(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(216, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int208 from int256, reverting on
         * overflow (when the input is less than smallest int208 or
         * greater than largest int208).
         *
         * Counterpart to Solidity's `int208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         */
        function toInt208(int256 value) internal pure returns (int208 downcasted) {
            downcasted = int208(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(208, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int200 from int256, reverting on
         * overflow (when the input is less than smallest int200 or
         * greater than largest int200).
         *
         * Counterpart to Solidity's `int200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         */
        function toInt200(int256 value) internal pure returns (int200 downcasted) {
            downcasted = int200(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(200, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int192 from int256, reverting on
         * overflow (when the input is less than smallest int192 or
         * greater than largest int192).
         *
         * Counterpart to Solidity's `int192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         */
        function toInt192(int256 value) internal pure returns (int192 downcasted) {
            downcasted = int192(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(192, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int184 from int256, reverting on
         * overflow (when the input is less than smallest int184 or
         * greater than largest int184).
         *
         * Counterpart to Solidity's `int184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         */
        function toInt184(int256 value) internal pure returns (int184 downcasted) {
            downcasted = int184(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(184, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int176 from int256, reverting on
         * overflow (when the input is less than smallest int176 or
         * greater than largest int176).
         *
         * Counterpart to Solidity's `int176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         */
        function toInt176(int256 value) internal pure returns (int176 downcasted) {
            downcasted = int176(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(176, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int168 from int256, reverting on
         * overflow (when the input is less than smallest int168 or
         * greater than largest int168).
         *
         * Counterpart to Solidity's `int168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         */
        function toInt168(int256 value) internal pure returns (int168 downcasted) {
            downcasted = int168(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(168, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int160 from int256, reverting on
         * overflow (when the input is less than smallest int160 or
         * greater than largest int160).
         *
         * Counterpart to Solidity's `int160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         */
        function toInt160(int256 value) internal pure returns (int160 downcasted) {
            downcasted = int160(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(160, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int152 from int256, reverting on
         * overflow (when the input is less than smallest int152 or
         * greater than largest int152).
         *
         * Counterpart to Solidity's `int152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         */
        function toInt152(int256 value) internal pure returns (int152 downcasted) {
            downcasted = int152(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(152, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int144 from int256, reverting on
         * overflow (when the input is less than smallest int144 or
         * greater than largest int144).
         *
         * Counterpart to Solidity's `int144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         */
        function toInt144(int256 value) internal pure returns (int144 downcasted) {
            downcasted = int144(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(144, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int136 from int256, reverting on
         * overflow (when the input is less than smallest int136 or
         * greater than largest int136).
         *
         * Counterpart to Solidity's `int136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         */
        function toInt136(int256 value) internal pure returns (int136 downcasted) {
            downcasted = int136(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(136, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int128 from int256, reverting on
         * overflow (when the input is less than smallest int128 or
         * greater than largest int128).
         *
         * Counterpart to Solidity's `int128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         */
        function toInt128(int256 value) internal pure returns (int128 downcasted) {
            downcasted = int128(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(128, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int120 from int256, reverting on
         * overflow (when the input is less than smallest int120 or
         * greater than largest int120).
         *
         * Counterpart to Solidity's `int120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         */
        function toInt120(int256 value) internal pure returns (int120 downcasted) {
            downcasted = int120(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(120, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int112 from int256, reverting on
         * overflow (when the input is less than smallest int112 or
         * greater than largest int112).
         *
         * Counterpart to Solidity's `int112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         */
        function toInt112(int256 value) internal pure returns (int112 downcasted) {
            downcasted = int112(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(112, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int104 from int256, reverting on
         * overflow (when the input is less than smallest int104 or
         * greater than largest int104).
         *
         * Counterpart to Solidity's `int104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         */
        function toInt104(int256 value) internal pure returns (int104 downcasted) {
            downcasted = int104(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(104, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int96 from int256, reverting on
         * overflow (when the input is less than smallest int96 or
         * greater than largest int96).
         *
         * Counterpart to Solidity's `int96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         */
        function toInt96(int256 value) internal pure returns (int96 downcasted) {
            downcasted = int96(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(96, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int88 from int256, reverting on
         * overflow (when the input is less than smallest int88 or
         * greater than largest int88).
         *
         * Counterpart to Solidity's `int88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         */
        function toInt88(int256 value) internal pure returns (int88 downcasted) {
            downcasted = int88(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(88, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int80 from int256, reverting on
         * overflow (when the input is less than smallest int80 or
         * greater than largest int80).
         *
         * Counterpart to Solidity's `int80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         */
        function toInt80(int256 value) internal pure returns (int80 downcasted) {
            downcasted = int80(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(80, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int72 from int256, reverting on
         * overflow (when the input is less than smallest int72 or
         * greater than largest int72).
         *
         * Counterpart to Solidity's `int72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         */
        function toInt72(int256 value) internal pure returns (int72 downcasted) {
            downcasted = int72(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(72, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int64 from int256, reverting on
         * overflow (when the input is less than smallest int64 or
         * greater than largest int64).
         *
         * Counterpart to Solidity's `int64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         */
        function toInt64(int256 value) internal pure returns (int64 downcasted) {
            downcasted = int64(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(64, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int56 from int256, reverting on
         * overflow (when the input is less than smallest int56 or
         * greater than largest int56).
         *
         * Counterpart to Solidity's `int56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         */
        function toInt56(int256 value) internal pure returns (int56 downcasted) {
            downcasted = int56(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(56, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int48 from int256, reverting on
         * overflow (when the input is less than smallest int48 or
         * greater than largest int48).
         *
         * Counterpart to Solidity's `int48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         */
        function toInt48(int256 value) internal pure returns (int48 downcasted) {
            downcasted = int48(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(48, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int40 from int256, reverting on
         * overflow (when the input is less than smallest int40 or
         * greater than largest int40).
         *
         * Counterpart to Solidity's `int40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         */
        function toInt40(int256 value) internal pure returns (int40 downcasted) {
            downcasted = int40(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(40, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int32 from int256, reverting on
         * overflow (when the input is less than smallest int32 or
         * greater than largest int32).
         *
         * Counterpart to Solidity's `int32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         */
        function toInt32(int256 value) internal pure returns (int32 downcasted) {
            downcasted = int32(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(32, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int24 from int256, reverting on
         * overflow (when the input is less than smallest int24 or
         * greater than largest int24).
         *
         * Counterpart to Solidity's `int24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         */
        function toInt24(int256 value) internal pure returns (int24 downcasted) {
            downcasted = int24(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(24, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int16 from int256, reverting on
         * overflow (when the input is less than smallest int16 or
         * greater than largest int16).
         *
         * Counterpart to Solidity's `int16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         */
        function toInt16(int256 value) internal pure returns (int16 downcasted) {
            downcasted = int16(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(16, value);
            }
        }
    
        /**
         * @dev Returns the downcasted int8 from int256, reverting on
         * overflow (when the input is less than smallest int8 or
         * greater than largest int8).
         *
         * Counterpart to Solidity's `int8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         */
        function toInt8(int256 value) internal pure returns (int8 downcasted) {
            downcasted = int8(value);
            if (downcasted != value) {
                revert SafeCastOverflowedIntDowncast(8, value);
            }
        }
    
        /**
         * @dev Converts an unsigned uint256 into a signed int256.
         *
         * Requirements:
         *
         * - input must be less than or equal to maxInt256.
         */
        function toInt256(uint256 value) internal pure returns (int256) {
            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
            if (value > uint256(type(int256).max)) {
                revert SafeCastOverflowedUintToInt(value);
            }
            return int256(value);
        }
    
        /**
         * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
         */
        function toUint(bool b) internal pure returns (uint256 u) {
            assembly ("memory-safe") {
                u := iszero(iszero(b))
            }
        }
    }
    
  • contracts/CoreLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./LibErrors.sol";
    
    /**
     * @title CoreLib
     * @notice Core library for metadata and string validation functions
     * @dev Contains constants and utility functions used across the application
     */
    library CoreLib {
        uint256 internal constant MAX_METADATA_KEYS = 99;
        uint256 internal constant MAX_METADATA_VALUES = 99;
        uint256 internal constant MAX_PLAYERS_PER_MATCH = 9_999;
        uint256 internal constant MAX_VERIFIED_ADDRESSES = 99;
        uint256 internal constant MAX_VERIFIED_IDS = 99;
        uint256 internal constant MAX_CONTRACTS = 99;
        uint256 private constant MAX_STRING_LENGTH = 512;
    
        /**
         * @notice Validates a string in calldata
         * @param s The string to validate
         * @dev Reverts if string is empty or exceeds maximum length
         */
        function validateStringCalldata(string calldata s) internal pure {
            uint256 len = bytes(s).length;
            if (len == 0) revert EmptyString();
            if (len > MAX_STRING_LENGTH) revert TooManyItems();
        }
    
        /**
         * @notice Validates a string in memory
         * @param s The string to validate
         * @dev Reverts if string is empty or exceeds maximum length
         */
        function validateStringMemory(string memory s) internal pure {
            uint256 len = bytes(s).length;
            if (len == 0) revert EmptyString();
            if (len > MAX_STRING_LENGTH) revert TooManyItems();
        }
    
        function addMetadata(
            DataTypes.MetaData storage metadata,
            string calldata key,
            string calldata value
        ) internal returns (uint256 index) {
            validateStringCalldata(key);
            validateStringCalldata(value);
    
            bytes32 keyHash = keccak256(bytes(key));
    
            for (uint256 i = 0; i < metadata.key.length; ++i) {
                if (keccak256(bytes(metadata.key[i])) == keyHash) {
                    // Overwrite value
                    metadata.values[i] = value;
                    return i;
                }
            }
    
            // New entry
            if (metadata.key.length >= MAX_METADATA_KEYS) revert TooManyItems();
            metadata.key.push(key);
            metadata.values.push(value);
            return metadata.key.length - 1;
        }
    }
    
  • contracts/DataTypes.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    library DataTypes {
        enum Device {
            iOS,
            Android,
            WebGL,
            PC,
            Console,
            Other,
            Last
        }
    
        enum WinLoss {
            Win,
            Loss,
            Forfeit,
            Draw,
            NotSet,
            Fail,
            Last
        }
    
        enum PlayerType {
            Human,
            NPC,
            Last
        }
    
        struct BaseData {
            uint256 id;
            uint256 startTime;
            uint256 endTime;
            uint256 applicationId;
        }
    
        struct MetaData {
            string[] key;
            string[] values;
        }
    
        struct LoginSession {
            BaseData baseData;
            MetaData metadata;
            Device device;
            uint256 playerIndex;
            uint256[] matchIds;
        }
    
        struct Player {
            string playerID;
            address playerAddress;
            PlayerType playerType;
            int256 totalScore;
            string[] verifiedIdKey;
            string[] verifiedIdValue;
            address[] verifiedAddresses;
            MetaData metadata;
        }
    
        struct MatchSession {
            BaseData baseData;
            MetaData metadata;
            bool multiplayer;
            uint256[] playerIds;
            uint256[] playData;
            string level;
        }
    
        struct PlayData {
            BaseData baseData;
            uint256 playerIndex;
            int256 score;
            WinLoss winLoss;
            int256 matchPosition;
            uint256[] records;
        }
    
        struct Records {
            uint256 id;
            string key;
            string value;
            int256 score;
            uint256 startTime;
            uint256 playerIndex;
            uint256[] otherPlayer;
            uint256 playDataId;
        }
    
        struct ApplicationRecord {
            string applicationVersion;
            string companyName;
            address[] contractAddresses;
        }
    
        struct Application {
            string name;
            address owner;
        }
    
        struct RecordInput {
        uint256 matchId;
        uint256 playerIndex;
        int256 score;
        string key;
        string value;
        uint256[] otherPlayers;
        uint256 startTime;
        }
    
    }
  • contracts/EntityLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./CoreLib.sol";
    import "./LibErrors.sol";
    
    /**
     * @title EntityLib
     * @notice Library for managing player entities and application records
     * @dev Provides functions for player creation, identifier management, and application data
     */
    library EntityLib {
    
        /*-------------  helpers -------------*/
    
        /**
         * @notice Gets a player's index from their unique ID
         * @param playerByUniqueId Mapping from player ID to index
         * @param playerID The unique ID of the player
         * @return idx The index of the player (0-based)
         * @dev Reverts if player ID is empty or not found
         */
        function _getPlayerIndex(
            mapping(string => uint256) storage playerByUniqueId,
            string memory playerID
        ) internal view returns (uint256 idx) {
            if (bytes(playerID).length == 0) revert EmptyString();
            uint256 stored = playerByUniqueId[playerID];
            if (stored == 0) revert NotFound();          // not registered
            return stored - 1;                           // convert 1‑based → 0‑based
        }
    
        /**
         * @notice Gets a player's unique ID from their index
         * @param _players Array of player structs
         * @param _playerIndex The index of the player
         * @return The unique ID of the player
         * @dev Reverts if player index is out of bounds
         */
        function _getPlayerUniqueId(
            DataTypes.Player[] storage _players,
            uint256 _playerIndex
        ) internal view returns (string memory) {
            if (_playerIndex >= _players.length) revert IndexOutOfBounds();
            return _players[_playerIndex].playerID;
        }
    
        /*-------------  player creation -------------*/
    
        /**
         * @notice Creates a new player
         * @param _players Array of player structs
         * @param _playerByUniqueId Mapping from player ID to index
         * @param _playersByAddress Mapping from player address to index
         * @param _playerID The unique ID for the new player
         * @param _playerType The type of player (Human, NPC)
         * @param _playerAddress The blockchain address of the player
         * @return playerIndex The index of the created player
         * @dev Reverts if:
         *      - Player ID is empty or invalid
         *      - Player type is invalid
         *      - Player address is zero
         *      - Player ID already exists
         */
        function createPlayer(
            DataTypes.Player[] storage _players,
            mapping(string => uint256) storage _playerByUniqueId,
            mapping(address => uint256) storage _playersByAddress,
            string calldata _playerID,
            DataTypes.PlayerType _playerType,
            address _playerAddress
        ) internal returns (uint256 playerIndex) {
    
            CoreLib.validateStringCalldata(_playerID);
            if (_playerType >= DataTypes.PlayerType.Last) revert IndexOutOfBounds();
            if (_playerAddress == address(0)) revert ZeroAddress();
            if (_playerByUniqueId[_playerID] != 0) revert AlreadyExists();
    
            playerIndex = _players.length;
            _players.push();
    
            DataTypes.Player storage p = _players[playerIndex];
            p.playerID     = _playerID;
            p.playerType   = _playerType;
            p.playerAddress= _playerAddress;
    
            _playerByUniqueId[_playerID]   = playerIndex + 1;
            _playersByAddress[_playerAddress] = playerIndex + 1;
        }
    
        /*-------------  identifiers -------------*/
    
        /**
         * @notice Adds or updates an identifier for a player
         * @param _players Array of player structs
         * @param _playerIndex The index of the player
         * @param _identifierType The type of identifier
         * @param _identifierValue The value of the identifier
         * @dev Reverts if:
         *      - Identifier type or value is empty or invalid
         *      - Player index is out of bounds
         *      - Maximum number of identifiers exceeded
         */
        function addPlayerIdentifier(
            DataTypes.Player[] storage _players,
            uint256 _playerIndex,
            string calldata _identifierType,
            string calldata _identifierValue
        ) internal {
            CoreLib.validateStringCalldata(_identifierType);
            CoreLib.validateStringCalldata(_identifierValue);
    
            if (_playerIndex >= _players.length) revert IndexOutOfBounds();
            DataTypes.Player storage p = _players[_playerIndex];
    
            if (p.verifiedIdKey.length >= CoreLib.MAX_VERIFIED_IDS)
                revert TooManyItems();
    
            bytes32 idHash = keccak256(bytes(_identifierType));
            for (uint256 i; i < p.verifiedIdKey.length; ++i) {
                if (keccak256(bytes(p.verifiedIdKey[i])) == idHash) {
                    // update existing value
                    p.verifiedIdValue[i] = _identifierValue;
                    return;
                }
            }
    
            // add new
            p.verifiedIdKey.push(_identifierType);
            p.verifiedIdValue.push(_identifierValue);
        }
    
        /*-------------  verified addresses -------------*/
    
        /**
         * @notice Adds a verified address to a player
         * @param _players Array of player structs
         * @param _playerIndex The index of the player
         * @param _verifiedAddress The address to verify for the player
         * @dev Reverts if:
         *      - Address is zero
         *      - Player index is out of bounds
         *      - Maximum number of verified addresses exceeded
         *      - Address already verified for this player
         */
        function addVerifiedAddress(
            DataTypes.Player[] storage _players,
            uint256 _playerIndex,
            address _verifiedAddress
        ) internal {
            if (_verifiedAddress == address(0)) revert ZeroAddress();
            if (_playerIndex >= _players.length) revert IndexOutOfBounds();
    
            DataTypes.Player storage p = _players[_playerIndex];
    
            if (p.verifiedAddresses.length >= CoreLib.MAX_VERIFIED_ADDRESSES)
                revert TooManyItems();
    
            for (uint256 i; i < p.verifiedAddresses.length; ++i)
                if (p.verifiedAddresses[i] == _verifiedAddress)
                    revert AlreadyExists();
    
            p.verifiedAddresses.push(_verifiedAddress);
        }
    
        /*-------------  application -------------*/
    
        /**
         * @notice Sets application details
         * @param _app Application storage reference
         * @param _name The name of the application
         * @param _owner The owner address of the application
         * @dev Reverts if name is empty or invalid
         */
        function setApplication(
            DataTypes.Application storage _app,
            string calldata _name,
            address _owner
        ) internal {
            CoreLib.validateStringCalldata(_name);
            _app.name  = _name;
            _app.owner = _owner;
        }
    
        /**
         * @notice Creates a new application record
         * @param records Array of application records
         * @param _version The version of the application
         * @param _company The company name
         * @param _contracts Array of contract addresses
         * @return id The ID of the created application record
         * @dev Reverts if:
         *      - Version or company name is empty or invalid
         *      - Too many contracts provided
         *      - Any contract address is zero
         */
        function createApplicationRecord(
            DataTypes.ApplicationRecord[] storage records,
            string calldata _version,
            string calldata _company,
            address[] calldata _contracts
        ) internal returns (uint256 id) {
            CoreLib.validateStringCalldata(_version);
            CoreLib.validateStringCalldata(_company);
    
            if (_contracts.length > CoreLib.MAX_CONTRACTS) revert TooManyItems();
    
            id = records.length;
            records.push();
    
            DataTypes.ApplicationRecord storage r = records[id];
            r.applicationVersion = _version;
            r.companyName        = _company;
            r.contractAddresses  = _validateAddresses(_contracts);
        }
    
        /**
         * @notice Updates contract addresses for an application record
         * @param records Array of application records
         * @param id The ID of the application record
         * @param _contracts New array of contract addresses
         * @dev Reverts if:
         *      - ID is out of bounds
         *      - Contracts array is empty
         *      - Too many contracts provided
         *      - Any contract address is zero
         */
        function updateApplicationRecordAddresses(
            DataTypes.ApplicationRecord[] storage records,
            uint256 id,
            address[] calldata _contracts
        ) internal {
            if (id >= records.length) revert IndexOutOfBounds();
            if (_contracts.length == 0)  revert ZeroAddress();      // empty list
            if (_contracts.length > CoreLib.MAX_CONTRACTS) revert TooManyItems();
    
            records[id].contractAddresses = _validateAddresses(_contracts);
        }
    
        /*-------------  helpers -------------*/
    
        /**
         * @notice Validates an array of addresses
         * @param arr Array of addresses to validate
         * @return out The validated array of addresses
         * @dev Reverts if any address is zero
         */
        function _validateAddresses(
            address[] calldata arr
        ) private pure returns (address[] memory out) {
            for (uint256 i; i < arr.length; ++i)
                if (arr[i] == address(0)) revert ZeroAddress();
    
            return arr; // dynamic‑to‑memory copy happens automatically
        }
    
        /*-------------  metadata -------------*/
    
        // /**
        //  * @notice Sets metadata for an application record
        //  * @param records Array of application records
        //  * @param id The ID of the application record
        //  * @param key The metadata key
        //  * @param value The metadata value
        //  * @dev Reverts if:
        //  *      - ID is out of bounds
        //  *      - Key or value is empty or invalid
        //  *      - Maximum metadata keys or values exceeded
        //  *      - Value already exists for the key
        //  */
        // function setApplicationRecordMetadata(
        //     DataTypes.ApplicationRecord[] storage records,
        //     uint256 id,
        //     string calldata key,
        //     string calldata value
        // ) internal {
        //     if (id >= records.length) revert IndexOutOfBounds();
        //     CoreLib.addMetadata(records[id].metadata, key, value);
        // }
    }
    
    
  • contracts/LibErrors.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    /**
     * @notice Error thrown when an index is out of the valid range
     */
    error IndexOutOfBounds();
    
    /**
     * @notice Error thrown when an invalid time value is provided
     */
    error InvalidTime();
    
    /**
     * @notice Error thrown when attempting to modify a match that has already ended
     */
    error MatchAlreadyEnded();
    
    /**
     * @notice Error thrown when attempting to modify a match that is finished
     */
    error MatchFinished();
    
    /**
     * @notice Error thrown when an empty array is provided where a non-empty one is required
     */
    error EmptyArray();
    
    /**
     * @notice Error thrown when too many players are added to a match
     */
    error TooManyPlayers();
    
    /**
     * @notice Error thrown when attempting to add a duplicate player to a match
     */
    error DuplicatePlayer();
    
    /**
     * @notice Error thrown when a match has reached its maximum capacity
     */
    error MatchFull();
    
    /**
     * @notice Error thrown when attempting to add a player who is already in a match
     */
    error PlayerAlreadyInMatch();
    
    /**
     * @notice Error thrown when a zero address is provided where a non-zero address is required
     */
    error ZeroAddress();          
    
    /**
     * @notice Error thrown when an empty string is provided where a non-empty string is required
     */
    error EmptyString(); 
    
    /**
     * @notice Error thrown when attempting to add an item that already exists
     */
    error AlreadyExists();
    
    /**
     * @notice Error thrown when a collection has reached its maximum capacity
     */
    error TooManyItems();
    
    /**
     * @notice Error thrown when a requested item cannot be found
     */
    error NotFound();
    
    /**
     * @notice Error thrown when an invalid value or parameter is provided
     */
    error Invalid();
    
  • contracts/MatchLibPlayer.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./CoreLib.sol";
    import "./LibErrors.sol"; // brings `Invalid` into scope
    
    /**
     * @title MatchLibPlayer
     * @notice Library for managing player data in matches
     * @dev Provides functions for creating and updating player data in match contexts
     */
    library MatchLibPlayer {
    
        /**
         * @notice Creates player data for a match
         * @param playerDatas Storage array of player data
         * @param _playerIndex Index of the player
         * @param _applicationId ID of the application
         * @param _startTime Start time of the player's participation
         * @return playerDataId ID of the created player data
         * @dev Reverts if start time is 0
         */
        function createPlayerData(
            DataTypes.PlayData[] storage playerDatas,
            uint256 _playerIndex,
            uint256 _applicationId,
            uint256 _startTime
        ) internal returns (uint256 playerDataId) {
            if (_startTime == 0) revert Invalid();
    
            playerDataId = playerDatas.length;
            DataTypes.PlayData storage pd = playerDatas.push();
    
            pd.baseData.id = playerDataId;
            pd.baseData.startTime = _startTime;
            pd.baseData.applicationId = _applicationId;
    
            pd.playerIndex = _playerIndex;
            pd.winLoss = DataTypes.WinLoss.NotSet;
        }
    
    
        /**
         * @notice Updates player data for a match
         * @param _playDataId ID of the player data to update
         * @param playerDatas Storage array of player data
         * @param _endTime End time of the player's participation
         * @param _score Player's score
         * @param _winLoss Win/loss status
         * @param _matchPosition Player's position in the match
         * @return playDataId ID of the updated player data
         * @return playerIndex Index of the player
         * @dev Reverts if:
         *      - Play data ID is out of bounds
         *      - Win/loss value is invalid
         *      - End time is 0
         *      - End time is before or equal to start time
         */
        function updatePlayerData(
            uint256 _playDataId,
            DataTypes.PlayData[] storage playerDatas,
            uint256 _endTime,
            int256 _score,
            DataTypes.WinLoss _winLoss,
            int256 _matchPosition
        ) internal returns (uint256 playDataId, uint256 playerIndex) {
            if (
                _playDataId >= playerDatas.length ||
                _winLoss >= DataTypes.WinLoss.Last ||
                _endTime == 0
            ) {
                revert Invalid();
            }
    
            DataTypes.PlayData storage pd = playerDatas[_playDataId];
    
            if (_endTime <= pd.baseData.startTime) revert Invalid();
    
            pd.baseData.endTime = _endTime;
            pd.score = _score;
            pd.winLoss = _winLoss;
            pd.matchPosition = _matchPosition;
    
            return (_playDataId, pd.playerIndex);
        }
    
    
        // /**
        //  * @notice Adds metadata to player data
        //  * @param playDatas Storage array of player data
        //  * @param _playDataId ID of the player data
        //  * @param _key Metadata key
        //  * @param _value Metadata value
        //  * @return keyIndex Index of the key in the metadata
        //  * @dev Reverts if:
        //  *      - Play data ID is out of bounds
        //  *      - Key or value is empty or invalid
        //  *      - Maximum metadata keys or values exceeded
        //  *      - Value already exists for the key
        //  */
        // function addPlayDataMetadata(
        //     DataTypes.PlayData[] storage playDatas,
        //     uint256 _playDataId,
        //     string calldata _key,
        //     string calldata _value
        // ) internal returns (uint256 keyIndex) {
        //     if (_playDataId >= playDatas.length) revert Invalid();
    
        //     DataTypes.PlayData storage pd = playDatas[_playDataId];
        //     return CoreLib.addMetadata(pd.metadata, _key, _value);
        // }
    }
    
  • contracts/MatchSessionLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./CoreLib.sol";
    import "./MatchLibPlayer.sol";
    import "./LibErrors.sol";
    
    /**
     * @title MatchLibSession
     * @notice Library for managing match sessions
     * @dev Provides functions for creating, ending, and modifying match sessions
     */
    library MatchLibSession {
    
        /**
         * @notice Starts a new match session
         * @param activeMatchSessions Storage array of active match session IDs
         * @param loginSessions Storage array of login sessions
         * @param matchSessions Storage array of match sessions
         * @param playData Storage array of player data
         * @param applicationId ID of the application
         * @param startTime Start time of the match
         * @param multiplayer Whether the match is multiplayer
         * @param playerIndices Array of player indices participating in the match
         * @param level The level/map identifier for the match
         * @return matchSessionId ID of the created match session
         * @dev Reverts if:
         *      - Player array is empty
         *      - Too many players for a single match
         *      - Start time is 0
         *      - Level string is empty or invalid
         *      - Duplicate players are detected
         */
        function startMatchSession(
            uint256[] storage activeMatchSessions,
            DataTypes.LoginSession[] storage loginSessions,
            DataTypes.MatchSession[] storage matchSessions,
            DataTypes.PlayData[] storage playData,
            uint256 applicationId,
            uint256 startTime,
            bool multiplayer,
            uint256[] memory playerIndices,
            string memory level
        ) internal returns (uint256 matchSessionId) {
            uint256 playerCount = playerIndices.length;
            if (playerCount == 0) revert EmptyArray();
            if (playerCount > CoreLib.MAX_PLAYERS_PER_MATCH)
                revert TooManyPlayers();
            if (startTime == 0) revert InvalidTime();
    
            CoreLib.validateStringMemory(level);
    
            /* create session --------------------------------------------------------- */
            matchSessionId = matchSessions.length;
            DataTypes.MatchSession storage ms = matchSessions.push();
    
            ms.baseData.id = matchSessionId;
            ms.baseData.startTime = startTime;
            ms.baseData.applicationId = applicationId;
            ms.multiplayer = multiplayer;
            ms.level = level;
    
            ms.playData = new uint256[](playerCount);
            ms.playerIds = new uint256[](playerCount);
    
            /* uniqueness check ------------------------------------------------------- */
            unchecked {
                for (uint256 i; i < playerCount - 1; ++i) {
                    for (uint256 j = i + 1; j < playerCount; ++j)
                        if (playerIndices[i] == playerIndices[j])
                            revert DuplicatePlayer();
                }
            }
    
            /* create play‑data ------------------------------------------------------- */
            unchecked {
                for (uint256 i; i < playerCount; ++i) {
                    uint256 pIdx = playerIndices[i];
    
                    ms.playerIds[i] = pIdx;
                    ms.playData[i] = MatchLibPlayer.createPlayerData(
                        playData,
                        pIdx,
                        applicationId,
                        startTime
                    );
    
                    // attach matchId to any active login‑session of this player
                    for (uint256 j; j < loginSessions.length; ++j) {
                        DataTypes.LoginSession storage ls = loginSessions[j];
                        if (ls.baseData.endTime == 0 && ls.playerIndex == pIdx) {
                            ls.matchIds.push(matchSessionId);
                            break;
                        }
                    }
                }
            }
    
            activeMatchSessions.push(matchSessionId);
        }
    
    
        /**
         * @notice Ends a match session
         * @param matchSessions Storage array of match sessions
         * @param activeMatchSessions Storage array of active match session IDs
         * @param playerDatas Storage array of player data
         * @param _matchSessionId ID of the match session to end
         * @param _endTime End time of the match
         * @dev Reverts if:
         *      - End time is 0
         *      - Match session ID is out of bounds
         *      - Match is already ended
         *      - End time is before or equal to start time
         * @dev Sets unfinished players to Forfeit status
         */
        function endMatchSession(
            DataTypes.MatchSession[] storage matchSessions,
            uint256[] storage activeMatchSessions,
            DataTypes.PlayData[] storage playerDatas,
            uint256 _matchSessionId,
            uint256 _endTime
        ) internal {
            if (_endTime == 0) revert InvalidTime();
            if (_matchSessionId >= matchSessions.length) revert IndexOutOfBounds();
    
            DataTypes.MatchSession storage ms = matchSessions[_matchSessionId];
            if (ms.baseData.endTime != 0) revert MatchAlreadyEnded();
            if (_endTime <= ms.baseData.startTime) revert InvalidTime();
    
            ms.baseData.endTime = _endTime;
    
            /* remove from active list (swap‑pop) */
            for (uint256 i; i < activeMatchSessions.length; ++i)
                if (activeMatchSessions[i] == _matchSessionId) {
                    activeMatchSessions[i] = activeMatchSessions[
                        activeMatchSessions.length - 1
                    ];
                    activeMatchSessions.pop();
                    break;
                }
    
            /* set unfinished players to Forfeit */
            uint256 n = ms.playData.length;
            for (uint256 i; i < n; ++i) {
                DataTypes.PlayData storage pd = playerDatas[ms.playData[i]];
                if (pd.baseData.endTime == 0) {
                    pd.baseData.endTime = _endTime;
                    pd.winLoss = DataTypes.WinLoss.Forfeit;
                }
            }
        }
    
    
        /**
         * @notice Adds a player to an existing match
         * @param matchSessions Storage array of match sessions
         * @param playDatas Storage array of player data
         * @param _matchSessionId ID of the match session
         * @param _playerIndex Index of the player to add
         * @param _startTime Start time for the player in the match
         * @return playDataId ID of the created player data
         * @dev Reverts if:
         *      - Match session ID is out of bounds
         *      - Match has already ended
         *      - Match is full
         *      - Player is already in the match
         */
        function addPlayerToMatch(
            DataTypes.MatchSession[] storage matchSessions,
            DataTypes.PlayData[] storage playDatas,
            uint256 _matchSessionId,
            uint256 _playerIndex,
            uint256 _startTime
        ) internal returns (uint256 playDataId) {
            if (_matchSessionId >= matchSessions.length) revert IndexOutOfBounds();
    
            DataTypes.MatchSession storage ms = matchSessions[_matchSessionId];
            if (ms.baseData.endTime != 0) revert MatchFinished();
            if (ms.playData.length >= CoreLib.MAX_PLAYERS_PER_MATCH)
                revert MatchFull();
    
            for (uint256 i; i < ms.playData.length; ++i)
                if (playDatas[ms.playData[i]].playerIndex == _playerIndex)
                    revert PlayerAlreadyInMatch();
    
            playDataId = MatchLibPlayer.createPlayerData(
                playDatas,
                _playerIndex,
                ms.baseData.applicationId,
                _startTime
            );
    
            ms.playData.push(playDataId);
            ms.playerIds.push(_playerIndex);
        }
    
    
        // /**
        //  * @notice Adds metadata to a match session
        //  * @param matchSessions Storage array of match sessions
        //  * @param _matchSessionId ID of the match session
        //  * @param _key Metadata key
        //  * @param _value Metadata value
        //  * @dev Reverts if:
        //  *      - Match session ID is out of bounds
        //  *      - Match has already ended
        //  *      - Key or value is empty or invalid
        //  *      - Maximum metadata keys or values exceeded
        //  *      - Value already exists for the key
        //  */
        // function setMatchSessionMetadata(
        //     DataTypes.MatchSession[] storage matchSessions,
        //     uint256 _matchSessionId,
        //     string calldata _key,
        //     string calldata _value
        // ) internal {
        //     if (_matchSessionId >= matchSessions.length) revert IndexOutOfBounds();
    
        //     DataTypes.MatchSession storage ms = matchSessions[_matchSessionId];
        //     if (ms.baseData.endTime != 0) revert MatchFinished();
    
        //     CoreLib.addMetadata(ms.metadata, _key, _value);
        // }
    }
    
  • contracts/RecordLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./CoreLib.sol";
    import "./LibErrors.sol";
    
    /**
     * @title RecordLib
     * @notice Creates and links record objects to PlayData while keeping a
     *         "latest‑record" mapping per player.
     * @dev    All reverts use custom‑error selectors (cheaper than strings).
     */
    library RecordLib {
        /**
         * @notice Creates a new record and links it to PlayData
         * @dev Updates the recordsByUniqueId mapping to track the latest record for each player
         * @param _playDataId         Target play‑data index
         * @param playDatas           Storage array with every PlayData
         * @param records             Storage array with every Record
         * @param recordsByUniqueId   playerIndex => newest recordId mapping
         * @param recordsByPlayer     playerIndex => all recordIds for that player
         * @param _score              Numerical score
         * @param _key                Record type
         * @param _value              Record payload
         * @param _otherPlayers       Auxiliary player indices
         * @param _startTime          Unix timestamp (must be > 0)
         * @param _playerIndex        Player index for match ID 0
         * @return recordId The ID of the newly created record
         * @return playerIndex The index of the player associated with this record
         */
        function setRecord(
            uint256 _playDataId,
            DataTypes.PlayData[] storage playDatas,
            DataTypes.Records[] storage records,
            mapping(uint256 => uint256) storage recordsByUniqueId,
            mapping(uint256 => uint256[]) storage recordsByPlayer,
            int256 _score,
            string calldata _key,
            string calldata _value,
            uint256[] calldata _otherPlayers,
            uint256 _startTime,
            uint256 _playerIndex
        ) internal returns (uint256 recordId, uint256 playerIndex) {
            /* ─── basic validation ─── */
            if (_startTime == 0) revert InvalidTime();
            CoreLib.validateStringCalldata(_key);
            CoreLib.validateStringCalldata(_value);
    
            /* ─── build and store the new record ─── */
            recordId = records.length;
            DataTypes.Records storage rec = records.push();
    
            rec.id = recordId;
            rec.key = _key;
            rec.value = _value;
            rec.score = _score;
            rec.startTime = _startTime;
            if (_otherPlayers.length != 0) rec.otherPlayer = _otherPlayers;
    
            // if playDataId is not max, then link to PlayData and update player mapping
            // this means that the record is linked to a level/match playData
            // if playDataId is max, then the record is linked to a player menu
            if (_playDataId != type(uint256).max) {
                /* ─── link to PlayData and update player mapping ─── */
                if (_playDataId >= playDatas.length) revert IndexOutOfBounds();
                DataTypes.PlayData storage pd = playDatas[_playDataId];
                pd.records.push(recordId);
                playerIndex = pd.playerIndex;
                rec.playDataId = _playDataId;
            } else {
                // For match ID 0, use the provided player index directly
                playerIndex = _playerIndex;
                rec.playDataId = type(uint256).max;
            }
    
            rec.playerIndex = playerIndex;
            recordsByUniqueId[playerIndex] = recordId;
            
            /* ─── add to player's record array ─── */
            recordsByPlayer[playerIndex].push(recordId);
        }
    }
    
  • contracts/SessionLib.sol
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import "./DataTypes.sol";
    import "./CoreLib.sol";
    import "./LibErrors.sol";
    
    /**
     * @title SessionLib
     * @notice Library for creating / ending login‑sessions and handling metadata.
     *         All reverts now use short custom‑error selectors (no revert‑strings).
     */
    library SessionLib {
    
        /**
         * @notice Creates a new login session for a player
         * @dev Automatically ends any existing active session for the player
         * @param activeLoginSessions Array of active login session IDs
         * @param activeLoginSessionByPlayer Mapping of player index to active login session ID
         * @param playersWithActiveSessions Array of player indices with active sessions
         * @param loginSessions Array of all login sessions
         * @param _playerIndex Index of the player
         * @param _applicationId ID of the application
         * @param _startTime Start time of the session (Unix timestamp)
         * @param _device Device type used for login
         * @return sessionId ID of the newly created login session
         */
        function loginSessionCreate(
            uint256[] storage activeLoginSessions,
            mapping(uint256 => uint256) storage activeLoginSessionByPlayer,
            uint256[] storage playersWithActiveSessions,
            DataTypes.LoginSession[] storage loginSessions,
            uint256 _playerIndex,
            uint256 _applicationId,
            uint256 _startTime,
            DataTypes.Device _device
        ) internal returns (uint256 sessionId) {
            if (_device >= DataTypes.Device.Last)
                revert IndexOutOfBounds(); // invalid enum value
            if (_startTime == 0) revert InvalidTime();
    
            /* —— End any existing active session for this player —— */
            uint256 existingId = activeLoginSessionByPlayer[_playerIndex];
            if (existingId < loginSessions.length) {
                DataTypes.LoginSession storage ls = loginSessions[existingId];
                if (ls.baseData.endTime == 0) {
                    ls.baseData.endTime = _startTime - 1;
    
                    // remove from activeLoginSessions
                    for (uint256 i; i < activeLoginSessions.length; ++i) {
                        if (activeLoginSessions[i] == existingId) {
                            activeLoginSessions[i] = activeLoginSessions[
                                activeLoginSessions.length - 1
                            ];
                            activeLoginSessions.pop();
                            break;
                        }
                    }
                    // remove from playersWithActiveSessions
                    for (uint256 j; j < playersWithActiveSessions.length; ++j) {
                        if (playersWithActiveSessions[j] == _playerIndex) {
                            playersWithActiveSessions[
                                j
                            ] = playersWithActiveSessions[
                                playersWithActiveSessions.length - 1
                            ];
                            playersWithActiveSessions.pop();
                            break;
                        }
                    }
                    delete activeLoginSessionByPlayer[_playerIndex];
                }
            }
    
            /* —— Create the new session —— */
            sessionId = loginSessions.length;
            DataTypes.LoginSession storage s = loginSessions.push();
    
            s.baseData.id = sessionId;
            s.baseData.startTime = _startTime;
            s.baseData.applicationId = _applicationId;
            s.playerIndex = _playerIndex;
            s.device = _device;
    
            // mark as active
            activeLoginSessions.push(sessionId);
            activeLoginSessionByPlayer[_playerIndex] = sessionId;
            playersWithActiveSessions.push(_playerIndex);
    
            return sessionId;
        }
    
    
        /**
         * @notice Ends an active login session
         * @dev Removes the session from active tracking arrays and mappings
         * @param activeLoginSessions Array of active login session IDs
         * @param activeLoginSessionByPlayer Mapping of player index to active login session ID
         * @param playersWithActiveSessions Array of player indices with active sessions
         * @param loginSessions Array of all login sessions
         * @param _sessionId ID of the session to end
         * @param _endTime End time of the session (Unix timestamp)
         */
        function loginSessionEnd(
            uint256[] storage activeLoginSessions,
            mapping(uint256 => uint256) storage activeLoginSessionByPlayer,
            uint256[] storage playersWithActiveSessions,
            DataTypes.LoginSession[] storage loginSessions,
            uint256 _sessionId,
            uint256 _endTime
        ) internal {
            if (_sessionId >= loginSessions.length)
                revert IndexOutOfBounds();
    
            DataTypes.LoginSession storage ls = loginSessions[_sessionId];
    
            ls.baseData.endTime = _endTime;
    
            /* —— cleanup active arrays —— */
            for (uint256 i; i < activeLoginSessions.length; ++i) {
                if (activeLoginSessions[i] == _sessionId) {
                    activeLoginSessions[i] = activeLoginSessions[
                        activeLoginSessions.length - 1
                    ];
                    activeLoginSessions.pop();
                    break;
                }
            }
    
            uint256 pIdx = ls.playerIndex;
            for (uint256 j; j < playersWithActiveSessions.length; ++j) {
                if (playersWithActiveSessions[j] == pIdx) {
                    playersWithActiveSessions[j] = playersWithActiveSessions[
                        playersWithActiveSessions.length - 1
                    ];
                    playersWithActiveSessions.pop();
                    break;
                }
            }
    
            delete activeLoginSessionByPlayer[pIdx];
        }
    
    
        // /**
        //  * @notice Adds metadata to a login session
        //  * @dev Uses CoreLib.addMetadata to handle the metadata storage
        //  * @param loginSessions Array of all login sessions
        //  * @param _sessionId ID of the session to add metadata to
        //  * @param _key Metadata key
        //  * @param _value Metadata value
        //  */
        // function setLoginSessionMetadata(
        //     DataTypes.LoginSession[] storage loginSessions,
        //     uint256 _sessionId,
        //     string calldata _key,
        //     string calldata _value
        // ) internal {
        //     CoreLib.addMetadata(loginSessions[_sessionId].metadata, _key, _value);
        // }
    }
    
ABI · 122 entries
json
[
  {
    "type": "constructor",
    "inputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "AccessControlBadConfirmation",
    "type": "error",
    "inputs": []
  },
  {
    "name": "AccessControlEnforcedDefaultAdminDelay",
    "type": "error",
    "inputs": [
      {
        "name": "schedule",
        "type": "uint48",
        "internalType": "uint48"
      }
    ]
  },
  {
    "name": "AccessControlEnforcedDefaultAdminRules",
    "type": "error",
    "inputs": []
  },
  {
    "name": "AccessControlInvalidDefaultAdmin",
    "type": "error",
    "inputs": [
      {
        "name": "defaultAdmin",
        "type": "address",
        "internalType": "address"
      }
    ]
  },
  {
    "name": "AccessControlUnauthorizedAccount",
    "type": "error",
    "inputs": [
      {
        "name": "account",
        "type": "address",
        "internalType": "address"
      },
      {
        "name": "neededRole",
        "type": "bytes32",
        "internalType": "bytes32"
      }
    ]
  },
  {
    "name": "AlreadyExists",
    "type": "error",
    "inputs": []
  },
  {
    "name": "DuplicatePlayer",
    "type": "error",
    "inputs": []
  },
  {
    "name": "EmptyArray",
    "type": "error",
    "inputs": []
  },
  {
    "name": "EmptyString",
    "type": "error",
    "inputs": []
  },
  {
    "name": "EnforcedPause",
    "type": "error",
    "inputs": []
  },
  {
    "name": "ExpectedPause",
    "type": "error",
    "inputs": []
  },
  {
    "name": "IndexOutOfBounds",
    "type": "error",
    "inputs": []
  },
  {
    "name": "Invalid",
    "type": "error",
    "inputs": []
  },
  {
    "name": "InvalidTime",
    "type": "error",
    "inputs": []
  },
  {
    "name": "MatchAlreadyEnded",
    "type": "error",
    "inputs": []
  },
  {
    "name": "MatchFinished",
    "type": "error",
    "inputs": []
  },
  {
    "name": "MatchFull",
    "type": "error",
    "inputs": []
  },
  {
    "name": "NotFound",
    "type": "error",
    "inputs": []
  },
  {
    "name": "PlayerAlreadyInMatch",
    "type": "error",
    "inputs": []
  },
  {
    "name": "SafeCastOverflowedUintDowncast",
    "type": "error",
    "inputs": [
      {
        "name": "bits",
        "type": "uint8",
        "internalType": "uint8"
      },
      {
        "name": "value",
        "type": "uint256",
        "internalType": "uint256"
      }
    ]
  },
  {
    "name": "TooManyItems",
    "type": "error",
    "inputs": []
  },
  {
    "name": "TooManyPlayers",
    "type": "error",
    "inputs": []
  },
  {
    "name": "ZeroAddress",
    "type": "error",
    "inputs": []
  },
  {
    "name": "ApplicationRecordAddressesUpdated",
    "type": "event",
    "inputs": [
      {
        "name": "recordId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "contractAddresses",
        "type": "address[]",
        "indexed": false,
        "internalType": "address[]"
      }
    ],
    "anonymous": false
  },
  {
    "name": "ApplicationRecordCreated",
    "type": "event",
    "inputs": [
      {
        "name": "recordId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "applicationVersion",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "companyName",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "contractAddresses",
        "type": "address[]",
        "indexed": false,
        "internalType": "address[]"
      }
    ],
    "anonymous": false
  },
  {
    "name": "ApplicationRecordMetadataAdded",
    "type": "event",
    "inputs": [
      {
        "name": "recordId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "key",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "ApplicationSet",
    "type": "event",
    "inputs": [
      {
        "name": "name",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "owner",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "DefaultAdminDelayChangeCanceled",
    "type": "event",
    "inputs": [],
    "anonymous": false
  },
  {
    "name": "DefaultAdminDelayChangeScheduled",
    "type": "event",
    "inputs": [
      {
        "name": "newDelay",
        "type": "uint48",
        "indexed": false,
        "internalType": "uint48"
      },
      {
        "name": "effectSchedule",
        "type": "uint48",
        "indexed": false,
        "internalType": "uint48"
      }
    ],
    "anonymous": false
  },
  {
    "name": "DefaultAdminTransferCanceled",
    "type": "event",
    "inputs": [],
    "anonymous": false
  },
  {
    "name": "DefaultAdminTransferScheduled",
    "type": "event",
    "inputs": [
      {
        "name": "newAdmin",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      },
      {
        "name": "acceptSchedule",
        "type": "uint48",
        "indexed": false,
        "internalType": "uint48"
      }
    ],
    "anonymous": false
  },
  {
    "name": "LoginSessionCreated",
    "type": "event",
    "inputs": [
      {
        "name": "sessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "startTime",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "device",
        "type": "uint8",
        "indexed": false,
        "internalType": "enum DataTypes.Device"
      },
      {
        "name": "applicationId",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "LoginSessionEnded",
    "type": "event",
    "inputs": [
      {
        "name": "sessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "endTime",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "LoginSessionMetadataAdded",
    "type": "event",
    "inputs": [
      {
        "name": "sessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "key",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "MatchSessionEnded",
    "type": "event",
    "inputs": [
      {
        "name": "matchSessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "endTime",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "MatchSessionMetadataAdded",
    "type": "event",
    "inputs": [
      {
        "name": "matchSessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "key",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "MatchSessionStarted",
    "type": "event",
    "inputs": [
      {
        "name": "matchSessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "applicationId",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      },
      {
        "name": "startTime",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "multiplayer",
        "type": "bool",
        "indexed": false,
        "internalType": "bool"
      },
      {
        "name": "playerIndices",
        "type": "uint256[]",
        "indexed": false,
        "internalType": "uint256[]"
      },
      {
        "name": "level",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "Paused",
    "type": "event",
    "inputs": [
      {
        "name": "account",
        "type": "address",
        "indexed": false,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerAddedToMatchSession",
    "type": "event",
    "inputs": [
      {
        "name": "matchSessionId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerDataId",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerCreated",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerAddress",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      },
      {
        "name": "playerID",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "playerType",
        "type": "uint8",
        "indexed": false,
        "internalType": "enum DataTypes.PlayerType"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerDataUpdated",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playDataId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "endTime",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      },
      {
        "name": "score",
        "type": "int256",
        "indexed": false,
        "internalType": "int256"
      },
      {
        "name": "winLoss",
        "type": "uint8",
        "indexed": false,
        "internalType": "enum DataTypes.WinLoss"
      },
      {
        "name": "matchPosition",
        "type": "int256",
        "indexed": false,
        "internalType": "int256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerIdUpdated",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerID",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerIdentifierAdded",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "identifierType",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "identifierValue",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerMetadataAdded",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "key",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerScoreUpdated",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "newScore",
        "type": "int256",
        "indexed": false,
        "internalType": "int256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "PlayerVerifiedAddressAdded",
    "type": "event",
    "inputs": [
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "verifiedAddress",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "RecordSet",
    "type": "event",
    "inputs": [
      {
        "name": "recordId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playerIndex",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "playDataId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "score",
        "type": "int256",
        "indexed": false,
        "internalType": "int256"
      },
      {
        "name": "key",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "indexed": false,
        "internalType": "string"
      },
      {
        "name": "otherPlayers",
        "type": "uint256[]",
        "indexed": false,
        "internalType": "uint256[]"
      },
      {
        "name": "startTime",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "RoleAdminChanged",
    "type": "event",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "indexed": true,
        "internalType": "bytes32"
      },
      {
        "name": "previousAdminRole",
        "type": "bytes32",
        "indexed": true,
        "internalType": "bytes32"
      },
      {
        "name": "newAdminRole",
        "type": "bytes32",
        "indexed": true,
        "internalType": "bytes32"
      }
    ],
    "anonymous": false
  },
  {
    "name": "RoleGranted",
    "type": "event",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "indexed": true,
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      },
      {
        "name": "sender",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "RoleRevoked",
    "type": "event",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "indexed": true,
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      },
      {
        "name": "sender",
        "type": "address",
        "indexed": true,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "Unpaused",
    "type": "event",
    "inputs": [
      {
        "name": "account",
        "type": "address",
        "indexed": false,
        "internalType": "address"
      }
    ],
    "anonymous": false
  },
  {
    "name": "UserBanned",
    "type": "event",
    "inputs": [
      {
        "name": "playerId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "startTime",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "UserUnbanned",
    "type": "event",
    "inputs": [
      {
        "name": "playerId",
        "type": "uint256",
        "indexed": true,
        "internalType": "uint256"
      },
      {
        "name": "timestamp",
        "type": "uint256",
        "indexed": false,
        "internalType": "uint256"
      }
    ],
    "anonymous": false
  },
  {
    "name": "DEFAULT_ADMIN_ROLE",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "bytes32",
        "internalType": "bytes32"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "MODERATOR_ROLE",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "bytes32",
        "internalType": "bytes32"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "acceptDefaultAdminTransfer",
    "type": "function",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "addPlayerIdentifier",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "k",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "v",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "addPlayerToMatchSession",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "pIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "startTime",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "addVerifiedAddress",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "a",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "application",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "name",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "owner",
        "type": "address",
        "internalType": "address"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "banPlayer",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "batchSetRecords",
    "type": "function",
    "inputs": [
      {
        "name": "inputs",
        "type": "tuple[]",
        "components": [
          {
            "name": "matchId",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "playerIndex",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "score",
            "type": "int256",
            "internalType": "int256"
          },
          {
            "name": "key",
            "type": "string",
            "internalType": "string"
          },
          {
            "name": "value",
            "type": "string",
            "internalType": "string"
          },
          {
            "name": "otherPlayers",
            "type": "uint256[]",
            "internalType": "uint256[]"
          },
          {
            "name": "startTime",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct DataTypes.RecordInput[]"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "beginDefaultAdminTransfer",
    "type": "function",
    "inputs": [
      {
        "name": "newAdmin",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "cancelDefaultAdminTransfer",
    "type": "function",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "changeDefaultAdminDelay",
    "type": "function",
    "inputs": [
      {
        "name": "newDelay",
        "type": "uint48",
        "internalType": "uint48"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "createApplicationRecord",
    "type": "function",
    "inputs": [
      {
        "name": "_ver",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "_company",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "_contracts",
        "type": "address[]",
        "internalType": "address[]"
      }
    ],
    "outputs": [
      {
        "name": "recordId",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "createPlayer",
    "type": "function",
    "inputs": [
      {
        "name": "_pid",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "_ptype",
        "type": "uint8",
        "internalType": "enum DataTypes.PlayerType"
      },
      {
        "name": "_addr",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "defaultAdmin",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "address"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "defaultAdminDelay",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint48",
        "internalType": "uint48"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "defaultAdminDelayIncreaseWait",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint48",
        "internalType": "uint48"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "endMatchSession",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "end",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "findPlayDataId",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "pIdx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "id",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getAllActiveLoginPlayers",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getAllActiveLoginSessionIds",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getAllActiveMatchSessionIds",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getAllBannedPlayers",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getApplicationRecordAddresses",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "address[]",
        "internalType": "address[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getApplicationRecordByIndex",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "ver",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "company",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "contracts_",
        "type": "address[]",
        "internalType": "address[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getLatestApplicationRecord",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getLoginSessionById",
    "type": "function",
    "inputs": [
      {
        "name": "sid",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "base_",
        "type": "tuple",
        "components": [
          {
            "name": "id",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "startTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "endTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "applicationId",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct DataTypes.BaseData"
      },
      {
        "name": "meta_",
        "type": "tuple",
        "components": [
          {
            "name": "key",
            "type": "string[]",
            "internalType": "string[]"
          },
          {
            "name": "values",
            "type": "string[]",
            "internalType": "string[]"
          }
        ],
        "internalType": "struct DataTypes.MetaData"
      },
      {
        "name": "device_",
        "type": "uint8",
        "internalType": "enum DataTypes.Device"
      },
      {
        "name": "playerIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "matchIds_",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getLoginSessionCount",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getMatchSessionByIndex",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "base_",
        "type": "tuple",
        "components": [
          {
            "name": "id",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "startTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "endTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "applicationId",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct DataTypes.BaseData"
      },
      {
        "name": "meta_",
        "type": "tuple",
        "components": [
          {
            "name": "key",
            "type": "string[]",
            "internalType": "string[]"
          },
          {
            "name": "values",
            "type": "string[]",
            "internalType": "string[]"
          }
        ],
        "internalType": "struct DataTypes.MetaData"
      },
      {
        "name": "multiplayer",
        "type": "bool",
        "internalType": "bool"
      },
      {
        "name": "playerIds",
        "type": "uint256[]",
        "internalType": "uint256[]"
      },
      {
        "name": "playDataIds",
        "type": "uint256[]",
        "internalType": "uint256[]"
      },
      {
        "name": "level",
        "type": "string",
        "internalType": "string"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getMatchSessionCount",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayDataByIndex",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "base_",
        "type": "tuple",
        "components": [
          {
            "name": "id",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "startTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "endTime",
            "type": "uint256",
            "internalType": "uint256"
          },
          {
            "name": "applicationId",
            "type": "uint256",
            "internalType": "uint256"
          }
        ],
        "internalType": "struct DataTypes.BaseData"
      },
      {
        "name": "playerIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "score",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "wl",
        "type": "uint8",
        "internalType": "enum DataTypes.WinLoss"
      },
      {
        "name": "pos",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "recIds",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayDataCount",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerByIndex",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "pid",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "addr",
        "type": "address",
        "internalType": "address"
      },
      {
        "name": "ptype",
        "type": "uint8",
        "internalType": "enum DataTypes.PlayerType"
      },
      {
        "name": "score",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "idKeys",
        "type": "string[]",
        "internalType": "string[]"
      },
      {
        "name": "idVals",
        "type": "string[]",
        "internalType": "string[]"
      },
      {
        "name": "verifiedAddrs",
        "type": "address[]",
        "internalType": "address[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerByVerifiedId",
    "type": "function",
    "inputs": [
      {
        "name": "k",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "v",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerCount",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerIndex",
    "type": "function",
    "inputs": [
      {
        "name": "_pid",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerIndexByAddress",
    "type": "function",
    "inputs": [
      {
        "name": "a",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getPlayerUniqueId",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "string",
        "internalType": "string"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getRecordIdsByPlayer",
    "type": "function",
    "inputs": [
      {
        "name": "playerIdx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getRecordsByIndex",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "id",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "key",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "score",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "start",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "playerIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "others",
        "type": "uint256[]",
        "internalType": "uint256[]"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "getRoleAdmin",
    "type": "function",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "internalType": "bytes32"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "bytes32",
        "internalType": "bytes32"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "grantRole",
    "type": "function",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "hasRole",
    "type": "function",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "bool",
        "internalType": "bool"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "isPlayerBanned",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "bool",
        "internalType": "bool"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "loginSessionCreate",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "appId",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "start",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "devc",
        "type": "uint8",
        "internalType": "enum DataTypes.Device"
      }
    ],
    "outputs": [
      {
        "name": "sid",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "loginSessionEnd",
    "type": "function",
    "inputs": [
      {
        "name": "sid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "end",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "owner",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "address",
        "internalType": "address"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "pause",
    "type": "function",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "paused",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "",
        "type": "bool",
        "internalType": "bool"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "pendingDefaultAdmin",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "newAdmin",
        "type": "address",
        "internalType": "address"
      },
      {
        "name": "schedule",
        "type": "uint48",
        "internalType": "uint48"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "pendingDefaultAdminDelay",
    "type": "function",
    "inputs": [],
    "outputs": [
      {
        "name": "newDelay",
        "type": "uint48",
        "internalType": "uint48"
      },
      {
        "name": "schedule",
        "type": "uint48",
        "internalType": "uint48"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "renounceRole",
    "type": "function",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "revokeRole",
    "type": "function",
    "inputs": [
      {
        "name": "role",
        "type": "bytes32",
        "internalType": "bytes32"
      },
      {
        "name": "account",
        "type": "address",
        "internalType": "address"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "rollbackDefaultAdminDelay",
    "type": "function",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "setApplication",
    "type": "function",
    "inputs": [
      {
        "name": "_name",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "setLoginSessionMetadata",
    "type": "function",
    "inputs": [
      {
        "name": "sid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "k",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "v",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "setMatchSessionMetadata",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "k",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "v",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "setPlayerMetadata",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "k",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "v",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "setRecord",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "pIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "score",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "key",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "value",
        "type": "string",
        "internalType": "string"
      },
      {
        "name": "others",
        "type": "uint256[]",
        "internalType": "uint256[]"
      },
      {
        "name": "start",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [
      {
        "name": "rid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "playerId",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "startMatchSession",
    "type": "function",
    "inputs": [
      {
        "name": "appId",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "start",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "multiplayer",
        "type": "bool",
        "internalType": "bool"
      },
      {
        "name": "pIdx",
        "type": "uint256[]",
        "internalType": "uint256[]"
      },
      {
        "name": "level",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "supportsInterface",
    "type": "function",
    "inputs": [
      {
        "name": "interfaceId",
        "type": "bytes4",
        "internalType": "bytes4"
      }
    ],
    "outputs": [
      {
        "name": "",
        "type": "bool",
        "internalType": "bool"
      }
    ],
    "stateMutability": "view"
  },
  {
    "name": "unbanPlayer",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "unpause",
    "type": "function",
    "inputs": [],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "updateApplicationRecordAddresses",
    "type": "function",
    "inputs": [
      {
        "name": "_id",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "_contracts",
        "type": "address[]",
        "internalType": "address[]"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "updatePlayDataForMatchSession",
    "type": "function",
    "inputs": [
      {
        "name": "mid",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "pIdx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "end",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "score",
        "type": "int256",
        "internalType": "int256"
      },
      {
        "name": "wl",
        "type": "uint8",
        "internalType": "enum DataTypes.WinLoss"
      },
      {
        "name": "pos",
        "type": "int256",
        "internalType": "int256"
      }
    ],
    "outputs": [
      {
        "name": "pdId",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "playerIdx",
        "type": "uint256",
        "internalType": "uint256"
      }
    ],
    "stateMutability": "nonpayable"
  },
  {
    "name": "updatePlayerScore",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "newScore",
        "type": "int256",
        "internalType": "int256"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "updatePlayerUniqueId",
    "type": "function",
    "inputs": [
      {
        "name": "idx",
        "type": "uint256",
        "internalType": "uint256"
      },
      {
        "name": "newPid",
        "type": "string",
        "internalType": "string"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  },
  {
    "name": "withdrawETH",
    "type": "function",
    "inputs": [
      {
        "name": "recipient",
        "type": "address",
        "internalType": "address payable"
      }
    ],
    "outputs": [],
    "stateMutability": "nonpayable"
  }
]