Accounts
0xf4...4c18
0xf4...4C18

0xf4...4C18

$500
This contract's source code is verified!
Contract Metadata
Compiler
0.8.24+commit.e11b9ed9
Language
Solidity
Contract Source Code
File 1 of 46: 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;
        }
    }
}
Contract Source Code
File 2 of 46: Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}
Contract Source Code
File 3 of 46: Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Arrays.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * `array` is expected to be sorted in ascending order, and to contain no
     * repeated elements.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

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

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

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

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

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`
        // following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays.

        /// @solidity memory-safe-assembly
        assembly {
            mstore(0, arr.slot)
            slot := add(keccak256(0, 0x20), pos)
        }
        return slot.getUint256Slot();
    }

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

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }
}
Contract Source Code
File 4 of 46: 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;
    }
}
Contract Source Code
File 5 of 46: ERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/ERC1155.sol)

pragma solidity ^0.8.20;

import {IERC1155} from "./IERC1155.sol";
import {IERC1155Receiver} from "./IERC1155Receiver.sol";
import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
import {Context} from "../../utils/Context.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {Arrays} from "../../utils/Arrays.sol";
import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 */
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
    using Arrays for uint256[];
    using Arrays for address[];

    mapping(uint256 id => mapping(address account => uint256)) private _balances;

    mapping(address account => mapping(address operator => bool)) private _operatorApprovals;

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor(string memory uri_) {
        _setURI(uri_);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC1155).interfaceId ||
            interfaceId == type(IERC1155MetadataURI).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256 /* id */) public view virtual returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     */
    function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] memory accounts,
        uint256[] memory ids
    ) public view virtual returns (uint256[] memory) {
        if (accounts.length != ids.length) {
            revert ERC1155InvalidArrayLength(ids.length, accounts.length);
        }

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
        }

        return batchBalances;
    }

    /**
     * @dev See {IERC1155-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC1155-isApprovedForAll}.
     */
    function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
        return _operatorApprovals[account][operator];
    }

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
        address sender = _msgSender();
        if (from != sender && !isApprovedForAll(from, sender)) {
            revert ERC1155MissingApprovalForAll(sender, from);
        }
        _safeTransferFrom(from, to, id, value, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) public virtual {
        address sender = _msgSender();
        if (from != sender && !isApprovedForAll(from, sender)) {
            revert ERC1155MissingApprovalForAll(sender, from);
        }
        _safeBatchTransferFrom(from, to, ids, values, data);
    }

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
     * (or `to`) is the zero address.
     *
     * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
     *   or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
     * - `ids` and `values` must have the same length.
     *
     * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
     */
    function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
        if (ids.length != values.length) {
            revert ERC1155InvalidArrayLength(ids.length, values.length);
        }

        address operator = _msgSender();

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids.unsafeMemoryAccess(i);
            uint256 value = values.unsafeMemoryAccess(i);

            if (from != address(0)) {
                uint256 fromBalance = _balances[id][from];
                if (fromBalance < value) {
                    revert ERC1155InsufficientBalance(from, fromBalance, value, id);
                }
                unchecked {
                    // Overflow not possible: value <= fromBalance
                    _balances[id][from] = fromBalance - value;
                }
            }

            if (to != address(0)) {
                _balances[id][to] += value;
            }
        }

        if (ids.length == 1) {
            uint256 id = ids.unsafeMemoryAccess(0);
            uint256 value = values.unsafeMemoryAccess(0);
            emit TransferSingle(operator, from, to, id, value);
        } else {
            emit TransferBatch(operator, from, to, ids, values);
        }
    }

    /**
     * @dev Version of {_update} that performs the token acceptance check by calling
     * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
     * contains code (eg. is a smart contract at the moment of execution).
     *
     * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
     * update to the contract state after this function would break the check-effect-interaction pattern. Consider
     * overriding {_update} instead.
     */
    function _updateWithAcceptanceCheck(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal virtual {
        _update(from, to, ids, values);
        if (to != address(0)) {
            address operator = _msgSender();
            if (ids.length == 1) {
                uint256 id = ids.unsafeMemoryAccess(0);
                uint256 value = values.unsafeMemoryAccess(0);
                _doSafeTransferAcceptanceCheck(operator, from, to, id, value, data);
            } else {
                _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, values, data);
            }
        }
    }

    /**
     * @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, to, ids, values, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     * - `ids` and `values` must have the same length.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, to, ids, values, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the values in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(address(0), to, ids, values, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        _updateWithAcceptanceCheck(address(0), to, ids, values, data);
    }

    /**
     * @dev Destroys a `value` amount of tokens of type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     */
    function _burn(address from, uint256 id, uint256 value) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, address(0), ids, values, "");
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     * - `ids` and `values` must have the same length.
     */
    function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, address(0), ids, values, "");
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC1155InvalidOperator(address(0));
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Performs an acceptance check by calling {IERC1155-onERC1155Received} on the `to` address
     * if it contains code at the moment of execution.
     */
    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 value,
        bytes memory data
    ) private {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    // Tokens rejected
                    revert ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-ERC1155Receiver implementer
                    revert ERC1155InvalidReceiver(to);
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }

    /**
     * @dev Performs a batch acceptance check by calling {IERC1155-onERC1155BatchReceived} on the `to` address
     * if it contains code at the moment of execution.
     */
    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) private {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    // Tokens rejected
                    revert ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-ERC1155Receiver implementer
                    revert ERC1155InvalidReceiver(to);
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }

    /**
     * @dev Creates an array in memory with only one value for each of the elements provided.
     */
    function _asSingletonArrays(
        uint256 element1,
        uint256 element2
    ) private pure returns (uint256[] memory array1, uint256[] memory array2) {
        /// @solidity memory-safe-assembly
        assembly {
            // Load the free memory pointer
            array1 := mload(0x40)
            // Set array length to 1
            mstore(array1, 1)
            // Store the single element at the next word after the length (where content starts)
            mstore(add(array1, 0x20), element1)

            // Repeat for next array locating it right after the first array
            array2 := add(array1, 0x40)
            mstore(array2, 1)
            mstore(add(array2, 0x20), element2)

            // Update the free memory pointer by pointing after the second array
            mstore(0x40, add(array2, 0x40))
        }
    }
}
Contract Source Code
File 6 of 46: ERC1155Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Burnable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Extension of {ERC1155} that allows token holders to destroy both their
 * own tokens and those that they have been approved to use.
 */
abstract contract ERC1155Burnable is ERC1155 {
    function burn(address account, uint256 id, uint256 value) public virtual {
        if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) {
            revert ERC1155MissingApprovalForAll(_msgSender(), account);
        }

        _burn(account, id, value);
    }

    function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual {
        if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) {
            revert ERC1155MissingApprovalForAll(_msgSender(), account);
        }

        _burnBatch(account, ids, values);
    }
}
Contract Source Code
File 7 of 46: ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}
Contract Source Code
File 8 of 46: ERC1155Supply.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Supply.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Extension of ERC1155 that adds tracking of total supply per id.
 *
 * Useful for scenarios where Fungible and Non-fungible tokens have to be
 * clearly identified. Note: While a totalSupply of 1 might mean the
 * corresponding is an NFT, there is no guarantees that no other token with the
 * same id are not going to be minted.
 *
 * NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens
 * that can be minted.
 *
 * CAUTION: This extension should not be added in an upgrade to an already deployed contract.
 */
abstract contract ERC1155Supply is ERC1155 {
    mapping(uint256 id => uint256) private _totalSupply;
    uint256 private _totalSupplyAll;

    /**
     * @dev Total value of tokens in with a given id.
     */
    function totalSupply(uint256 id) public view virtual returns (uint256) {
        return _totalSupply[id];
    }

    /**
     * @dev Total value of tokens.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupplyAll;
    }

    /**
     * @dev Indicates whether any token exist with a given id, or not.
     */
    function exists(uint256 id) public view virtual returns (bool) {
        return totalSupply(id) > 0;
    }

    /**
     * @dev See {ERC1155-_update}.
     */
    function _update(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values
    ) internal virtual override {
        super._update(from, to, ids, values);

        if (from == address(0)) {
            uint256 totalMintValue = 0;
            for (uint256 i = 0; i < ids.length; ++i) {
                uint256 value = values[i];
                // Overflow check required: The rest of the code assumes that totalSupply never overflows
                _totalSupply[ids[i]] += value;
                totalMintValue += value;
            }
            // Overflow check required: The rest of the code assumes that totalSupplyAll never overflows
            _totalSupplyAll += totalMintValue;
        }

        if (to == address(0)) {
            uint256 totalBurnValue = 0;
            for (uint256 i = 0; i < ids.length; ++i) {
                uint256 value = values[i];

                unchecked {
                    // Overflow not possible: values[i] <= balanceOf(from, ids[i]) <= totalSupply(ids[i])
                    _totalSupply[ids[i]] -= value;
                    // Overflow not possible: sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
                    totalBurnValue += value;
                }
            }
            unchecked {
                // Overflow not possible: totalBurnValue = sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
                _totalSupplyAll -= totalBurnValue;
            }
        }
    }
}
Contract Source Code
File 9 of 46: ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
Contract Source Code
File 10 of 46: ERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/common/ERC2981.sol)

pragma solidity ^0.8.20;

import {IERC2981} from "../../interfaces/IERC2981.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
 *
 * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
 * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
 *
 * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
 * fee is specified in basis points by default.
 *
 * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
 * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
 * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
 */
abstract contract ERC2981 is IERC2981, ERC165 {
    struct RoyaltyInfo {
        address receiver;
        uint96 royaltyFraction;
    }

    RoyaltyInfo private _defaultRoyaltyInfo;
    mapping(uint256 tokenId => RoyaltyInfo) private _tokenRoyaltyInfo;

    /**
     * @dev The default royalty set is invalid (eg. (numerator / denominator) >= 1).
     */
    error ERC2981InvalidDefaultRoyalty(uint256 numerator, uint256 denominator);

    /**
     * @dev The default royalty receiver is invalid.
     */
    error ERC2981InvalidDefaultRoyaltyReceiver(address receiver);

    /**
     * @dev The royalty set for an specific `tokenId` is invalid (eg. (numerator / denominator) >= 1).
     */
    error ERC2981InvalidTokenRoyalty(uint256 tokenId, uint256 numerator, uint256 denominator);

    /**
     * @dev The royalty receiver for `tokenId` is invalid.
     */
    error ERC2981InvalidTokenRoyaltyReceiver(uint256 tokenId, address receiver);

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

    /**
     * @inheritdoc IERC2981
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual returns (address, uint256) {
        RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId];

        if (royalty.receiver == address(0)) {
            royalty = _defaultRoyaltyInfo;
        }

        uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator();

        return (royalty.receiver, royaltyAmount);
    }

    /**
     * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
     * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
     * override.
     */
    function _feeDenominator() internal pure virtual returns (uint96) {
        return 10000;
    }

    /**
     * @dev Sets the royalty information that all ids in this contract will default to.
     *
     * Requirements:
     *
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
        uint256 denominator = _feeDenominator();
        if (feeNumerator > denominator) {
            // Royalty fee will exceed the sale price
            revert ERC2981InvalidDefaultRoyalty(feeNumerator, denominator);
        }
        if (receiver == address(0)) {
            revert ERC2981InvalidDefaultRoyaltyReceiver(address(0));
        }

        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Removes default royalty information.
     */
    function _deleteDefaultRoyalty() internal virtual {
        delete _defaultRoyaltyInfo;
    }

    /**
     * @dev Sets the royalty information for a specific token id, overriding the global default.
     *
     * Requirements:
     *
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {
        uint256 denominator = _feeDenominator();
        if (feeNumerator > denominator) {
            // Royalty fee will exceed the sale price
            revert ERC2981InvalidTokenRoyalty(tokenId, feeNumerator, denominator);
        }
        if (receiver == address(0)) {
            revert ERC2981InvalidTokenRoyaltyReceiver(tokenId, address(0));
        }

        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Resets royalty information for the token id back to the global default.
     */
    function _resetTokenRoyalty(uint256 tokenId) internal virtual {
        delete _tokenRoyaltyInfo[tokenId];
    }
}
Contract Source Code
File 11 of 46: ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "./IERC721.sol";
import {IERC721Receiver} from "./IERC721Receiver.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    mapping(uint256 tokenId => address) private _owners;

    mapping(address owner => uint256) private _balances;

    mapping(uint256 tokenId => address) private _tokenApprovals;

    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual returns (uint256) {
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
     * the `spender` for the specific `tokenId`.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        unchecked {
            _balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                _balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                _balances[to] += 1;
            }
        }

        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        _checkOnERC721Received(address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        _tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }

    /**
     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
     * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     */
    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    revert ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert ERC721InvalidReceiver(to);
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }
}
Contract Source Code
File 12 of 46: ERC721Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Burnable.sol)

pragma solidity ^0.8.20;

import {ERC721} from "../ERC721.sol";
import {Context} from "../../../utils/Context.sol";

/**
 * @title ERC721 Burnable Token
 * @dev ERC721 Token that can be burned (destroyed).
 */
abstract contract ERC721Burnable is Context, ERC721 {
    /**
     * @dev Burns `tokenId`. See {ERC721-_burn}.
     *
     * Requirements:
     *
     * - The caller must own `tokenId` or be an approved operator.
     */
    function burn(uint256 tokenId) public virtual {
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        _update(address(0), tokenId, _msgSender());
    }
}
Contract Source Code
File 13 of 46: ERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability
 * of all the token ids in the contract as well as all token ids owned by each account.
 *
 * CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,
 * interfere with enumerability and should not be used together with `ERC721Enumerable`.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    mapping(address owner => mapping(uint256 index => uint256)) private _ownedTokens;
    mapping(uint256 tokenId => uint256) private _ownedTokensIndex;

    uint256[] private _allTokens;
    mapping(uint256 tokenId => uint256) private _allTokensIndex;

    /**
     * @dev An `owner`'s token query was out of bounds for `index`.
     *
     * NOTE: The owner being `address(0)` indicates a global out of bounds index.
     */
    error ERC721OutOfBoundsIndex(address owner, uint256 index);

    /**
     * @dev Batch mint is not allowed.
     */
    error ERC721EnumerableForbiddenBatchMint();

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

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
        if (index >= balanceOf(owner)) {
            revert ERC721OutOfBoundsIndex(owner, index);
        }
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual returns (uint256) {
        if (index >= totalSupply()) {
            revert ERC721OutOfBoundsIndex(address(0), index);
        }
        return _allTokens[index];
    }

    /**
     * @dev See {ERC721-_update}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
        address previousOwner = super._update(to, tokenId, auth);

        if (previousOwner == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (previousOwner != to) {
            _removeTokenFromOwnerEnumeration(previousOwner, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (previousOwner != to) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }

        return previousOwner;
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = balanceOf(to) - 1;
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = balanceOf(from);
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }

    /**
     * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
     */
    function _increaseBalance(address account, uint128 amount) internal virtual override {
        if (amount > 0) {
            revert ERC721EnumerableForbiddenBatchMint();
        }
        super._increaseBalance(account, amount);
    }
}
Contract Source Code
File 14 of 46: ERC721Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Pausable.sol)

pragma solidity ^0.8.20;

import {ERC721} from "../ERC721.sol";
import {Pausable} from "../../../utils/Pausable.sol";

/**
 * @dev ERC721 token with pausable token transfers, minting and burning.
 *
 * Useful for scenarios such as preventing trades until the end of an evaluation
 * period, or having an emergency switch for freezing all token transfers in the
 * event of a large bug.
 *
 * IMPORTANT: This contract does not include public pause and unpause functions. In
 * addition to inheriting this contract, you must define both functions, invoking the
 * {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate
 * access control, e.g. using {AccessControl} or {Ownable}. Not doing so will
 * make the contract pause mechanism of the contract unreachable, and thus unusable.
 */
abstract contract ERC721Pausable is ERC721, Pausable {
    /**
     * @dev See {ERC721-_update}.
     *
     * Requirements:
     *
     * - the contract must not be paused.
     */
    function _update(
        address to,
        uint256 tokenId,
        address auth
    ) internal virtual override whenNotPaused returns (address) {
        return super._update(to, tokenId, auth);
    }
}
Contract Source Code
File 15 of 46: IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
Contract Source Code
File 16 of 46: IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the value of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}
Contract Source Code
File 17 of 46: IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}
Contract Source Code
File 18 of 46: IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}
Contract Source Code
File 19 of 46: IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
Contract Source Code
File 21 of 46: IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
Contract Source Code
File 22 of 46: IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Contract Source Code
File 23 of 46: IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (address receiver, uint256 royaltyAmount);
}
Contract Source Code
File 24 of 46: IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}
Contract Source Code
File 25 of 46: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}
Contract Source Code
File 26 of 46: IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}
Contract Source Code
File 27 of 46: IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}
Contract Source Code
File 28 of 46: IPermissionCallable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

/// @title IPermissionCallable
///
/// @notice Interface for external contracts to support Session Keys permissionlessly.
///
/// @author Coinbase (https://github.com/coinbase/smart-wallet-permissions)
interface IPermissionCallable {
    /// @notice Wrap a call to the contract with a new selector.
    ///
    /// @dev Call data exactly matches valid selector+arguments on this contract.
    /// @dev Call data matching required because this performs a self-delegatecall.
    ///
    /// @param call Call data exactly matching valid selector+arguments on this contract.
    ///
    /// @return res data returned from the inner self-delegatecall.
    function permissionedCall(bytes calldata call) external payable returns (bytes memory res);

    /// @notice Determine if a function selector is allowed via permissionedCall on this contract.
    ///
    /// @param selector the specific function to check support for.
    ///
    /// @return supported indicator if the selector is supported.
    function supportsPermissionedCallSelector(bytes4 selector) external view returns (bool supported);
}
Contract Source Code
File 29 of 46: ManaSystem.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "@openzeppelin/contracts/access/AccessControl.sol";

contract ManaSystem is AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant SPENDER_ROLE = keccak256("SPENDER_ROLE");

    mapping(address => uint256) public userMana;
    mapping(address => uint256) public lifetimeMana;

    event ManaAdded(address indexed user, uint256 amount, uint256 newTotal, uint256 newLifetime);
    event ManaSpent(address indexed user, uint256 amount, uint256 newTotal);

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    function addMana(address user, uint256 amount) external onlyRole(MINTER_ROLE) {
        userMana[user] += amount;
        lifetimeMana[user] += amount;
        emit ManaAdded(user, amount, userMana[user], lifetimeMana[user]);
    }

    function spendMana(address user, uint256 amount) external onlyRole(SPENDER_ROLE) {
        require(userMana[user] >= amount, "Insufficient mana");
        userMana[user] -= amount;
        emit ManaSpent(user, amount, userMana[user]);
    }

    function getMana(address user) external view returns (uint256) {
        return userMana[user];
    }

    function getLifetimeMana(address user) external view returns (uint256) {
        return lifetimeMana[user];
    }
}
Contract Source Code
File 30 of 46: Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

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

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
Contract Source Code
File 31 of 46: Multicall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)

pragma solidity ^0.8.20;

import {Address} from "./Address.sol";
import {Context} from "./Context.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
 * careful about sending transactions invoking {multicall}. For example, a relay address that filters function
 * selectors won't filter calls nested within a {multicall} operation.
 *
 * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
 * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
 * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
 * {_msgSender} are not propagated to subcalls.
 */
abstract contract Multicall is Context {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        bytes memory context = msg.sender == _msgSender()
            ? new bytes(0)
            : msg.data[msg.data.length - _contextSuffixLength():];

        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
        }
        return results;
    }
}
Contract Source Code
File 32 of 46: Oracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IOffchainOracle {
    function getRateToEth(address srcToken, bool useSrcWrappers) external view returns (uint256 weightedRate);
}

contract Oracle is Ownable {
    using Math for uint256;

    address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
    uint256 private constant BASIS_POINTS = 10000;
    IOffchainOracle public immutable offchainOracle;
    address public daoAddress;

    struct PaymentTokenConfig {
        uint256 burnBasisPoints;
        uint256 daoBasisPoints;
        uint256 partnerBasisPoints;
        address partnerWallet;
        bool isStablecoin;
        bool isWhitelisted;
    }

    mapping(address => PaymentTokenConfig) public tokenConfigs;

    event TokenConfigUpdated(
        address indexed tokenAddress,
        uint256 burnBasisPoints,
        uint256 daoBasisPoints,
        uint256 partnerBasisPoints,
        address partnerWallet,
        bool isStablecoin,
        bool isWhitelisted
    );

    constructor(address _offchainOracle) Ownable(msg.sender) {
        offchainOracle = IOffchainOracle(_offchainOracle);
        daoAddress = msg.sender;
    }

    /**
     * @dev Checks if a token is whitelisted for payments
     * @param paymentToken The address of the payment token
     * @return Whether the token is whitelisted
     */
    function isTokenWhitelisted(address paymentToken) external view returns (bool) {
        return tokenConfigs[paymentToken].isWhitelisted;
    }

    /**
     * @dev Calculates the token amount based on the native cost and quantity
     * @param paymentToken The address of the payment token
     * @param assetNativeCost The native cost of the asset
     * @param quantity The quantity of assets
     * @return tokenPriceNative The price of 1 token in native currency
     * @return tokenAmount The amount of token
     */
    function calculateTokenAmount(
        address paymentToken,
        uint256 assetNativeCost,
        uint256 quantity
    ) public view returns (uint256 tokenPriceNative, uint256 tokenAmount) {
        uint256 decimals = IERC20Metadata(paymentToken).decimals();

        tokenPriceNative = getPriceInNative(paymentToken);
        tokenAmount = (assetNativeCost * quantity * 10 ** decimals * 10 ** 18) / tokenPriceNative;
        tokenAmount = (tokenAmount + 10 ** 18 - 1) / 10 ** 18; // Round up
    }

    /**
     * @dev Gets the ETH price of a token
     * @param token The address of the token
     * @return The price of 1 token in ETH, with 18 decimals of precision
     */
    function getPriceInNative(address token) public view returns (uint256) {
        uint256 rate = offchainOracle.getRateToEth(token, true);
        uint8 tokenDecimals = IERC20Metadata(token).decimals();

        // Normalize the rate to 18 decimals
        if (tokenDecimals < 18) {
            rate = rate / 10 ** (18 - tokenDecimals);
        } else if (tokenDecimals > 18) {
            rate = rate * 10 ** (tokenDecimals - 18);
        }

        return rate;
    }

    /**
     * @dev Sets the configuration for a payment token
     * @param paymentToken The address of the payment token
     * @param burnBasisPoints The percentage of tokens to burn (in basis points)
     * @param daoBasisPoints The percentage of tokens to send to the DAO (in basis points)
     * @param partnerBasisPoints The percentage of tokens to send to the partner (in basis points)
     * @param partnerWallet The address of the partner wallet
     * @param isStablecoin Whether the token is a stablecoin
     * @param isWhitelisted Whether the token is whitelisted for payments
     */
    function setTokenConfig(
        address paymentToken,
        uint256 burnBasisPoints,
        uint256 daoBasisPoints,
        uint256 partnerBasisPoints,
        address partnerWallet,
        bool isStablecoin,
        bool isWhitelisted
    ) external onlyOwner {
        require(burnBasisPoints + daoBasisPoints + partnerBasisPoints == BASIS_POINTS, "Basis points must add up to 10000");
        tokenConfigs[paymentToken] = PaymentTokenConfig(
            burnBasisPoints,
            daoBasisPoints,
            partnerBasisPoints,
            partnerWallet,
            isStablecoin,
            isWhitelisted
        );
        emit TokenConfigUpdated(
            paymentToken,
            burnBasisPoints,
            daoBasisPoints,
            partnerBasisPoints,
            partnerWallet,
            isStablecoin,
            isWhitelisted
        );
    }

    /**
     * @dev Calculates the amounts to be distributed for a token payment
     * @param paymentToken The address of the payment token
     * @param totalAmount The total amount of tokens to be distributed
     * @return burnAmount The amount of tokens to be burned
     * @return daoAmount The amount of tokens to be sent to the DAO
     * @return partnerAmount The amount of tokens to be sent to the partner
     * @return partnerWallet The address of the partner wallet
     */
    function calculateTokenDistribution(
        address paymentToken,
        uint256 totalAmount
    ) external view returns (uint256 burnAmount, uint256 daoAmount, uint256 partnerAmount, address partnerWallet) {
        PaymentTokenConfig memory config = tokenConfigs[paymentToken];
        require(config.isWhitelisted, "Payment token not whitelisted");

        burnAmount = (totalAmount * config.burnBasisPoints) / BASIS_POINTS;
        daoAmount = (totalAmount * config.daoBasisPoints) / BASIS_POINTS;
        partnerAmount = (totalAmount * config.partnerBasisPoints) / BASIS_POINTS;
        partnerWallet = config.partnerWallet;
    }

    /**
     * @dev Sets the DAO address
     * @param _daoAddress The new DAO address
     */
    function setDaoAddress(address _daoAddress) external onlyOwner {
        require(_daoAddress != address(0), "Invalid DAO address");
        daoAddress = _daoAddress;
    }
}
Contract Source Code
File 33 of 46: Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

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

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

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

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

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

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

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
Contract Source Code
File 34 of 46: 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());
    }
}
Contract Source Code
File 35 of 46: PermissionCallable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;

import {Address} from "openzeppelin-contracts/contracts/utils/Address.sol";
import {Multicall} from "openzeppelin-contracts/contracts/utils/Multicall.sol";

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

/// @title PermissionCallable
///
/// @notice Abstract contract to add permissioned userOp support to smart contracts.
///
/// @author Coinbase (https://github.com/coinbase/smart-wallet-permissions)
abstract contract PermissionCallable is IPermissionCallable {
    /// @notice Call not enabled through permissionedCall and smart wallet permissions systems.
    ///
    /// @param selector The function that was attempting to go through permissionedCall.
    error NotPermissionCallable(bytes4 selector);

    /// @inheritdoc IPermissionCallable
    function permissionedCall(bytes calldata call) external payable returns (bytes memory res) {
        // check if call selector is allowed through permissionedCall
        if (!supportsPermissionedCallSelector(bytes4(call))) revert NotPermissionCallable(bytes4(call));
        // make self-delegatecall with provided call data
        return Address.functionDelegateCall(address(this), call);
    }

    /// @inheritdoc IPermissionCallable
    function supportsPermissionedCallSelector(bytes4 selector) public view virtual returns (bool);
}
Contract Source Code
File 36 of 46: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
Contract Source Code
File 37 of 46: SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}
Contract Source Code
File 38 of 46: SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
Contract Source Code
File 39 of 46: StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}
Contract Source Code
File 40 of 46: Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}
Contract Source Code
File 41 of 46: TokiemonBattles.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {PermissionCallable} from "./permissions/PermissionCallable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./TokiemonNFT.sol";
import "./ManaSystem.sol";
import "./TokiemonEquipment.sol";
import "./TokiemonEnergy.sol";
import "./Oracle.sol";

contract TokiemonBattles is AccessControl, PermissionCallable {
    using SafeERC20 for IERC20;

    TokiemonNFT public tokiemonNFT;
    ManaSystem public manaSystem;
    TokiemonEquipment public tokiemonEquipment;
    TokiemonEnergy public tokiemonEnergy;
    Oracle public oracle;

    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");

    uint256 public freeTier = 4;
    uint256 public battleCount = 40000; // Avoid conflicts with previous contract(s)
    uint256 public nextBattlePackId;
    uint256 public criticalEnergyThreshold;
    int256 public criticalEnergyProbability;

    EnergyThreshold[] public energyThresholds;
    RewardConfig public rewardConfig;
    DailyBattleSettings public dailyBattleSettings;
    BattleSettings public battleSettings;

    mapping(uint256 => BattlePack) public battlePacks;
    mapping(uint256 => Battle) public battles;
    mapping(uint256 => uint256) public purchasedBattles;
    mapping(uint256 => uint256) public lastBattleTimestamp;
    mapping(uint256 => uint256) public availableBattles;
    mapping(uint256 => uint256) public regenSurplus;
    mapping(address => uint256) public lastDailyResetForFreeTierByAddress;
    mapping(address => uint256) public dailyFreeTierBattlesUsedByAddress;

    event BattleComplete(
        uint256 battleId,
        uint256 indexed winner,
        uint256 indexed challenger,
        uint256 indexed opponent,
        address challengerAddress,
        address opponentAddress,
        AttackStyle challengerStyle,
        AttackStyle opponentStyle,
        uint256 challengerTotalLevel,
        uint256 opponentTotalLevel,
        uint8[3] challengerSkillLevels,
        uint8[3] opponentSkillLevels
    );
    event BattlePackPurchased(uint256 tokenId, uint256 numberOfBattles);

    struct RewardConfig {
        uint256 minReward;
        uint256 maxReward;
        uint256 maxLevel;
        uint256 freeTierMultiplier;
        uint256 bonusMultiplier;
        uint256 idleMultiplier;
    }

    struct DailyBattleSettings {
        uint256 freeMaxDailyBattles;
        uint256 freeBattleRegenerationTime;
        uint256 standardMaxDailyBattles;
        uint256 standardBattleRegenerationTime;
        uint256 maxFreeTierDailyBattlesPerAddress;
    }

    struct BattleSettings {
        bool equipmentOn;
        bool energyOn;
        uint8 energyLossChallenger;
        uint8 energyLossOpponent;
    }

    struct BattlePack {
        uint256 price;
        uint256 numberOfBattles;
        bool active;
    }

    struct Battle {
        uint256 winner;
        uint256 challenger;
        uint256 opponent;
        address challengerAddress;
        address opponentAddress;
        AttackStyle challengerStyle;
        AttackStyle opponentStyle;
        uint256 challengerTotalLevel;
        uint256 opponentTotalLevel;
        uint8[3] challengerSkillLevels;
        uint8[3] opponentSkillLevels;
    }

    struct BattleComputationData {
        uint8[3] challengerSkillLevels;
        uint8[3] opponentSkillLevels;
        uint256 challengerTotalLevel;
        uint256 opponentTotalLevel;
        uint256 challengerStyleLevel;
        uint256 opponentStyleLevel;
        TokiemonNFT.Rarity challengerRarity;
        TokiemonNFT.Rarity opponentRarity;
        AttackStyle challengerStyle;
        AttackStyle opponentStyle;
        TokiemonEquipment.ItemEffect challengerEquipmentEffect;
        TokiemonEquipment.ItemEffect opponentEquipmentEffect;
        TokiemonEnergy.TokiemonEnergyStatus challengerEnergyStatus;
    }

    struct EnergyThreshold {
        uint256 threshold;
        int256 adjustment;
    }

    enum AttackStyle {
        Attack,
        Defense,
        Magic
    }

    constructor(address _tokiemonNFT, address _manaSystem, address _tokiemonEquipment, address _tokiemonEnergy, address _oracle) {
        tokiemonNFT = TokiemonNFT(_tokiemonNFT);
        manaSystem = ManaSystem(_manaSystem);
        tokiemonEquipment = TokiemonEquipment(_tokiemonEquipment);
        tokiemonEnergy = TokiemonEnergy(_tokiemonEnergy);
        oracle = Oracle(_oracle);

        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(MINTER_ROLE, msg.sender);

        rewardConfig = RewardConfig({
            minReward: 22,
            maxReward: 222,
            maxLevel: 297,
            freeTierMultiplier: 100,
            bonusMultiplier: 100,
            idleMultiplier: 20
        });
        dailyBattleSettings = DailyBattleSettings({
            freeMaxDailyBattles: 2,
            freeBattleRegenerationTime: 12 hours,
            standardMaxDailyBattles: 4,
            standardBattleRegenerationTime: 6 hours,
            maxFreeTierDailyBattlesPerAddress: 5
        });
        battleSettings = BattleSettings({equipmentOn: true, energyOn: true, energyLossChallenger: 10, energyLossOpponent: 3});

        energyThresholds.push(EnergyThreshold(25, -10));
        energyThresholds.push(EnergyThreshold(50, -5));
        energyThresholds.push(EnergyThreshold(80, 0));
        energyThresholds.push(EnergyThreshold(100, 5));
        criticalEnergyThreshold = 10;
        criticalEnergyProbability = 25;
    }

    /*
        View Functions
    */

    function getTotalBattlesLeft(uint256 tokenId) public view returns (uint256) {
        return getAvailableBattles(tokenId) + purchasedBattles[tokenId];
    }

    function getBattleResult(uint256 battleId) external view returns (Battle memory) {
        return battles[battleId];
    }

    function getBattlesLeftBreakdown(uint256 tokenId) public view returns (uint256, uint256) {
        return (purchasedBattles[tokenId], getAvailableBattles(tokenId));
    }

    function getAvailableBattles(uint256 tokenId) public view returns (uint256) {
        (, , uint256 purchaseTier, ) = tokiemonNFT.getTokiemonData(tokenId);
        uint256 maxDailyBattles = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeMaxDailyBattles
            : dailyBattleSettings.standardMaxDailyBattles;
        uint256 regenerationTime = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeBattleRegenerationTime
            : dailyBattleSettings.standardBattleRegenerationTime;

        uint256 elapsedTime = block.timestamp - lastBattleTimestamp[tokenId];
        uint256 regeneratedBattles = (elapsedTime + regenSurplus[tokenId]) / regenerationTime;
        return Math.min(availableBattles[tokenId] + regeneratedBattles, maxDailyBattles);
    }

    function getNextBattleRegenerationTime(uint256 tokenId) public view returns (uint256) {
        (, , uint256 purchaseTier, ) = tokiemonNFT.getTokiemonData(tokenId);
        uint256 maxDailyBattles = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeMaxDailyBattles
            : dailyBattleSettings.standardMaxDailyBattles;
        uint256 regenerationTime = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeBattleRegenerationTime
            : dailyBattleSettings.standardBattleRegenerationTime;

        if (getAvailableBattles(tokenId) >= maxDailyBattles) {
            return 0;
        }
        uint256 elapsedTime = block.timestamp - lastBattleTimestamp[tokenId];
        uint256 timeUntilNextBattle = regenerationTime - ((elapsedTime + regenSurplus[tokenId]) % regenerationTime);
        return block.timestamp + timeUntilNextBattle;
    }

    function getRemainingDailyFreeTierBattles(address player) public view returns (uint256) {
        uint256 currentDay = block.timestamp / 1 days;
        uint256 lastResetDay = lastDailyResetForFreeTierByAddress[player] / 1 days;

        if (currentDay > lastResetDay) {
            return dailyBattleSettings.maxFreeTierDailyBattlesPerAddress;
        }

        return dailyBattleSettings.maxFreeTierDailyBattlesPerAddress - dailyFreeTierBattlesUsedByAddress[player];
    }

    function getEnergyProbabilityImpact(uint256 currentEnergy) public view returns (int256) {
        if (currentEnergy <= criticalEnergyThreshold) {
            return -9975;
        }

        int256 energyProbabilityImpact = energyThresholds[energyThresholds.length - 1].adjustment;
        for (uint256 i = 0; i < energyThresholds.length; i++) {
            if (currentEnergy <= energyThresholds[i].threshold) {
                energyProbabilityImpact = energyThresholds[i].adjustment;
                break;
            }
        }

        return energyProbabilityImpact;
    }

    function calculateBattleReward(uint256 winnerTokenId, uint256 loserTokenId, uint256 challengerTokenId) public view returns (uint256) {
        (, uint256 totalLevel, ) = getSkillInfo(loserTokenId);
        (, , uint256 purchaseTier, ) = tokiemonNFT.getTokiemonData(winnerTokenId);

        uint256 reward = totalLevel +
            rewardConfig.minReward +
            ((rewardConfig.maxReward - rewardConfig.minReward) * (Math.log2(totalLevel) - 1)) /
            (Math.log2(rewardConfig.maxLevel) - 1);

        // Ensure reward stays within bounds (not strictly necessary, but added for safety)
        reward = Math.min(Math.max(reward, rewardConfig.minReward), rewardConfig.maxReward + totalLevel);

        // Modify Reward for Free Tier Players
        bool isFreeTier = purchaseTier == freeTier;
        if (isFreeTier) {
            reward = (reward * rewardConfig.freeTierMultiplier) / 100;
        }

        // Modify Reward for Idle Players
        if (winnerTokenId != challengerTokenId) {
            reward = (reward * rewardConfig.idleMultiplier) / 100;
        }

        // Double XP Weekend, Anon?
        return (reward * rewardConfig.bonusMultiplier) / 100;
    }

    function getSkillInfo(uint256 tokenId) public view returns (uint8[3] memory skillLevels, uint256 totalLevel, AttackStyle bestSkill) {
        TokiemonNFT.Skill memory attackSkill = tokiemonNFT.getTokiemonSkill(tokenId, uint256(AttackStyle.Attack));
        TokiemonNFT.Skill memory defenseSkill = tokiemonNFT.getTokiemonSkill(tokenId, uint256(AttackStyle.Defense));
        TokiemonNFT.Skill memory magicSkill = tokiemonNFT.getTokiemonSkill(tokenId, uint256(AttackStyle.Magic));

        skillLevels = [attackSkill.level, defenseSkill.level, magicSkill.level];
        totalLevel = uint256(attackSkill.level) + uint256(defenseSkill.level) + uint256(magicSkill.level);

        if (attackSkill.level >= defenseSkill.level && attackSkill.level >= magicSkill.level) {
            bestSkill = AttackStyle.Attack;
        } else if (defenseSkill.level >= magicSkill.level) {
            bestSkill = AttackStyle.Defense;
        } else {
            bestSkill = AttackStyle.Magic;
        }
    }

    /*
        Buying Battles Functions
    */

    function buyBattles(uint256 _tokenId, uint256 _packId) external payable {
        BattlePack memory pack = battlePacks[_packId];
        require(pack.numberOfBattles > 0, "Invalid battle pack");
        require(pack.active, "Battle pack is not active");
        require(msg.value >= pack.price, "Insufficient payment");

        _processBattlePurchase(_tokenId, _packId);
    }

    function buyBattlesWithERC20(uint256 _tokenId, uint256 _packId, address paymentToken, uint256 maxPaymentTokenAmount) external {
        BattlePack memory pack = battlePacks[_packId];
        require(pack.numberOfBattles > 0, "Invalid battle pack");
        require(pack.active, "Battle pack is not active");
        require(oracle.isTokenWhitelisted(paymentToken), "Payment token not whitelisted");

        (, uint256 tokenAmount) = oracle.calculateTokenAmount(paymentToken, pack.price, 1);
        require(tokenAmount <= maxPaymentTokenAmount, "Slippage: amount exceeds maximum");

        (uint256 burnAmount, uint256 daoAmount, uint256 partnerAmount, address partnerWallet) = oracle.calculateTokenDistribution(
            paymentToken,
            tokenAmount
        );

        transferTokens(IERC20(paymentToken), burnAmount, daoAmount, partnerAmount, partnerWallet);

        _processBattlePurchase(_tokenId, _packId);
    }

    /*
        Core Battle Functionality
    */

    function battle(uint256 challengerTokenId, uint256 opponentTokenId, AttackStyle challengerStyle) external {
        (, , uint256 purchaseTier, ) = tokiemonNFT.getTokiemonData(challengerTokenId);
        bool isFreeTier = purchaseTier == freeTier;

        require(tokiemonNFT.ownerOf(challengerTokenId) == msg.sender, "You don't own the challenger Tokiemon");
        require(tokiemonNFT.ownerOf(opponentTokenId) != address(0), "Opponent Tokiemon doesn't exist");
        require(challengerTokenId != opponentTokenId, "Don't hurt yourself!");
        require(tokiemonNFT.ownerOf(opponentTokenId) != msg.sender, "Cannot battle against your own Tokiemon");

        if (lastBattleTimestamp[challengerTokenId] == 0) {
            lastBattleTimestamp[challengerTokenId] = block.timestamp - 24 hours;
        }

        _updateAvailableBattles(challengerTokenId);
        uint256 battlesLeft = getTotalBattlesLeft(challengerTokenId);
        require(battlesLeft > 0, "No battles left");

        // Check if using a regenerated battle (which would count use paid battles)
        bool usingRegeneratedBattle = availableBattles[challengerTokenId] > 0;
        if (isFreeTier && usingRegeneratedBattle) {
            _checkAndUpdateDailyFreeTierLimit(msg.sender);
            require(
                dailyFreeTierBattlesUsedByAddress[msg.sender] < dailyBattleSettings.maxFreeTierDailyBattlesPerAddress ||
                    purchasedBattles[challengerTokenId] > 0,
                "Daily free tier battle limit reached"
            );
        }

        if (usingRegeneratedBattle) {
            availableBattles[challengerTokenId]--;
            if (isFreeTier) {
                dailyFreeTierBattlesUsedByAddress[msg.sender]++;
            }
        } else {
            purchasedBattles[challengerTokenId]--;
        }

        (, , AttackStyle opponentStyle) = getSkillInfo(opponentTokenId);
        uint256 winner = generateWinner(challengerTokenId, opponentTokenId, challengerStyle);
        uint256 loser = winner == challengerTokenId ? opponentTokenId : challengerTokenId;

        uint256 reward = calculateBattleReward(winner, loser, challengerTokenId);
        manaSystem.addMana(tokiemonNFT.ownerOf(winner), reward);

        // Decrease energy for the loser
        if (battleSettings.energyOn) {
            if (loser == challengerTokenId) {
                tokiemonEnergy.decreaseEnergy(challengerTokenId, battleSettings.energyLossChallenger);
            } else {
                tokiemonEnergy.decreaseEnergy(opponentTokenId, battleSettings.energyLossOpponent);
            }
        }

        _createBattleAndEmitEvent(challengerTokenId, opponentTokenId, challengerStyle, opponentStyle, winner);
    }

    function generateWinner(
        uint256 challengerTokenId,
        uint256 opponentTokenId,
        AttackStyle challengerStyle
    ) private view returns (uint256 winner) {
        uint256 winProbability = calculateWinProbability(challengerTokenId, opponentTokenId, challengerStyle);

        uint256 randomNumber = uint256(
            keccak256(abi.encodePacked(block.timestamp, block.prevrandao, msg.sender, challengerTokenId, opponentTokenId))
        ) % 10000;

        winner = randomNumber < winProbability ? challengerTokenId : opponentTokenId;

        return winner;
    }

    function calculateWinProbability(
        uint256 challengerTokenId,
        uint256 opponentTokenId,
        AttackStyle challengerStyle
    ) public view returns (uint256) {
        BattleComputationData memory data = _initializeBattleData(challengerTokenId, opponentTokenId, challengerStyle);

        int256 winProbability = 5000;
        winProbability = _calculateStyleMatchup(winProbability, data.challengerStyle, data.opponentStyle);
        winProbability = _calculateRarityDifferential(winProbability, data.challengerRarity, data.opponentRarity);
        winProbability = _calculateLevelDifferentials(
            winProbability,
            data.challengerStyleLevel,
            data.opponentStyleLevel,
            data.challengerTotalLevel,
            data.opponentTotalLevel
        );

        if (battleSettings.equipmentOn) {
            winProbability = _applyEquipmentImpact(winProbability, data.challengerEquipmentEffect, data.opponentEquipmentEffect);
        }

        if (battleSettings.energyOn) {
            winProbability = _applyEnergyImpact(winProbability, data.challengerEnergyStatus);
        }

        if (winProbability < 0) {
            winProbability = 0;
        }

        // Final win probability adjustment between 0.25% and 99.75%
        return uint256(Math.max(Math.min(9975, uint256(winProbability)), 25));
    }

    /*
        Helper Functions
    */

    function _initializeBattleData(
        uint256 challengerTokenId,
        uint256 opponentTokenId,
        AttackStyle challengerStyle
    ) private view returns (BattleComputationData memory data) {
        (data.challengerSkillLevels, data.challengerTotalLevel, ) = getSkillInfo(challengerTokenId);
        (data.opponentSkillLevels, data.opponentTotalLevel, data.opponentStyle) = getSkillInfo(opponentTokenId);
        data.challengerStyleLevel = data.challengerSkillLevels[uint256(challengerStyle)];
        data.opponentStyleLevel = data.opponentSkillLevels[uint256(data.opponentStyle)];
        data.challengerStyle = challengerStyle;

        (, , , data.challengerRarity) = tokiemonNFT.getTokiemonData(challengerTokenId);
        (, , , data.opponentRarity) = tokiemonNFT.getTokiemonData(opponentTokenId);

        if (battleSettings.equipmentOn) {
            data.challengerEquipmentEffect = tokiemonEquipment.getTotalEquipmentEffect(challengerTokenId);
            data.opponentEquipmentEffect = tokiemonEquipment.getTotalEquipmentEffect(opponentTokenId);
            data = _applyEquipmentBonuses(data);
        }

        if (battleSettings.energyOn) {
            data.challengerEnergyStatus = tokiemonEnergy.getTokiemonEnergyStatus(challengerTokenId);
            data = _applyEnergyBonuses(data);
        }

        return data;
    }

    function _applyEquipmentBonuses(BattleComputationData memory data) private pure returns (BattleComputationData memory) {
        data.challengerTotalLevel +=
            data.challengerEquipmentEffect.attackBonus +
            data.challengerEquipmentEffect.defenseBonus +
            data.challengerEquipmentEffect.magicBonus;
        data.opponentTotalLevel +=
            data.opponentEquipmentEffect.attackBonus +
            data.opponentEquipmentEffect.defenseBonus +
            data.opponentEquipmentEffect.magicBonus;

        data.challengerStyleLevel += data.challengerStyle == AttackStyle.Attack
            ? data.challengerEquipmentEffect.attackBonus
            : data.challengerStyle == AttackStyle.Defense
            ? data.challengerEquipmentEffect.defenseBonus
            : data.challengerEquipmentEffect.magicBonus;
        data.opponentStyleLevel += data.opponentStyle == AttackStyle.Attack
            ? data.opponentEquipmentEffect.attackBonus
            : data.opponentStyle == AttackStyle.Defense
            ? data.opponentEquipmentEffect.defenseBonus
            : data.opponentEquipmentEffect.magicBonus;

        return data;
    }

    function _applyEnergyBonuses(BattleComputationData memory data) private view returns (BattleComputationData memory) {
        if (
            data.challengerEnergyStatus.skillImpactExpiry > block.timestamp &&
            data.challengerEnergyStatus.skillId == uint256(data.challengerStyle)
        ) {
            if (data.challengerEnergyStatus.skillImpactIncrease) {
                data.challengerStyleLevel += data.challengerEnergyStatus.skillImpactAmount;
            } else {
                data.challengerStyleLevel -= data.challengerEnergyStatus.skillImpactAmount;
            }
        }
        return data;
    }

    function _calculateStyleMatchup(
        int256 winProbability,
        AttackStyle challengerStyle,
        AttackStyle opponentStyle
    ) private pure returns (int256) {
        if (
            (challengerStyle == AttackStyle.Attack && opponentStyle == AttackStyle.Magic) ||
            (challengerStyle == AttackStyle.Defense && opponentStyle == AttackStyle.Attack) ||
            (challengerStyle == AttackStyle.Magic && opponentStyle == AttackStyle.Defense)
        ) {
            return winProbability + 500; // +5% for favorable matchup
        } else if (challengerStyle != opponentStyle) {
            return winProbability - 500; // -5% for unfavorable matchup
        }
        return winProbability;
    }

    function _calculateRarityDifferential(
        int256 winProbability,
        TokiemonNFT.Rarity challengerRarity,
        TokiemonNFT.Rarity opponentRarity
    ) private pure returns (int256) {
        return winProbability + (int256(uint256(challengerRarity)) - int256(uint256(opponentRarity))) * 300;
    }

    function _calculateLevelDifferentials(
        int256 winProbability,
        uint256 challengerStyleLevel,
        uint256 opponentStyleLevel,
        uint256 challengerTotalLevel,
        uint256 opponentTotalLevel
    ) private pure returns (int256) {
        int256 styleLevelDiff = int256(challengerStyleLevel) - int256(opponentStyleLevel);
        int256 totalLevelDiff = int256(challengerTotalLevel) - int256(opponentTotalLevel);
        return winProbability + (styleLevelDiff * 200) + (totalLevelDiff * 75);
    }

    function _applyEquipmentImpact(
        int256 winProbability,
        TokiemonEquipment.ItemEffect memory challengerEquipmentEffect,
        TokiemonEquipment.ItemEffect memory opponentEquipmentEffect
    ) private pure returns (int256) {
        int256 equipmentDiff = int256(challengerEquipmentEffect.overallBonus) - int256(opponentEquipmentEffect.overallBonus);
        return (winProbability * (100 + equipmentDiff)) / 100;
    }

    function _applyEnergyImpact(
        int256 winProbability,
        TokiemonEnergy.TokiemonEnergyStatus memory challengerEnergyStatus
    ) private view returns (int256) {
        if (challengerEnergyStatus.currentEnergy <= criticalEnergyThreshold) {
            return criticalEnergyProbability;
        }

        int256 energyAdjustment = energyThresholds[energyThresholds.length - 1].adjustment;
        for (uint256 i = 0; i < energyThresholds.length; i++) {
            if (challengerEnergyStatus.currentEnergy <= energyThresholds[i].threshold) {
                energyAdjustment = energyThresholds[i].adjustment;
                break;
            }
        }

        return (winProbability * (100 + energyAdjustment)) / 100;
    }

    function _createBattleAndEmitEvent(
        uint256 challengerTokenId,
        uint256 opponentTokenId,
        AttackStyle challengerStyle,
        AttackStyle opponentStyle,
        uint256 winner
    ) private {
        (uint8[3] memory challengerSkillLevels, uint256 challengerTotalLevel, ) = getSkillInfo(challengerTokenId);
        (uint8[3] memory opponentSkillLevels, uint256 opponentTotalLevel, ) = getSkillInfo(opponentTokenId);
        address opponentAddress = tokiemonNFT.ownerOf(opponentTokenId);

        battles[battleCount] = Battle(
            winner,
            challengerTokenId,
            opponentTokenId,
            msg.sender,
            opponentAddress,
            challengerStyle,
            opponentStyle,
            challengerTotalLevel,
            opponentTotalLevel,
            challengerSkillLevels,
            opponentSkillLevels
        );

        emit BattleComplete(
            battleCount,
            winner,
            challengerTokenId,
            opponentTokenId,
            msg.sender,
            opponentAddress,
            challengerStyle,
            opponentStyle,
            challengerTotalLevel,
            opponentTotalLevel,
            challengerSkillLevels,
            opponentSkillLevels
        );
        battleCount++;
    }

    function _updateAvailableBattles(uint256 tokenId) private {
        (, , uint256 purchaseTier, ) = tokiemonNFT.getTokiemonData(tokenId);
        uint256 maxDailyBattles = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeMaxDailyBattles
            : dailyBattleSettings.standardMaxDailyBattles;
        uint256 regenerationTime = (purchaseTier == freeTier)
            ? dailyBattleSettings.freeBattleRegenerationTime
            : dailyBattleSettings.standardBattleRegenerationTime;

        uint256 elapsedTime = block.timestamp - lastBattleTimestamp[tokenId];
        uint256 totalTime = elapsedTime + regenSurplus[tokenId];
        uint256 regeneratedBattles = totalTime / regenerationTime;

        // Update available battles
        availableBattles[tokenId] = Math.min(regeneratedBattles + availableBattles[tokenId], maxDailyBattles);

        // Update surplus time and last battle timestamp
        regenSurplus[tokenId] = totalTime % regenerationTime;
        lastBattleTimestamp[tokenId] = block.timestamp;
    }

    function _checkAndUpdateDailyFreeTierLimit(address player) private {
        // Reset counter if it's a new UTC day
        uint256 currentDay = block.timestamp / 1 days;
        uint256 lastResetDay = lastDailyResetForFreeTierByAddress[player] / 1 days;

        if (currentDay > lastResetDay) {
            dailyFreeTierBattlesUsedByAddress[player] = 0;
            lastDailyResetForFreeTierByAddress[player] = block.timestamp - (block.timestamp % 1 days); // Reset to start of UTC day
        }
    }

    function calculateTokenAmount(
        address paymentToken,
        uint256 packId
    ) public view returns (uint256 tokenPriceNative, uint256 tokenAmount) {
        BattlePack memory pack = battlePacks[packId];
        require(pack.active, "Battle pack is not active");
        require(pack.numberOfBattles > 0, "Invalid battle pack");

        return oracle.calculateTokenAmount(paymentToken, pack.price, 1);
    }

    function _processBattlePurchase(uint256 _tokenId, uint256 _packId) internal {
        BattlePack memory pack = battlePacks[_packId];
        purchasedBattles[_tokenId] += pack.numberOfBattles;
        emit BattlePackPurchased(_tokenId, pack.numberOfBattles);
    }

    function transferTokens(IERC20 token, uint256 burnAmount, uint256 daoAmount, uint256 partnerAmount, address partnerWallet) private {
        if (burnAmount > 0) {
            token.safeTransferFrom(msg.sender, oracle.DEAD_ADDRESS(), burnAmount);
        }
        if (daoAmount > 0) {
            token.safeTransferFrom(msg.sender, oracle.daoAddress(), daoAmount);
        }
        if (partnerAmount > 0 && partnerWallet != address(0)) {
            token.safeTransferFrom(msg.sender, partnerWallet, partnerAmount);
        }
    }

    /*
        Admin functions 
    */

    function addBattlePack(uint256 _price, uint256 _battles) external onlyRole(DEFAULT_ADMIN_ROLE) {
        battlePacks[nextBattlePackId] = BattlePack(_price, _battles, true);
        nextBattlePackId++;
    }

    function removeBattlePack(uint256 _packId) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(battlePacks[_packId].price > 0, "Pack does not exist");
        battlePacks[_packId].active = false;
    }

    function updateBattlePack(uint256 _packId, uint256 _price, uint256 _battles, bool _active) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(battlePacks[_packId].price > 0, "Pack does not exist");
        battlePacks[_packId] = BattlePack(_price, _battles, _active);
    }

    function addBattlesToToken(uint256 tokenId, uint256 amount) external onlyRole(MINTER_ROLE) {
        purchasedBattles[tokenId] += amount;
    }

    function setRewardConfig(
        uint256 _minReward,
        uint256 _maxReward,
        uint256 _maxLevel,
        uint256 _freeTierMultiplier,
        uint256 _bonusMultiplier,
        uint256 _idleMultiplier
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_minReward < _maxReward, "Min reward must be less than max reward");
        require(_maxLevel > 1, "Max level must be greater than 1");
        rewardConfig = RewardConfig({
            minReward: _minReward,
            maxReward: _maxReward,
            maxLevel: _maxLevel,
            freeTierMultiplier: _freeTierMultiplier,
            bonusMultiplier: _bonusMultiplier,
            idleMultiplier: _idleMultiplier
        });
    }

    function setDailyBattleSettings(
        uint256 _freeMaxDailyBattles,
        uint256 _freeBattleRegenerationTime,
        uint256 _standardMaxDailyBattles,
        uint256 _standardBattleRegenerationTime,
        uint256 _maxFreeTierDailyBattlesPerAddress
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        dailyBattleSettings = DailyBattleSettings({
            freeMaxDailyBattles: _freeMaxDailyBattles,
            freeBattleRegenerationTime: _freeBattleRegenerationTime,
            standardMaxDailyBattles: _standardMaxDailyBattles,
            standardBattleRegenerationTime: _standardBattleRegenerationTime,
            maxFreeTierDailyBattlesPerAddress: _maxFreeTierDailyBattlesPerAddress
        });
    }

    function setBattleSettings(
        bool _equipmentOn,
        bool _energyOn,
        uint8 _energyLossChallenger,
        uint8 _energyLossOpponent
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        battleSettings = BattleSettings({
            equipmentOn: _equipmentOn,
            energyOn: _energyOn,
            energyLossChallenger: _energyLossChallenger,
            energyLossOpponent: _energyLossOpponent
        });
    }

    function setEnergyThresholds(EnergyThreshold[] calldata _newThresholds) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_newThresholds.length > 0, "Must provide at least one threshold");
        require(_newThresholds[_newThresholds.length - 1].threshold == 100, "Last threshold must be 100");

        for (uint256 i = 1; i < _newThresholds.length; i++) {
            require(_newThresholds[i - 1].threshold < _newThresholds[i].threshold, "Thresholds must be in ascending order");
        }

        delete energyThresholds;
        for (uint256 i = 0; i < _newThresholds.length; i++) {
            energyThresholds.push(_newThresholds[i]);
        }
    }

    function setCriticalEnergySettings(uint256 _threshold, int256 _probability) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_threshold < energyThresholds[0].threshold, "Critical threshold must be less than first regular threshold");
        require(_probability >= 0 && _probability <= 9975, "Invalid critical energy probability");

        criticalEnergyThreshold = _threshold;
        criticalEnergyProbability = _probability;
    }

    function setOracle(address _oracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
        oracle = Oracle(_oracle);
    }

    function withdrawFunds(address payable _to) external onlyRole(DEFAULT_ADMIN_ROLE) {
        uint256 balance = address(this).balance;
        require(balance > 0, "No funds to withdraw");
        (bool sent, ) = _to.call{value: balance}("");
        require(sent, "Failed to send Ether");
    }

    function supportsPermissionedCallSelector(bytes4 /*selector*/) public pure override returns (bool) {
        return true;
    }
}
Contract Source Code
File 42 of 46: TokiemonEnergy.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {PermissionCallable} from "./permissions/PermissionCallable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./TokiemonNFT.sol";
import "./TokiemonItems.sol";

contract TokiemonEnergy is ERC1155Holder, AccessControl, ReentrancyGuard, PermissionCallable {
    TokiemonNFT public tokiemonNFT;
    TokiemonItems public tokiemonItems;

    bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");

    uint8 public minEnergy;
    uint8 public maxEnergy;
    uint256 public energyDecayInterval;
    uint8 public energyDecayAmount;
    uint256 public petCooldown;
    uint8 public petEnergyBoost;
    uint8 public startingEnergy;

    mapping(uint256 => uint8) public tokiemonEnergies;
    mapping(uint256 => uint256) public maxEnergyEffectExpiry;
    mapping(uint256 => uint256) public lastEnergyUpdateTime;
    mapping(uint256 => ItemEffect) public consumableEffects;
    mapping(uint256 => uint256) public lastPetTime;
    mapping(uint256 => ActiveSkillImpact) public activeSkillImpacts;

    // How we configure items
    // Attributes set to 0 implies not in use
    struct ItemEffect {
        uint8 energyBoost; // + impact on energy levels
        uint256 energyDuration; // MAX energy effect duration, in seconds
        SkillEffect skillEffect; // Impact on skill levels
    }

    // The effects on item has on skills
    struct SkillEffect {
        uint8 impactAmount;
        uint256 impactDuration;
        bool increase; // false = decrease
        uint256 skillId;
    }

    // The effects on skills that are currently active
    struct ActiveSkillImpact {
        uint8 impactAmount;
        uint256 impactExpiry;
        bool increase; // false = decrease
        uint256 skillId;
    }

    // A struct for viewing the energy status of a tokiemon
    struct TokiemonEnergyStatus {
        uint256 nextPetTime;
        uint8 currentEnergy;
        uint256 maxEnergyEffectExpiryTime;
        uint256 skillId;
        uint8 skillImpactAmount;
        uint256 skillImpactExpiry;
        bool skillImpactIncrease;
    }

    event EnergyUpdated(uint256 indexed tokenId, uint8 oldEnergy, uint8 newEnergy, string reason);
    event ItemConsumed(uint256 indexed tokenId, uint256 itemId, uint8 energyBoost, uint256 energyDuration);
    event TokiemonPetted(uint256 indexed tokenId, uint8 energyBoost);
    event SkillImpactApplied(uint256 indexed tokenId, uint256 skillId, uint8 impactAmount, uint256 impactExpiry, bool increase);

    constructor(address _tokiemonNFT, address _tokiemonItems) {
        tokiemonNFT = TokiemonNFT(_tokiemonNFT);
        tokiemonItems = TokiemonItems(_tokiemonItems);
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(MANAGER_ROLE, msg.sender);

        minEnergy = 1;
        maxEnergy = 100;
        energyDecayInterval = 1 hours;
        energyDecayAmount = 1;
        petCooldown = 4 hours;
        petEnergyBoost = 10;
        startingEnergy = 80;
    }

    /*
        View Functions
    */
    function getTokiemonEnergyStatus(uint256 tokenId) public view returns (TokiemonEnergyStatus memory) {
        require(tokiemonNFT.ownerOf(tokenId) != address(0), "Tokiemon does not exist");

        uint256 nextPetTime;
        if (lastPetTime[tokenId] == 0) {
            nextPetTime = 0; // Tokiemon has never been petted
        } else {
            uint256 calculatedNextPetTime = lastPetTime[tokenId] + petCooldown;
            nextPetTime = calculatedNextPetTime > block.timestamp ? calculatedNextPetTime : block.timestamp;
        }

        uint8 currentEnergy = getEnergy(tokenId);
        uint256 expiryTime = maxEnergyEffectExpiry[tokenId];

        ActiveSkillImpact memory skillImpact = activeSkillImpacts[tokenId];

        return
            TokiemonEnergyStatus(
                nextPetTime,
                currentEnergy,
                expiryTime,
                skillImpact.skillId,
                skillImpact.impactAmount,
                skillImpact.impactExpiry,
                skillImpact.increase
            );
    }

    function getBulkTokiemonEnergyStatus(uint256[] calldata tokenIds) external view returns (TokiemonEnergyStatus[] memory) {
        TokiemonEnergyStatus[] memory statuses = new TokiemonEnergyStatus[](tokenIds.length);
        for (uint256 i = 0; i < tokenIds.length; i++) {
            statuses[i] = getTokiemonEnergyStatus(tokenIds[i]);
        }
        return statuses;
    }

    function getConsumableEffectData(
        uint256 itemId
    ) external view returns (uint8 energyBoost, uint256 energyDuration, SkillEffect memory skillEffect) {
        ItemEffect memory effect = consumableEffects[itemId];
        return (effect.energyBoost, effect.energyDuration, effect.skillEffect);
    }

    function getEnergy(uint256 tokenId) public view returns (uint8) {
        require(tokiemonNFT.ownerOf(tokenId) != address(0), "Tokiemon does not exist");
        uint8 currentEnergy = tokiemonEnergies[tokenId];
        if (currentEnergy == 0) {
            return startingEnergy;
        }

        uint256 timePassedSinceUpdate = block.timestamp - lastEnergyUpdateTime[tokenId];
        uint256 maxEnergyExpiry = maxEnergyEffectExpiry[tokenId];

        if (block.timestamp <= maxEnergyExpiry) {
            // Max energy effect is still active
            return maxEnergy;
        }

        // Calculate decay after max energy effect expires
        if (maxEnergyExpiry > lastEnergyUpdateTime[tokenId]) {
            timePassedSinceUpdate = block.timestamp - maxEnergyExpiry;
            currentEnergy = maxEnergy;
        }

        uint256 decayPeriods = timePassedSinceUpdate / energyDecayInterval;
        if (decayPeriods > 0) {
            uint8 totalDecay = uint8(decayPeriods) * energyDecayAmount;
            return currentEnergy > totalDecay ? currentEnergy - totalDecay : minEnergy;
        }

        return currentEnergy;
    }

    function getNextPetTime(uint256 tokenId) public view returns (uint256) {
        require(tokiemonNFT.ownerOf(tokenId) != address(0), "Tokiemon does not exist");

        if (lastPetTime[tokenId] == 0) {
            return 0; // Tokiemon has never been petted
        }

        uint256 nextPetTime = lastPetTime[tokenId] + petCooldown;
        return nextPetTime > block.timestamp ? nextPetTime : block.timestamp;
    }

    /*
        User Functions
    */

    function consume(uint256 tokenId, uint256 itemId) external nonReentrant {
        _validateConsumption(tokenId, itemId);

        _spendItem(msg.sender, itemId);

        ItemEffect memory effect = consumableEffects[itemId];
        uint8 currentEnergy = getEnergy(tokenId);
        _applyAndUpdateEnergyEffect(tokenId, currentEnergy, effect);
        _applySkillEffect(tokenId, effect.skillEffect);

        emit ItemConsumed(tokenId, itemId, effect.energyBoost, effect.energyDuration);
    }

    function petTokiemon(uint256 tokenId) external nonReentrant {
        _petTokiemon(tokenId);
    }

    function bulkPetTokiemon(uint256[] calldata tokenIds) external nonReentrant {
        uint256 length = tokenIds.length;
        for (uint256 i = 0; i < length; i++) {
            _petTokiemon(tokenIds[i]);
        }
    }

    /*
        Helper Functions
    */

    function _petTokiemon(uint256 tokenId) internal {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        require(block.timestamp >= lastPetTime[tokenId] + petCooldown, "Tokiemon was pet too recently");

        uint8 currentEnergy = getEnergy(tokenId);
        require(currentEnergy < maxEnergy, "Tokiemon is already at max energy");

        uint8 oldEnergy = currentEnergy;
        uint8 newEnergy = currentEnergy + petEnergyBoost > maxEnergy ? maxEnergy : currentEnergy + petEnergyBoost;

        tokiemonEnergies[tokenId] = newEnergy;
        lastEnergyUpdateTime[tokenId] = block.timestamp;
        lastPetTime[tokenId] = block.timestamp;

        emit TokiemonPetted(tokenId, newEnergy - oldEnergy);
        emit EnergyUpdated(tokenId, oldEnergy, newEnergy, "Petting");
    }

    function _setConsumableEffect(
        uint256 itemId,
        uint8 energyBoost,
        uint256 energyDuration,
        bool hasSkillImpact,
        SkillEffect memory skillEffect
    ) internal {
        require(energyBoost == 0 || energyDuration == 0, "Cannot set both energyBoost and energyDuration");
        consumableEffects[itemId] = ItemEffect(energyBoost, energyDuration, hasSkillImpact ? skillEffect : SkillEffect(0, 0, false, 0));
    }

    function _validateConsumption(uint256 tokenId, uint256 itemId) internal view {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        require(
            consumableEffects[itemId].energyBoost > 0 ||
                consumableEffects[itemId].energyDuration > 0 ||
                consumableEffects[itemId].skillEffect.impactAmount > 0,
            "Item is not consumable"
        );
        require(tokiemonItems.balanceOf(msg.sender, itemId) > 0, "You don't have this item");
    }

    function _applyAndUpdateEnergyEffect(uint256 tokenId, uint8 currentEnergy, ItemEffect memory effect) internal returns (uint8) {
        uint8 newEnergy = currentEnergy;

        if (effect.energyDuration > 0) {
            maxEnergyEffectExpiry[tokenId] = block.timestamp + effect.energyDuration;
            newEnergy = maxEnergy;
        } else if (effect.energyBoost > 0) {
            newEnergy = uint8(min(uint256(currentEnergy) + effect.energyBoost, maxEnergy));
        }

        tokiemonEnergies[tokenId] = newEnergy;
        lastEnergyUpdateTime[tokenId] = block.timestamp;

        emit EnergyUpdated(tokenId, currentEnergy, newEnergy, "Item consumption");

        return newEnergy;
    }

    function _applySkillEffect(uint256 tokenId, SkillEffect memory skillEffect) internal {
        if (skillEffect.impactAmount > 0) {
            activeSkillImpacts[tokenId] = ActiveSkillImpact({
                skillId: skillEffect.skillId,
                impactAmount: skillEffect.impactAmount,
                impactExpiry: block.timestamp + skillEffect.impactDuration,
                increase: skillEffect.increase
            });

            emit SkillImpactApplied(
                tokenId,
                skillEffect.skillId,
                skillEffect.impactAmount,
                block.timestamp + skillEffect.impactDuration,
                skillEffect.increase
            );
        }
    }

    function _spendItem(address owner, uint256 itemId) internal {
        tokiemonItems.spendItem(owner, itemId, 1);
    }

    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /*
        Admin Functions
    */

    function setEnergy(uint256 tokenId, uint8 newEnergy) external onlyRole(MANAGER_ROLE) {
        require(newEnergy >= minEnergy && newEnergy <= maxEnergy, "Invalid energy value");
        require(tokiemonNFT.ownerOf(tokenId) != address(0), "Tokiemon does not exist");

        tokiemonEnergies[tokenId] = newEnergy;
        lastEnergyUpdateTime[tokenId] = block.timestamp;

        emit EnergyUpdated(tokenId, 0, newEnergy, "Manual set");
    }

    function decreaseEnergy(uint256 tokenId, uint8 amount) external onlyRole(MANAGER_ROLE) {
        require(tokiemonNFT.ownerOf(tokenId) != address(0), "Tokiemon does not exist");
        require(amount <= maxEnergy, "Amount must be less than or equal to max energy");
        if (amount == 0) {
            return;
        }

        uint8 currentEnergy = getEnergy(tokenId);
        uint8 newEnergy = currentEnergy > amount ? currentEnergy - amount : minEnergy;

        tokiemonEnergies[tokenId] = newEnergy;
        lastEnergyUpdateTime[tokenId] = block.timestamp;

        emit EnergyUpdated(tokenId, currentEnergy, newEnergy, "Energy decreased");
    }

    function setConsumableEffect(
        uint256 itemId,
        uint8 energyBoost,
        uint256 energyDuration,
        bool hasSkillImpact,
        SkillEffect memory skillEffect
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setConsumableEffect(itemId, energyBoost, energyDuration, hasSkillImpact, skillEffect);
    }

    function setEnergyParameters(
        uint8 _minEnergy,
        uint8 _maxEnergy,
        uint256 _energyDecayInterval,
        uint8 _energyDecayAmount,
        uint256 _petCooldown,
        uint8 _petEnergyBoost,
        uint8 _startingEnergy
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_minEnergy < _maxEnergy, "Invalid energy range");
        require(_startingEnergy >= _minEnergy && _startingEnergy <= _maxEnergy, "Invalid starting energy");
        minEnergy = _minEnergy;
        maxEnergy = _maxEnergy;
        energyDecayInterval = _energyDecayInterval;
        energyDecayAmount = _energyDecayAmount;
        petCooldown = _petCooldown;
        petEnergyBoost = _petEnergyBoost;
        startingEnergy = _startingEnergy;
    }

    function bulkSetConsumableEffects(
        uint256[] calldata itemIds,
        uint8[] calldata energyBoosts,
        uint256[] calldata energyDurations,
        bool[] calldata hasSkillImpact,
        SkillEffect[] calldata skillEffects
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(
            itemIds.length == energyBoosts.length &&
                itemIds.length == energyDurations.length &&
                itemIds.length == hasSkillImpact.length &&
                itemIds.length == skillEffects.length,
            "Array lengths must match"
        );

        for (uint256 i = 0; i < itemIds.length; i++) {
            _setConsumableEffect(itemIds[i], energyBoosts[i], energyDurations[i], hasSkillImpact[i], skillEffects[i]);
        }
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Holder, AccessControl) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    function supportsPermissionedCallSelector(bytes4 /*selector*/) public pure override returns (bool) {
        return true;
    }
}
Contract Source Code
File 43 of 46: TokiemonEquipment.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {PermissionCallable} from "./permissions/PermissionCallable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./TokiemonNFT.sol";
import "./TokiemonItems.sol";

contract TokiemonEquipment is ERC1155Holder, AccessControl, ReentrancyGuard, PermissionCallable {
    TokiemonNFT public tokiemonNFT;
    ITokiemonItems public tokiemonItems;
    uint256 public tokiemonSkillCount = 3;

    mapping(uint256 => mapping(Slot => uint256)) public equippedItems;
    mapping(uint256 => ItemConfig) public itemConfigs;

    enum Slot {
        None,
        Head,
        Weapon,
        Torso,
        Offhand,
        Legs,
        Special,
        Mystical,
        Amazing,
        Superior
    }

    struct ItemConfig {
        Slot primarySlot;
        Slot secondarySlot;
        SkillRequirement[5] skillRequirements;
        ItemEffect effect;
        uint8 skillRequirementCount;
    }

    struct SkillRequirement {
        uint256 skillId;
        uint8 skillLevel;
        bool isOverallSkill;
    }

    struct ItemEffect {
        uint256 attackBonus;
        uint256 defenseBonus;
        uint256 magicBonus;
        uint256 overallBonus;
    }

    event ItemConfigured(
        uint256 itemId,
        Slot primarySlot,
        Slot secondarySlot,
        SkillRequirement[] skillRequirements,
        uint256 attackBonus,
        uint256 defenseBonus,
        uint256 magicBonus,
        uint256 overallBonus
    );
    event TokiemonEquipmentUpdated(uint256 indexed tokenId, uint256[9] equippedItems);

    constructor(address _tokiemonNFT, address _tokiemonItems) {
        tokiemonNFT = TokiemonNFT(_tokiemonNFT);
        tokiemonItems = ITokiemonItems(_tokiemonItems);
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    /*
        View Functions
    */

    function getEquippedItem(uint256 tokenId, Slot slot) external view returns (uint256) {
        return equippedItems[tokenId][slot];
    }

    function getAllEquippedItems(uint256 tokenId) external view returns (uint256[9] memory) {
        uint256[9] memory items;
        for (uint256 i = 1; i <= 9; i++) {
            items[i - 1] = equippedItems[tokenId][Slot(i)];
        }
        return items;
    }

    function getTotalEquipmentEffect(uint256 tokenId) public view returns (ItemEffect memory) {
        ItemEffect memory totalEffect;
        for (uint256 i = 1; i <= uint256(Slot.Superior); i++) {
            uint256 itemId = equippedItems[tokenId][Slot(i)];
            if (itemId != 0) {
                ItemConfig memory config = itemConfigs[itemId];
                totalEffect.attackBonus += config.effect.attackBonus;
                totalEffect.defenseBonus += config.effect.defenseBonus;
                totalEffect.magicBonus += config.effect.magicBonus;
                totalEffect.overallBonus += config.effect.overallBonus;
            }
        }
        return totalEffect;
    }

    function getItemConfigData(
        uint256 itemId
    )
        external
        view
        returns (
            Slot primarySlot,
            Slot secondarySlot,
            SkillRequirement[5] memory skillRequirements,
            ItemEffect memory effect,
            uint8 skillRequirementCount
        )
    {
        ItemConfig memory config = itemConfigs[itemId];
        return (config.primarySlot, config.secondarySlot, config.skillRequirements, config.effect, config.skillRequirementCount);
    }

    /* 
        User Functions
    */

    function equipItem(uint256 tokenId, uint256 itemId) external nonReentrant {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        _equipItem(tokenId, itemId);

        _emitEquipmentUpdate(tokenId);
    }

    function unequipItem(uint256 tokenId, Slot slot) external nonReentrant {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        _unequipItem(tokenId, slot);

        _emitEquipmentUpdate(tokenId);
    }

    function bulkEquipItems(uint256 tokenId, uint256[] calldata itemIds) external nonReentrant {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        require(itemIds.length > 0, "No items to equip");

        for (uint256 i = 0; i < itemIds.length; i++) {
            _equipItem(tokenId, itemIds[i]);
        }

        _emitEquipmentUpdate(tokenId);
    }

    function bulkUnequipItems(uint256 tokenId, Slot[] calldata slots) external nonReentrant {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");
        require(slots.length > 0, "No slots to unequip");

        for (uint256 i = 0; i < slots.length; i++) {
            _unequipItem(tokenId, slots[i]);
        }

        _emitEquipmentUpdate(tokenId);
    }

    function updateAllEquipment(uint256 tokenId, uint256[9] calldata itemIds) external nonReentrant {
        require(tokiemonNFT.ownerOf(tokenId) == msg.sender, "Not the owner of the Tokiemon");

        for (uint256 i = 0; i < 9; i++) {
            Slot slot = Slot(i + 1);
            uint256 itemId = itemIds[i];

            if (itemId == 0) {
                // Unequip if there's an item in this slot
                if (equippedItems[tokenId][slot] != 0) {
                    _unequipItem(tokenId, slot);
                }
            } else {
                // Equip the new item
                _equipItem(tokenId, itemId);
            }
        }

        _emitEquipmentUpdate(tokenId);
    }

    /* 
        Helper Functions
    */

    function _equipItem(uint256 tokenId, uint256 itemId) internal returns (Slot) {
        ItemConfig memory config = itemConfigs[itemId];
        require(config.primarySlot != Slot.None, "Item is not equippable");

        // Get all skills and calculate total skill level
        uint256 totalSkillLevel = 0;
        TokiemonNFT.Skill[3] memory skills;
        for (uint256 i = 0; i < tokiemonSkillCount; i++) {
            skills[i] = tokiemonNFT.getTokiemonSkill(tokenId, i);
            totalSkillLevel += skills[i].level;
        }

        // Check if the Tokiemon meets all skill requirements
        for (uint8 i = 0; i < config.skillRequirementCount; i++) {
            SkillRequirement memory req = config.skillRequirements[i];
            if (req.isOverallSkill) {
                require(totalSkillLevel >= req.skillLevel, "Tokiemon does not meet the required overall skill level");
            } else {
                require(req.skillId < tokiemonSkillCount, "Invalid skill ID");
                require(skills[req.skillId].level >= req.skillLevel, "Tokiemon does not meet the required skill level");
            }
        }

        // Check if the item is already equipped in either primary or secondary slot
        bool alreadyEquipped = equippedItems[tokenId][config.primarySlot] == itemId &&
            (config.secondarySlot == Slot.None || equippedItems[tokenId][config.secondarySlot] == itemId);
        if (alreadyEquipped) {
            return config.primarySlot;
        }

        uint256[] memory itemIds = new uint256[](1);
        itemIds[0] = itemId;
        uint256[] memory amounts = new uint256[](1);
        amounts[0] = 1;

        // transfer item to contract
        tokiemonItems.whitelistTransfer(msg.sender, address(this), itemIds, amounts);

        // Unequip items in both primary and secondary slots if they exist
        if (equippedItems[tokenId][config.primarySlot] != 0) {
            _unequipItem(tokenId, config.primarySlot);
        }
        if (config.secondarySlot != Slot.None && equippedItems[tokenId][config.secondarySlot] != 0) {
            _unequipItem(tokenId, config.secondarySlot);
        }

        // Equip new item in primary slot
        equippedItems[tokenId][config.primarySlot] = itemId;

        // If there's a secondary slot, equip there too
        if (config.secondarySlot != Slot.None) {
            equippedItems[tokenId][config.secondarySlot] = itemId;
        }

        return config.primarySlot;
    }

    function _unequipItem(uint256 tokenId, Slot slot) internal returns (uint256) {
        uint256 itemId = equippedItems[tokenId][slot];
        require(itemId != 0, "No item equipped in this slot");

        // Transfer item back to the Tokiemon owner
        tokiemonItems.safeTransferFrom(address(this), tokiemonNFT.ownerOf(tokenId), itemId, 1, "");

        ItemConfig memory config = itemConfigs[itemId];

        delete equippedItems[tokenId][slot];

        // Check and clear both primary and secondary slots
        if (config.primarySlot != slot && equippedItems[tokenId][config.primarySlot] == itemId) {
            delete equippedItems[tokenId][config.primarySlot];
        }
        if (config.secondarySlot != Slot.None && config.secondarySlot != slot && equippedItems[tokenId][config.secondarySlot] == itemId) {
            delete equippedItems[tokenId][config.secondarySlot];
        }

        return itemId;
    }

    function _emitEquipmentUpdate(uint256 tokenId) internal {
        uint256[9] memory items;
        for (uint256 i = 1; i <= 9; i++) {
            items[i - 1] = equippedItems[tokenId][Slot(i)];
        }
        emit TokiemonEquipmentUpdated(tokenId, items);
    }

    /* 
        Admin Functions
    */

    function setTokiemonSkillCount(uint256 newCount) external onlyRole(DEFAULT_ADMIN_ROLE) {
        tokiemonSkillCount = newCount;
    }

    function configureItem(
        uint256 itemId,
        Slot primarySlot,
        Slot secondarySlot,
        SkillRequirement[] memory skillRequirements,
        ItemEffect memory effect
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        _configureItem(itemId, primarySlot, secondarySlot, skillRequirements, effect);
    }

    function configureMultipleItems(
        uint256[] calldata itemIds,
        Slot[] calldata primarySlots,
        Slot[] calldata secondarySlots,
        SkillRequirement[][] calldata skillRequirements,
        ItemEffect[] calldata effects
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(
            itemIds.length == primarySlots.length &&
                itemIds.length == secondarySlots.length &&
                itemIds.length == skillRequirements.length &&
                itemIds.length == effects.length,
            "Input arrays must have the same length"
        );

        for (uint256 i = 0; i < itemIds.length; i++) {
            _configureItem(itemIds[i], primarySlots[i], secondarySlots[i], skillRequirements[i], effects[i]);
        }
    }

    function _configureItem(
        uint256 itemId,
        Slot primarySlot,
        Slot secondarySlot,
        SkillRequirement[] memory skillRequirements,
        ItemEffect memory effect
    ) internal {
        require(primarySlot != Slot.None, "Primary slot cannot be None");
        require(skillRequirements.length <= 5, "Too many skill requirements");

        ItemConfig storage config = itemConfigs[itemId];
        config.primarySlot = primarySlot;
        config.secondarySlot = secondarySlot;
        config.effect = effect;
        config.skillRequirementCount = uint8(skillRequirements.length);

        for (uint8 i = 0; i < skillRequirements.length; i++) {
            config.skillRequirements[i] = skillRequirements[i];
        }

        emit ItemConfigured(
            itemId,
            primarySlot,
            secondarySlot,
            skillRequirements,
            effect.attackBonus,
            effect.defenseBonus,
            effect.magicBonus,
            effect.overallBonus
        );
    }

    function emergencyWithdraw(
        uint256[] calldata ids,
        uint256[] calldata amounts,
        address recipient
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(ids.length == amounts.length, "Mismatched ids and amounts");
        require(recipient != address(0), "Invalid recipient");

        tokiemonItems.safeBatchTransferFrom(address(this), recipient, ids, amounts, "");
    }

    /*
        Overrides
    */

    function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Holder, AccessControl) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    function supportsPermissionedCallSelector(bytes4 /*selector*/) public pure override returns (bool) {
        return true;
    }
}
Contract Source Code
File 44 of 46: TokiemonItems.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {PermissionCallable} from "./permissions/PermissionCallable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";

interface ITokiemonItems is IERC1155 {
    function whitelistTransfer(address from, address to, uint256[] memory ids, uint256[] memory amounts) external;
}

contract TokiemonItems is ERC1155, AccessControl, ERC1155Burnable, ERC1155Supply, PermissionCallable {
    bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant SPENDER_ROLE = keccak256("SPENDER_ROLE");
    bytes32 public constant EQUIPMENT_ROLE = keccak256("EQUIPMENT_ROLE");

    uint256 currentHighestId;
    mapping(uint256 => ItemConfig) public itemConfigs;
    mapping(address => bool) public whitelistedContracts;

    /*
        Data Types
    */
    enum TransferRestriction {
        Transferable,
        NonTransferable,
        WhitelistOnly
    }

    enum ItemType {
        Spendable,
        Consumable,
        Equipable,
        Collectible,
        Quest,
        Other
    }

    struct ItemConfig {
        TransferRestriction transferRestriction;
        ItemType itemType;
        uint256 maxSupply;
    }

    constructor() ERC1155("https://api.tokiemon.io/items/{id}") {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(MINTER_ROLE, msg.sender);
    }

    /* 
        View Functions
    */

    function getItemBalances(address account) public view returns (uint256[] memory ids, uint256[] memory balances) {
        uint256 count = 0;
        for (uint256 i = 1; i <= currentHighestId; i++) {
            if (balanceOf(account, i) > 0) {
                count++;
            }
        }
        ids = new uint256[](count);
        balances = new uint256[](count);

        uint256 index = 0;
        for (uint256 i = 1; i <= currentHighestId; i++) {
            uint256 balance = balanceOf(account, i);
            if (balance > 0) {
                ids[index] = i;
                balances[index] = balance;
                index++;
            }
        }

        return (ids, balances);
    }

    function isAvailable(uint256 id) external view returns (bool) {
        ItemConfig memory config = itemConfigs[id];
        if (config.maxSupply == 0) {
            return true; // No max supply constraint
        }
        return totalSupply(id) < config.maxSupply;
    }

    function getItemConfigData(uint256 id) external view returns (
        TransferRestriction transferRestriction,
        ItemType itemType,
        uint256 maxSupply
    ) {
        ItemConfig memory config = itemConfigs[id];
        return (config.transferRestriction, config.itemType, config.maxSupply);
    }

    /*
        Minting/Burning/Whitelist Functions
    */

    function mint(address account, uint256 id, uint256 amount, bytes memory data) public onlyRole(MINTER_ROLE) {
        ItemConfig memory config = itemConfigs[id];
        if (config.maxSupply > 0) {
            require(totalSupply(id) + amount <= config.maxSupply, "Exceeds maximum supply");
        }
        _mint(account, id, amount, data);
    }

    function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public onlyRole(MINTER_ROLE) {
        for (uint256 i = 0; i < ids.length; i++) {
            ItemConfig memory config = itemConfigs[ids[i]];
            if (config.maxSupply > 0) {
                require(totalSupply(ids[i]) + amounts[i] <= config.maxSupply, "Exceeds maximum supply");
            }
        }
        _mintBatch(to, ids, amounts, data);
    }

    function spendItem(address from, uint256 id, uint256 amount) public onlyRole(SPENDER_ROLE) {
        _burn(from, id, amount);
    }

    function spendBatchItems(address from, uint256[] memory ids, uint256[] memory amounts) public onlyRole(SPENDER_ROLE) {
        _burnBatch(from, ids, amounts);
    }

    function whitelistTransfer(address from, address to, uint256[] memory ids, uint256[] memory amounts) public onlyRole(EQUIPMENT_ROLE) {
        _update(from, to, ids, amounts);
    }

    /*
        Admin Functions
    */

    function setURI(string memory newuri) public onlyRole(URI_SETTER_ROLE) {
        _setURI(newuri);
    }

    function setItemConfig(
        uint256 id,
        TransferRestriction restriction,
        uint256 maxSupply,
        ItemType itemType
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        _setAndUpdateHighestId(id, restriction, maxSupply, itemType);
    }

    function setBulkItemConfigs(
        uint256[] memory ids,
        TransferRestriction[] memory restrictions,
        uint256[] memory maxSupplies,
        ItemType[] memory itemTypes
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        require(
            ids.length == restrictions.length && ids.length == maxSupplies.length && ids.length == itemTypes.length,
            "Input arrays must have the same length"
        );
        for (uint256 i = 0; i < ids.length; i++) {
            _setAndUpdateHighestId(ids[i], restrictions[i], maxSupplies[i], itemTypes[i]);
        }
    }

    function _setAndUpdateHighestId(uint256 id, TransferRestriction restriction, uint256 maxSupply, ItemType itemType) internal {
        itemConfigs[id] = ItemConfig(restriction, itemType, maxSupply);
        if (id > currentHighestId) {
            currentHighestId = id;
        }
    }

    function setWhitelistedContract(address contractAddress, bool isWhitelisted) public onlyRole(DEFAULT_ADMIN_ROLE) {
        whitelistedContracts[contractAddress] = isWhitelisted;
    }

    /*
        Solidity Overrides
    */

    function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal override(ERC1155, ERC1155Supply) {
        for (uint256 i = 0; i < ids.length; i++) {
            ItemConfig memory config = itemConfigs[ids[i]];
            if (from != address(0) && to != address(0)) {
                // Transfer
                if (config.transferRestriction == TransferRestriction.NonTransferable) {
                    revert("Item is not transferable");
                } else if (config.transferRestriction == TransferRestriction.WhitelistOnly) {
                    require(whitelistedContracts[from] || whitelistedContracts[to], "Either sender or recipient must be whitelisted");
                }
            }
        }
        super._update(from, to, ids, values);
    }

    function supportsInterface(bytes4 interfaceId) public view override(ERC1155, AccessControl) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    function supportsPermissionedCallSelector(bytes4 /*selector*/) public pure override returns (bool) {
        return true;
    }
}
Contract Source Code
File 45 of 46: TokiemonNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/common/ERC2981.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ManaSystem.sol";

/// @custom:security-contact tokiemon [at] almalabs.io
contract TokiemonNFT is ERC721, ERC721Enumerable, ERC721Pausable, AccessControl, ERC721Burnable, ERC2981, ReentrancyGuard {
    using Strings for uint256;

    uint16 public constant RARITY_PRECISION = 10000;
    uint96 public constant DEFAULT_ROYALTY_PERCENTAGE = 250;
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    uint256 private _nextTokenId;
    uint256[] public activeTiers;
    ManaSystem public manaSystem;
    address public royaltyReceiver;

    struct TokiemonData {
        string communityId;
        string name;
        uint256 purchaseTier;
        Rarity rarity;
        mapping(uint256 => Skill) skills;
    }

    mapping(uint256 => TokiemonData) private _tokiemonData;
    mapping(uint256 => uint8) public skillMaxLevels;
    mapping(uint256 => RarityProbabilities) public tierToRarityProbabilities;

    // Data Type Definitions
    enum Rarity {
        Common,
        Uncommon,
        Rare,
        Epic,
        Legendary
    }
    struct RarityProbabilities {
        uint16 common;
        uint16 uncommon;
        uint16 rare;
        uint16 epic;
        uint16 legendary;
    }
    struct Skill {
        uint8 level;
        uint32 manaPerLevelMultiplier;
        uint32 manaUntilNextLevel;
        uint256 cumulativeMana;
    }

    event SkillManaApplied(uint256 indexed tokenId, uint256 indexed skillId, uint256 manaAmount, uint8 newLevel, uint256 newMana);
    event TokiemonSkillsUpdated(uint256 indexed tokenId, uint256[] skillIds, Skill[] updatedSkills);
    event NameChanged(uint256 indexed tokenId, string newName);
    event TokiemonMinted(
        uint256 indexed tokenId,
        address indexed to,
        string communityId,
        uint256 purchaseTier,
        Rarity rarity,
        address paymentToken
    );

    constructor(address defaultAdmin, address pauser, address minter) ERC721("Tokiemon", "TOKIE") {
        _grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
        _grantRole(PAUSER_ROLE, pauser);
        _grantRole(MINTER_ROLE, minter);

        royaltyReceiver = defaultAdmin;
        _setDefaultRoyalty(royaltyReceiver, DEFAULT_ROYALTY_PERCENTAGE);

        addRarityProbability(1, RarityProbabilities(6200, 3000, 500, 250, 50));
        addRarityProbability(2, RarityProbabilities(3000, 3800, 2000, 1000, 200));
        addRarityProbability(3, RarityProbabilities(500, 1500, 5000, 2500, 500));

        skillMaxLevels[0] = 99; // Attack
        skillMaxLevels[1] = 99; // Defense
        skillMaxLevels[2] = 99; // Magic
    }

    /*
        VIEW FUNCTIONS
    */

    function _baseURI() internal pure override returns (string memory) {
        return "https://api.tokiemon.io/tokiemon/";
    }

    function getActiveTiers() public view returns (uint256[] memory) {
        return activeTiers;
    }

    function getRarity(uint256 tokenId) public view returns (Rarity) {
        _requireOwned(tokenId);
        return _tokiemonData[tokenId].rarity;
    }

    function getTierRarityProbabilities(uint256 tier) public view returns (uint16, uint16, uint16, uint16, uint16) {
        RarityProbabilities memory probs = tierToRarityProbabilities[tier];
        return (probs.common, probs.uncommon, probs.rare, probs.epic, probs.legendary);
    }

    function _tierExists(uint256 tier) private view returns (bool) {
        return tierToRarityProbabilities[tier].common != 0;
    }

    function getTokiemonSkill(uint256 tokenId, uint256 skillId) public view returns (Skill memory) {
        _requireOwned(tokenId);
        return _tokiemonData[tokenId].skills[skillId];
    }

    function getTokiemonData(
        uint256 tokenId
    ) public view returns (string memory community, string memory name, uint256 purchaseTier, Rarity rarity) {
        _requireOwned(tokenId);
        TokiemonData storage data = _tokiemonData[tokenId];
        return (data.communityId, data.name, data.purchaseTier, data.rarity);
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireOwned(tokenId);
        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /*
        MINTING LOGIC
    */

    function safeMint(
        address to,
        uint256 tier,
        string memory communityId,
        address paymentToken,
        Skill[] memory initialSkills
    ) public onlyRole(MINTER_ROLE) returns (uint256) {
        require(_tierExists(tier), "Invalid tier");
        uint256 tokenId = _nextTokenId++;

        TokiemonData storage newTokiemon = _tokiemonData[tokenId];
        newTokiemon.communityId = communityId;
        newTokiemon.name = string(abi.encodePacked("Tokiemon #", tokenId.toString()));
        newTokiemon.purchaseTier = tier;
        newTokiemon.rarity = _determineRarity(tier);

        // Set initial skills
        for (uint256 i = 0; i < initialSkills.length; i++) {
            newTokiemon.skills[i] = initialSkills[i];
        }

        _safeMint(to, tokenId);

        emit TokiemonMinted(tokenId, to, communityId, tier, newTokiemon.rarity, paymentToken);

        return tokenId;
    }

    // Minimal rarity function. Choosing not to implement advanced randomness for now, since these NFTs are for entertainment purposes only :)
    function _determineRarity(uint256 purchaseTier) private view returns (Rarity) {
        RarityProbabilities memory probs = tierToRarityProbabilities[purchaseTier];
        uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao, _nextTokenId, msg.sender))) %
            RARITY_PRECISION;

        uint256 cumulativeProbability = 0;
        if (randomNumber < (cumulativeProbability += probs.common)) return Rarity.Common;
        if (randomNumber < (cumulativeProbability += probs.uncommon)) return Rarity.Uncommon;
        if (randomNumber < (cumulativeProbability += probs.rare)) return Rarity.Rare;
        if (randomNumber < (cumulativeProbability += probs.epic)) return Rarity.Epic;
        return Rarity.Legendary;
    }

    /*
        LEVELING LOGIC
    */
    function levelUpSkill(uint256 tokenId, uint256 skillId, uint256 manaAmount) public nonReentrant {
        require(msg.sender == ownerOf(tokenId), "Only owner can level up skills");
        require(manaSystem.getMana(msg.sender) >= manaAmount, "Insufficient mana");

        Skill storage skill = _tokiemonData[tokenId].skills[skillId];
        require(skill.level < skillMaxLevels[skillId], "Skill already at maximum level");

        manaSystem.spendMana(msg.sender, manaAmount);

        uint8 newLevel = skill.level;
        skill.cumulativeMana += manaAmount;

        uint256 surplusMana = calculateAnyLevelCost(tokenId, skillId, newLevel + 1) - skill.manaUntilNextLevel;
        uint256 manaAvailable = manaAmount + surplusMana;

        while (manaAvailable >= calculateAnyLevelCost(tokenId, skillId, newLevel + 1) && newLevel < skillMaxLevels[skillId]) {
            uint256 levelCost = calculateAnyLevelCost(tokenId, skillId, newLevel + 1);
            manaAvailable -= levelCost;
            newLevel++;
        }

        skill.level = newLevel;
        skill.manaUntilNextLevel = uint32(calculateAnyLevelCost(tokenId, skillId, newLevel + 1) - manaAvailable);

        emit SkillManaApplied(tokenId, skillId, manaAmount, newLevel, skill.manaUntilNextLevel);
    }

    function calculateAnyLevelCost(uint256 tokenId, uint256 skillId, uint8 level) public view returns (uint256) {
        Skill memory skill = _tokiemonData[tokenId].skills[skillId];
        return uint256(skill.manaPerLevelMultiplier) * uint256(level);
    }

    // get total mana required to level up to a certain level
    function getCumulativeManaRequiredToLevelUp(uint256 tokenId, uint256 skillId, uint8 level) public view returns (uint256) {
        uint256 totalMana = 0;
        Skill memory skill = _tokiemonData[tokenId].skills[skillId];

        for (uint8 i = skill.level + 1; i <= level; i++) {
            totalMana += i * skill.manaPerLevelMultiplier;
        }
        return totalMana;
    }

    function getNextLevelDelta(uint256 tokenId, uint256 skillId) public view returns (uint32) {
        Skill memory skill = _tokiemonData[tokenId].skills[skillId];
        return skill.manaUntilNextLevel;
    }

    /*
        TOKEN OWNER FUNCTIONS
    */
    function changeName(uint256 tokenId, string memory newName) public {
        require(ownerOf(tokenId) == msg.sender, "Only token owner can change name");
        _tokiemonData[tokenId].name = newName;
        emit NameChanged(tokenId, newName);
    }

    /*
        ADMIN LOGIC
    */
    function addRarityProbability(uint256 tier, RarityProbabilities memory probs) public onlyRole(DEFAULT_ADMIN_ROLE) {
        require(!_tierExists(tier), "Tier already exists");
        require(
            probs.common + probs.uncommon + probs.rare + probs.epic + probs.legendary == RARITY_PRECISION,
            "Probabilities must sum to 10000"
        );
        tierToRarityProbabilities[tier] = probs;
        activeTiers.push(tier);
    }

    function updateRarityProbability(uint256 tier, RarityProbabilities memory probs) public onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_tierExists(tier), "Tier does not exist");
        require(
            probs.common + probs.uncommon + probs.rare + probs.epic + probs.legendary == RARITY_PRECISION,
            "Probabilities must sum to 10000"
        );
        tierToRarityProbabilities[tier] = probs;
    }

    function removeRarityProbability(uint256 tier) public onlyRole(DEFAULT_ADMIN_ROLE) {
        require(_tierExists(tier), "Tier does not exist");
        for (uint256 i = 0; i < activeTiers.length; i++) {
            if (activeTiers[i] == tier) {
                activeTiers[i] = activeTiers[activeTiers.length - 1];
                activeTiers.pop();
                break;
            }
        }
        delete tierToRarityProbabilities[tier];
    }

    function pause() public onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() public onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    function setManaSystem(address _manaSystem) external onlyRole(DEFAULT_ADMIN_ROLE) {
        manaSystem = ManaSystem(_manaSystem);
    }

    function updateSkillMaxLevel(uint256 skillId, uint8 newMaxLevel) external onlyRole(DEFAULT_ADMIN_ROLE) {
        skillMaxLevels[skillId] = newMaxLevel;
    }

    function setRoyaltyInfo(address receiver, uint96 feeNumerator) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setDefaultRoyalty(receiver, feeNumerator);
        royaltyReceiver = receiver;
    }

    function updateTokiemonSkills(
        uint256 tokenId,
        uint256[] memory skillIds,
        Skill[] memory updatedSkills
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(skillIds.length == updatedSkills.length, "Skill IDs and updated skills must have the same length");
        _requireOwned(tokenId);

        for (uint256 i = 0; i < skillIds.length; i++) {
            uint256 skillId = skillIds[i];
            Skill memory updatedSkill = updatedSkills[i];

            require(updatedSkill.level <= skillMaxLevels[skillId], "Skill level exceeds maximum");

            _tokiemonData[tokenId].skills[skillId] = updatedSkill;
        }

        emit TokiemonSkillsUpdated(tokenId, skillIds, updatedSkills);
    }

    /* Solidity Required Overrides */
    function _update(
        address to,
        uint256 tokenId,
        address auth
    ) internal override(ERC721, ERC721Enumerable, ERC721Pausable) returns (address) {
        return super._update(to, tokenId, auth);
    }

    function _increaseBalance(address account, uint128 value) internal override(ERC721, ERC721Enumerable) {
        super._increaseBalance(account, value);
    }

    function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControl, ERC2981) returns (bool) {
        return super.supportsInterface(interfaceId);
    }
}
Contract Source Code
File 46 of 46: draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
Settings
{
  "compilationTarget": {
    "src/TokiemonBattles.sol": "TokiemonBattles"
  },
  "evmVersion": "paris",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "remappings": []
}
ABI
[{"inputs":[{"internalType":"address","name":"_tokiemonNFT","type":"address"},{"internalType":"address","name":"_manaSystem","type":"address"},{"internalType":"address","name":"_tokiemonEquipment","type":"address"},{"internalType":"address","name":"_tokiemonEnergy","type":"address"},{"internalType":"address","name":"_oracle","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"NotPermissionCallable","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"battleId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"winner","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"challenger","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"opponent","type":"uint256"},{"indexed":false,"internalType":"address","name":"challengerAddress","type":"address"},{"indexed":false,"internalType":"address","name":"opponentAddress","type":"address"},{"indexed":false,"internalType":"enum TokiemonBattles.AttackStyle","name":"challengerStyle","type":"uint8"},{"indexed":false,"internalType":"enum TokiemonBattles.AttackStyle","name":"opponentStyle","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"challengerTotalLevel","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"opponentTotalLevel","type":"uint256"},{"indexed":false,"internalType":"uint8[3]","name":"challengerSkillLevels","type":"uint8[3]"},{"indexed":false,"internalType":"uint8[3]","name":"opponentSkillLevels","type":"uint8[3]"}],"name":"BattleComplete","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"numberOfBattles","type":"uint256"}],"name":"BattlePackPurchased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINTER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_price","type":"uint256"},{"internalType":"uint256","name":"_battles","type":"uint256"}],"name":"addBattlePack","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"addBattlesToToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"availableBattles","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"challengerTokenId","type":"uint256"},{"internalType":"uint256","name":"opponentTokenId","type":"uint256"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"challengerStyle","type":"uint8"}],"name":"battle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"battleCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"battlePacks","outputs":[{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"numberOfBattles","type":"uint256"},{"internalType":"bool","name":"active","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"battleSettings","outputs":[{"internalType":"bool","name":"equipmentOn","type":"bool"},{"internalType":"bool","name":"energyOn","type":"bool"},{"internalType":"uint8","name":"energyLossChallenger","type":"uint8"},{"internalType":"uint8","name":"energyLossOpponent","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"battles","outputs":[{"internalType":"uint256","name":"winner","type":"uint256"},{"internalType":"uint256","name":"challenger","type":"uint256"},{"internalType":"uint256","name":"opponent","type":"uint256"},{"internalType":"address","name":"challengerAddress","type":"address"},{"internalType":"address","name":"opponentAddress","type":"address"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"challengerStyle","type":"uint8"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"opponentStyle","type":"uint8"},{"internalType":"uint256","name":"challengerTotalLevel","type":"uint256"},{"internalType":"uint256","name":"opponentTotalLevel","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_packId","type":"uint256"}],"name":"buyBattles","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"uint256","name":"_packId","type":"uint256"},{"internalType":"address","name":"paymentToken","type":"address"},{"internalType":"uint256","name":"maxPaymentTokenAmount","type":"uint256"}],"name":"buyBattlesWithERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"winnerTokenId","type":"uint256"},{"internalType":"uint256","name":"loserTokenId","type":"uint256"},{"internalType":"uint256","name":"challengerTokenId","type":"uint256"}],"name":"calculateBattleReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"paymentToken","type":"address"},{"internalType":"uint256","name":"packId","type":"uint256"}],"name":"calculateTokenAmount","outputs":[{"internalType":"uint256","name":"tokenPriceNative","type":"uint256"},{"internalType":"uint256","name":"tokenAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"challengerTokenId","type":"uint256"},{"internalType":"uint256","name":"opponentTokenId","type":"uint256"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"challengerStyle","type":"uint8"}],"name":"calculateWinProbability","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"criticalEnergyProbability","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"criticalEnergyThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dailyBattleSettings","outputs":[{"internalType":"uint256","name":"freeMaxDailyBattles","type":"uint256"},{"internalType":"uint256","name":"freeBattleRegenerationTime","type":"uint256"},{"internalType":"uint256","name":"standardMaxDailyBattles","type":"uint256"},{"internalType":"uint256","name":"standardBattleRegenerationTime","type":"uint256"},{"internalType":"uint256","name":"maxFreeTierDailyBattlesPerAddress","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"dailyFreeTierBattlesUsedByAddress","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"energyThresholds","outputs":[{"internalType":"uint256","name":"threshold","type":"uint256"},{"internalType":"int256","name":"adjustment","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"freeTier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getAvailableBattles","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"battleId","type":"uint256"}],"name":"getBattleResult","outputs":[{"components":[{"internalType":"uint256","name":"winner","type":"uint256"},{"internalType":"uint256","name":"challenger","type":"uint256"},{"internalType":"uint256","name":"opponent","type":"uint256"},{"internalType":"address","name":"challengerAddress","type":"address"},{"internalType":"address","name":"opponentAddress","type":"address"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"challengerStyle","type":"uint8"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"opponentStyle","type":"uint8"},{"internalType":"uint256","name":"challengerTotalLevel","type":"uint256"},{"internalType":"uint256","name":"opponentTotalLevel","type":"uint256"},{"internalType":"uint8[3]","name":"challengerSkillLevels","type":"uint8[3]"},{"internalType":"uint8[3]","name":"opponentSkillLevels","type":"uint8[3]"}],"internalType":"struct TokiemonBattles.Battle","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getBattlesLeftBreakdown","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"currentEnergy","type":"uint256"}],"name":"getEnergyProbabilityImpact","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getNextBattleRegenerationTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"player","type":"address"}],"name":"getRemainingDailyFreeTierBattles","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getSkillInfo","outputs":[{"internalType":"uint8[3]","name":"skillLevels","type":"uint8[3]"},{"internalType":"uint256","name":"totalLevel","type":"uint256"},{"internalType":"enum TokiemonBattles.AttackStyle","name":"bestSkill","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTotalBattlesLeft","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"lastBattleTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastDailyResetForFreeTierByAddress","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manaSystem","outputs":[{"internalType":"contract ManaSystem","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextBattlePackId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"contract Oracle","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"call","type":"bytes"}],"name":"permissionedCall","outputs":[{"internalType":"bytes","name":"res","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"purchasedBattles","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"regenSurplus","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_packId","type":"uint256"}],"name":"removeBattlePack","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardConfig","outputs":[{"internalType":"uint256","name":"minReward","type":"uint256"},{"internalType":"uint256","name":"maxReward","type":"uint256"},{"internalType":"uint256","name":"maxLevel","type":"uint256"},{"internalType":"uint256","name":"freeTierMultiplier","type":"uint256"},{"internalType":"uint256","name":"bonusMultiplier","type":"uint256"},{"internalType":"uint256","name":"idleMultiplier","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_equipmentOn","type":"bool"},{"internalType":"bool","name":"_energyOn","type":"bool"},{"internalType":"uint8","name":"_energyLossChallenger","type":"uint8"},{"internalType":"uint8","name":"_energyLossOpponent","type":"uint8"}],"name":"setBattleSettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_threshold","type":"uint256"},{"internalType":"int256","name":"_probability","type":"int256"}],"name":"setCriticalEnergySettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_freeMaxDailyBattles","type":"uint256"},{"internalType":"uint256","name":"_freeBattleRegenerationTime","type":"uint256"},{"internalType":"uint256","name":"_standardMaxDailyBattles","type":"uint256"},{"internalType":"uint256","name":"_standardBattleRegenerationTime","type":"uint256"},{"internalType":"uint256","name":"_maxFreeTierDailyBattlesPerAddress","type":"uint256"}],"name":"setDailyBattleSettings","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"threshold","type":"uint256"},{"internalType":"int256","name":"adjustment","type":"int256"}],"internalType":"struct TokiemonBattles.EnergyThreshold[]","name":"_newThresholds","type":"tuple[]"}],"name":"setEnergyThresholds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_oracle","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minReward","type":"uint256"},{"internalType":"uint256","name":"_maxReward","type":"uint256"},{"internalType":"uint256","name":"_maxLevel","type":"uint256"},{"internalType":"uint256","name":"_freeTierMultiplier","type":"uint256"},{"internalType":"uint256","name":"_bonusMultiplier","type":"uint256"},{"internalType":"uint256","name":"_idleMultiplier","type":"uint256"}],"name":"setRewardConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"name":"supportsPermissionedCallSelector","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"tokiemonEnergy","outputs":[{"internalType":"contract TokiemonEnergy","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokiemonEquipment","outputs":[{"internalType":"contract TokiemonEquipment","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokiemonNFT","outputs":[{"internalType":"contract TokiemonNFT","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_packId","type":"uint256"},{"internalType":"uint256","name":"_price","type":"uint256"},{"internalType":"uint256","name":"_battles","type":"uint256"},{"internalType":"bool","name":"_active","type":"bool"}],"name":"updateBattlePack","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_to","type":"address"}],"name":"withdrawFunds","outputs":[],"stateMutability":"nonpayable","type":"function"}]