ETH Price: $2,525.45 (+0.41%)

Contract Diff Checker

Contract Name:
GnomesNFT

Contract Source Code:

/*

░██████╗░███╗░░██╗░█████╗░███╗░░░███╗███████╗██╗░░░░░░█████╗░███╗░░██╗██████╗░
██╔════╝░████╗░██║██╔══██╗████╗░████║██╔════╝██║░░░░░██╔══██╗████╗░██║██╔══██╗
██║░░██╗░██╔██╗██║██║░░██║██╔████╔██║█████╗░░██║░░░░░███████║██╔██╗██║██║░░██║
██║░░╚██╗██║╚████║██║░░██║██║╚██╔╝██║██╔══╝░░██║░░░░░██╔══██║██║╚████║██║░░██║
╚██████╔╝██║░╚███║╚█████╔╝██║░╚═╝░██║███████╗███████╗██║░░██║██║░╚███║██████╔╝
░╚═════╝░╚═╝░░╚══╝░╚════╝░╚═╝░░░░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝╚═╝░░╚══╝╚═════╝░

                                   ╓╓╓▄▄▄▓▓█▓▓▓▓▀▀▀▀▀▀▓█
                             ╓▄██▀╙╙░░░░░░░░░░░░░░░░╠╬║█
                        ╓▄▓▀╙░░░░░░░░░░░░░░░░░░░░░░╠╠╠║▌
                     ╓█╩░░░░░░░░░░░░░░░░░░░░░░░░░░╠╠╠╠║▌
                   ▄█▒░░░░░░░░░░░░░▒▄██████▄▄░░░░░╠╠╠╠║▌
                 ╓██▀▀▀╙╙╚▀░░░░░▄██╩░░░░░░░░╙▀█▄▒░╠╠╠╠╬█
              ╓▓▀╙░░░░░░░░░░░░░╚╩░░░░░░░░░░░░░░╙▀█╠╠╠╠╬▓
             ▄╩░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░╠╠╠╠╠║▌
            ║██▓▓▓▓▓▄▄▒░░░░░░░░░░░▄▄██▓█▄▄▒░░░░░░░╠╠╠╠╠╬█
           ╔▀         ╙▀▀█▓▄▄▄██▀╙       └╙▀█▄▒░░░╠╠╠╠╠╠║▌
          ║█▀▀╙╙╙▀▀▓▄╖       ▄▄▓▓▓▓╗▄▄╓      ╙╙█▄▒░╠╠╠╠╠╬█
        ╓▀   ╓╓╓╓╓╓   ╙█▄ ▄▀╙          ╙▀▓▄      ╙▀▓▒▒╠╠╠║▌
        ▐██████████╙╙▀█▄ ╙█▄▓████████▀▀╗▄           █▀███╬█
        █║██████▌ ██    ╙██╓███████╙▀█   └▀╗╓       ║▒   ╙╙▓
       ╒▌╫███████╦╫█     ║ ╫███████╓▄█▌     └█╕     ║▌    ▀█▀▀
        █╚██████████    ╓╣ ║██████████▒    ╔▀╙      ║▒     └█
       ┌╣█╣████████╓╓▄▓▓▒▄█▄║████████▌╓╗╗▀╙        ╓█        ╚▄
       │█▄╗▀▀╙      ╙▀╙         ╙▀▀██▒            ▄█          ╙▄
     █▒                               ╙▀▀▀▀╠█▌╓▄▓▀             ║
      ╙█╓           ╓╓                   ╓██╩║▌                ║
       ╓╣███▄▄▄▄▓██╬╬╠╬███▄▄▄▄╓╓╓╓╓▄▄▄▓█╬╬▒░░╠█             ╔ ┌█
      ╓▌  ▀█╬╬▒╠╠╠╠░▒░░░╠╠╠╚╚╚╩╠╠╠╠╬███▀╩░░░▄█        ▓      █▀
     ╒▌   ╘█░╚╚╚╚╚▀▀▀▀▀▀▀▀▀▀▀▀▀▀╚╚╚░░░░░░▄█▀╙         ║      ▐▌
     ╟     └▀█▄▒▒▒░░░░░░░░░░░▒▒▒▒▒▄▄█▓╝▀╙                    ▐▌
     ║░        ╙╙▀▀▀▀▀▀▀▀▀▀▀▀▀▀╙╙                        ╓   █
      █                                                  ▓ ╓█
      ║▌   ╔                                            ╔█▀
       █   ╚▄                              ╓╩          ╔▀
       ╚▌   ╙                             ▓▀         ╓█╙
        ╙▌          ▐                  ╓═    ▄    ╓▄▀╙
          ▀▄        ╙▒                      ▄██▄█▀
            ╙▀▄╓║▄   └                    ▄╩
                ╙▀█                   ╓▄▀▀
                   ▀▓        ▄▄▓▀▀▀▀╙
                     └▀╗▄╓▄▀╙
    
    
https://www.gnomeland.money/
https://twitter.com/Gnome0xLand

$GNOMES

Everywhere...

// SPDX-License-Identifier: MIT

 */
pragma solidity ^0.8.0;
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol

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

// File: @openzeppelin/contracts/utils/math/SignedMath.sol

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

// File: @openzeppelin/contracts/utils/math/Math.sol

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

// File: @openzeppelin/contracts/utils/Strings.sol

// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

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

// File: @openzeppelin/contracts/utils/Context.sol

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

// File: @openzeppelin/contracts/utils/Pausable.sol

// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
// File: @openzeppelin/contracts/access/Ownable.sol

// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

pragma solidity ^0.8.20;

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

interface IGnomeURI {
    function _tokenURI(uint256 id) external view returns (string memory);
}

interface IMinimalNonfungiblePositionManager {
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

// libraries to separate ERC20 and ERC721 events, and certain signature-specific functions
// ERC20 events
library libSJ20 {
    event Transfer(address indexed from, address indexed to, uint amount);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    function emitTransfer(address _from, address _to, uint _amount) internal {
        emit Transfer(_from, _to, _amount);
    }

    function emitApproval(address _owner, address _spender, uint _value) internal {
        emit Approval(_owner, _spender, _value);
    }
}

// ERC721 events
library libSJ721 {
    event Transfer(address indexed _from, address indexed _to, uint indexed _tokenId);
    event Approval(address indexed _owner, address indexed _approved, uint indexed _tokenId);
    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

    function emitTransfer(address _from, address _to, uint _tokenId) internal {
        emit Transfer(_from, _to, _tokenId);
    }

    function emitApproval(address _owner, address _approve, uint _tokenId) internal {
        emit Approval(_owner, _approve, _tokenId);
    }

    function emitApprovalForAll(address _owner, address _operator, bool _approved) internal {
        emit ApprovalForAll(_owner, _operator, _approved);
    }
}

// ERC165 https://eips.ethereum.org/EIPS/eip-721
interface IERC165 {
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

// ERC20 https://eips.ethereum.org/EIPS/eip-20
interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// ERC721 https://eips.ethereum.org/EIPS/eip-721
interface IERC721 is IERC165 {
    function balanceOf(address account) external view returns (uint256);
    function ownerOf(uint256 _tokenId) external view returns (address);
    function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable;
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
    function setApprovalForAll(address _operator, bool _approved) external;
    function getApproved(uint256 _tokenId) external view returns (address);
    function isApprovedForAll(address _owner, address _operator) external view returns (bool);

    // payable removed for erc20 etherscan compatibility
    function approve(address spender, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

interface ISJ741 is IERC20, IERC721 {
    // library transfers can not be included in the interface
    // incorporate them directly with library
    // libSJ20.Transfer
    // libSJ20.Approval
    // libSJ721.Transfer
    // libSJ721.Approval
    // libSJ721.ApprovalForAll
    function balanceOf(address account) external view override(IERC20, IERC721) returns (uint256);
    function approve(address spender, uint256 value) external override(IERC20, IERC721) returns (bool);
    function transferFrom(address from, address to, uint256 value) external override(IERC20, IERC721) returns (bool);
}

// ERC721 Token Receiver https://eips.ethereum.org/EIPS/eip-721
interface IERC721TokenReceiver {
    function onERC721Received(
        address _operator,
        address _from,
        uint256 _tokenId,
        bytes memory _data
    ) external returns (bytes4);
}

interface IGnomeGamePlay {
    function isGnomeSignedUp(uint256 tokenId) external view returns (bool);
    function getMeditateTimeStamp(uint256 gnomeID) external view returns (uint256);
    function getSleepTimeStamp(uint256 gnomeID) external view returns (uint256);
    function getGnomeStats(
        uint256 tokenId
    )
        external
        view
        returns (
            string memory _gnomeX,
            uint256 _xp,
            uint256 _hp,
            uint256 _shieldTimeStamp,
            uint256 _meditationTimeStamp,
            bool[] memory _items,
            uint256 _activityAmount,
            uint256 _boopAmount,
            uint256 _WethSpent,
            uint256 _GnomeSpent,
            uint256 _lastHPUpdateTime,
            uint256 _gnomeEmotion
        );
    function setGnomeStats(
        uint256 tokenId,
        string memory _gnomeX,
        uint256 _xp,
        uint256 _hp,
        uint256 _shieldTimeStamp,
        uint256 _meditateTimeStamp,
        bool[] memory _items,
        uint256 _activityAmount,
        uint256 _boopAmount,
        uint256 _lastHPUpdateTime,
        uint256 _gnomeEmotion,
        uint256 _GnomeSpent,
        uint256 _WethSpent
    ) external returns (bool);
    function deleteGameStats(uint256 tokenId) external;
    function setGnomeX(uint256 tokenId, string memory gnomeX) external;
    function setGnomeXP(uint256 tokenId, uint256 xp) external;
    function setGnomeHP(uint256 tokenId, uint256 hp) external;
    function setisSignedUp(uint256 tokenId, bool _isSignedUp) external;
    function setBoopTimeStamp(uint256 tokenId, uint256 lastAtackTimeStamp) external;
    function setGnomeItems(uint256 tokenId, bool[] memory items) external;
    function setGnomeFeedAmount(string memory food, uint256 tokenId, uint256 _feedAmount) external;
    function setGnomeBoopAmount(uint256 tokenId, uint256 boopAmount) external;
    function getIsSleeping(uint256 tokenId) external view returns (bool);
    function setMeditateTimeStamp(uint256 tokenId, uint256 _meditateTimeStamp) external;
    function setGnomeHPUpdate(uint256 tokenId, uint256 lastHPUpdateTime) external;
    function setGnomeEmotion(uint256 tokenId, uint256 gnomeEmotion) external;
}

contract GnomesNFT is ISJ741, Ownable {
    /// @dev Token name
    string internal constant _name = "GnomeLand";
    /// @dev Token symbol
    string internal constant _symbol = "GNOMES";

    uint internal constant _decimals = 8;
    uint internal constant _totalIds = 555;
    uint internal _totalSupply = _totalIds * 10 ** _decimals;
    uint internal constant _maxSupply = 3333 * 10 ** _decimals;

    uint internal constant ONE = 10 ** _decimals; // 1.0 token(s)
    uint internal constant MAXID = ONE + _totalIds; // 1.00000001 : 1.00003333 is the range for NFT IDs

    uint32 public minted; // number of unique ID mints
    uint32[] private broken; // broken NFTs stored in limbo list
    string public baseTokenURI =
        "https://nftstorage.link/ipfs/bafkreie37v2cvci7sy3pnk53w4ju7k3pdtdipdq5hgon2zbkitmbmjnpiy";
    address public dev;
    bool public supportsNFTinterface;
    IGnomeURI public gnomeURI;
    IGnomeGamePlay public gnomeGamePlay;
    mapping(address => mapping(address => bool)) private _operatorApprovals;
    mapping(address => mapping(address => uint)) internal _allowance;
    mapping(uint256 tokenId => address) public ownerOf;
    mapping(uint256 => address) private _nftApprovals;
    mapping(address => uint) internal _balanceOf;
    mapping(address => uint32[]) public ownedNFTs;
    mapping(uint32 => uint256) private idToIndex;
    mapping(string => uint16) public destChainId;
    mapping(address => uint256) public treasuryMintTimeStamp;
    mapping(address => bool) public isAuth;
    bool gameActive = false;

    uint256 public factoryMints = 0;
    uint256 public maxfactoryMints = 690;
    error UnsupportedReceiver();

    modifier onlyDev() {
        require(msg.sender == dev, "Not the developer");
        _;
    }

    constructor(address _owner) Ownable(_owner) {
        minted = uint32(ONE);

        _balanceOf[msg.sender] = _totalSupply;
        dev = msg.sender;
        isAuth[msg.sender] = true;
    }

    function name() public view virtual returns (string memory) {
        return _name;
    }

    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    function decimals() public view virtual returns (uint) {
        return _decimals;
    }

    function totalSupply() public view override returns (uint) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint) {
        return _balanceOf[account];
    }

    function allowance(address owner, address spender) public view override returns (uint) {
        return _allowance[owner][spender];
    }

    function setBaseURI(string memory newBaseURI) public onlyDev {
        baseTokenURI = newBaseURI;
    }

    function changeDev(address newDev) public onlyDev {
        dev = newDev;
    } //simple function to change developer address, or revoke ownership (with address(0))

    // @DEV toggleNFTinterface is for the small possibility of frontend system changes leading the contract to favor enabling the disabled supportsNFTinterface flag
    // don't waste it, as frontends don't typically change classification of contracts
    // probably never to be used.
    function toggelNFTinterface() public onlyDev {
        supportsNFTinterface = !supportsNFTinterface;
    }

    function approve(address spender, uint amount) public override returns (bool) {
        // if the amount is greater than one token, and within range of IDs for NFTs
        // then set NFT approval for the given ID
        if (amount > ONE && amount <= MAXID) {
            address owner = ownerOf[amount]; // getting the owner of token ID via the `amount` input
            if (msg.sender != owner && !isApprovedForAll(owner, msg.sender)) revert("SJ741: You are not approved");
            _nftApprovals[amount] = spender; // calling nft approval for the token and spender
            libSJ721.emitApproval(owner, spender, amount);
            return true;
        }

        // else set the ERC20 allowance
        // the NFT ID range being set within a limited subset of ONE token(s)
        // allows for non-clashing interactions
        _allowance[msg.sender][spender] = amount;
        libSJ20.emitApproval(msg.sender, spender, amount);
        return true;
    }

    function _transfer741(address from, address to, uint amount) internal virtual {
        require(_balanceOf[from] >= amount, "SJ741: transfer amount exceeds balance");

        // checking the decimal amount of tokens owned before transaction for both participants
        uint256 fromDecimalsPre = _balanceOf[from] % ONE;
        uint256 toDecimalsPre = _balanceOf[to] % ONE;

        // simple erc20 balance operations
        _transfer20(from, to, amount);

        // checking the decimal amount of tokens after transaction for both partcipants
        uint256 fromDecimalsPost = _balanceOf[from] % ONE;
        uint256 toDecimalsPost = _balanceOf[to] % ONE;

        // stores the NFT IDs owned by `from`, enabling NFT management for that address.
        uint32[] storage ownedNFTsArray = ownedNFTs[from];

        // references NFTs marked as "broken", tracking these special state NFTs.
        uint32[] storage brokenIDsArray = broken;

        // if sender has higher decimal count after transaction, then they "roll under" and break an NFT
        if (fromDecimalsPre < fromDecimalsPost) {
            if (ownedNFTsArray.length > 0) {
                // if the sender has an nft to send

                uint32 tokenId = ownedNFTsArray[0]; //selects the user's first NFT from the list

                brokenIDsArray.push(tokenId); //pushes the nft into the "broken list" for limbo NFTs
                _transfer721(from, address(0), tokenId); //transfers the NFT ID ownership to (0) address for stewardship
            }
        }

        // if receiver has lower decimal count after transaction then they "roll over" and will "remake" an nft
        if (toDecimalsPre > toDecimalsPost) {
            if (brokenIDsArray.length > 0) {
                // recover an id from broken list

                _transfer721(address(0), to, brokenIDsArray[brokenIDsArray.length - 1]);
                brokenIDsArray.pop();
            } else {
                // mint new id
                _mint(to);
            }
        }

        // amount of tokens - amount of whole tokens being processed in int
        uint amountInTokens = amount / ONE;

        // ignore minting nfts from dev when they call -- this allows for gas-efficient team operations
        // @DEV if dev gathers NFTs, use the ERC721 transferFrom method to extract
        // @DEV be careful, don't let the wallet fall to some convoluted transferFrom scam to do something unexpected
        if (from == dev) return;

        if (amountInTokens > 0) {
            uint len = ownedNFTsArray.length; //len is the length, or number of NFTs in the addresses's owned array
            len = amountInTokens < len ? amountInTokens : len;
            // transfers owned NFTs from `from` to `to` until either all are transferred or the desired amount is reached
            // Subtracts transferred NFT count from `amountInTokens` to update remaining transfers
            for (uint i = 0; i < len; i++) {
                _transfer721(from, to, ownedNFTsArray[0]);
            }
            amountInTokens -= len;
            len = brokenIDsArray.length;
            len = amountInTokens < len ? amountInTokens : len;

            // recovers NFTs from the broken state to `to`, or mints new ones if not enough broken NFTs are available
            // if any tokens remain to be allocated, it mints new NFTs to `to` for the remaining balance
            for (uint i = 0; i < len; i++) {
                _transfer721(address(0), to, brokenIDsArray[brokenIDsArray.length - 1]);
                brokenIDsArray.pop();
            }

            _mintBatch(to, amountInTokens - len);
        }
    }

    function _mintBatch(address to, uint256 amount) internal {
        if (amount == 0) return; // Exit if no NFTs to mint

        if (amount == 1) {
            // Optimize single mint process
            _mint(to);
            return;
        }
        uint32 id = minted; // Start ID from last minted value
        uint256 ownedLen = ownedNFTs[to].length; // Current number of NFTs owned by 'to'
        for (uint i = 0; i < amount; ) {
            unchecked {
                id++; // Increment ID for each new NFT
            }
            ownerOf[id] = to; // Assign new NFT to owner.
            idToIndex[id] = ownedLen; // Map NFT ID to its index in owner's array
            ownedNFTs[to].push(id); // Add new NFT ID to owner's list

            libSJ721.emitTransfer(address(0), to, id); // Emit NFT transfer event

            unchecked {
                ownedLen++; // Increment count of owned NFTs
                i++; // Move to next NFT
            }
        }
        unchecked {
            minted += uint32(amount); // Update total minted count
        }
    }

    function _mint(address to) internal virtual returns (uint32 tokenId) {
        unchecked {
            minted++; // Increment the total number of minted tokens
        }
        tokenId = minted; // Assign the newly minted token ID

        ownerOf[tokenId] = to; // Set ownership of the new token to 'to'
        idToIndex[tokenId] = ownedNFTs[to].length; // Map the new token ID to its index in the owner's list
        ownedNFTs[to].push(tokenId); // Add the new token ID to the owner's list of owned tokens

        libSJ721.emitTransfer(address(0), to, tokenId); // Emit an event for the token transfer
    }

    function _mintGnomes(address to, bool burnGnomes) internal virtual returns (uint32 tokenId) {
        unchecked {
            minted++; // Increment the total number of minted tokens
        }
        tokenId = minted; // Assign the newly minted token ID

        ownerOf[tokenId] = to; // Set ownership of the new token to 'to'
        idToIndex[tokenId] = ownedNFTs[to].length; // Map the new token ID to its index in the owner's list
        ownedNFTs[to].push(tokenId); // Add the new token ID to the owner's list of owned tokens

        libSJ721.emitTransfer(address(0), to, tokenId); // Emit an event for the token transfer

        libSJ20.emitTransfer(address(0), to, ONE);
        _totalSupply += ONE;
        _balanceOf[to] += ONE;
    }

    function _burn(address from, uint32 tokenId) internal {
        require(from == ownerOf[tokenId], "SJ741: Incorrect owner"); // Ensure 'from' is the current owner

        delete _nftApprovals[tokenId]; // Clear any approvals for this token
        delete ownerOf[tokenId];
        uint256 index = idToIndex[tokenId]; // Get current index of the token in the owner's list
        uint32[] storage nftArray = ownedNFTs[from]; // Reference to the list of NFTs owned by 'from'
        uint256 len = nftArray.length; // Current number of NFTs owned by 'from'
        uint32 lastTokenId = nftArray[len - 1]; // Last token in the 'from' array to swap with transferred token

        nftArray[index] = lastTokenId; // Replace the transferred token with the last token in the array
        nftArray.pop(); // Remove the last element, effectively deleting the transferred token from 'from'

        if (len - 1 != 0) {
            idToIndex[lastTokenId] = index; // Update the index of the swapped token
        }
        libSJ721.emitTransfer(from, address(0), tokenId); // Emit an ERC721 transfer event

        _balanceOf[from] -= ONE; // Deduct the amount from the sender's balance

        libSJ20.emitTransfer(from, address(0), ONE); // Emit an ERC20 transfer event
        _totalSupply -= ONE;
    }

    // Updates the mappings and arrays managing ownership and index of NFTs after a transfer
    function _updateOwnedNFTs(address from, address to, uint32 tokenId) internal {
        uint256 index = idToIndex[tokenId]; // Get current index of the token in the owner's list
        uint32[] storage nftArray = ownedNFTs[from]; // Reference to the list of NFTs owned by 'from'
        uint256 len = nftArray.length; // Current number of NFTs owned by 'from'
        uint32 lastTokenId = nftArray[len - 1]; // Last token in the 'from' array to swap with transferred token

        nftArray[index] = lastTokenId; // Replace the transferred token with the last token in the array
        nftArray.pop(); // Remove the last element, effectively deleting the transferred token from 'from'

        if (len - 1 != 0) {
            idToIndex[lastTokenId] = index; // Update the index of the swapped token
        }

        ownedNFTs[to].push(tokenId); // Add the transferred token to the 'to' array
        idToIndex[tokenId] = ownedNFTs[to].length - 1; // Update the index mapping for the transferred token
    }

    // Executes a simple ERC20 token transfer.
    function _transfer20(address from, address to, uint256 amount) internal {
        _balanceOf[from] -= amount; // Deduct the amount from the sender's balance
        unchecked {
            _balanceOf[to] += amount; // Add the amount to the recipient's balance
        }
        libSJ20.emitTransfer(from, to, amount); // Emit an ERC20 transfer event
    }

    // Handles the transfer of an ERC721 token, ensuring proper ownership and event emission
    function _transfer721(address from, address to, uint32 tokenId) internal virtual {
        require(from == ownerOf[tokenId], "SJ741: Incorrect owner"); // Ensure 'from' is the current owner

        delete _nftApprovals[tokenId]; // Clear any approvals for this token
        ownerOf[tokenId] = to; // Transfer ownership of the token to 'to'
        _updateOwnedNFTs(from, to, tokenId); // Update ownership tracking structures
        libSJ721.emitTransfer(from, to, tokenId); // Emit an ERC721 transfer event
    }

    // only erc20 calls this
    // if amount is a token id owned my the caller send as an NFT
    // else transfer741
    function transfer(address to, uint amount) public override returns (bool) {
        if (ownerOf[amount] == msg.sender) {
            _transfer721(msg.sender, to, uint32(amount));
            _transfer20(msg.sender, to, ONE);
            return true;
        }
        _transfer741(msg.sender, to, amount);
        return true;
    }

    // erc20 and erc721 call this
    function transferFrom(address from, address to, uint amount) public virtual returns (bool) {
        //if amount is within the NFT id range, then a simple NFT transfer + token amount (ONE)
        if (treasuryMintTimeStamp[from] > block.timestamp) {
            uint finalBalance = _balanceOf[from] - amount;
            require(finalBalance >= ONE, "Can't transfer all your Gnome yet");
        }

        if (amount > ONE && amount <= MAXID) {
            require(
                //require from is the msg caller, or that caller is approved for that specific NFT, or all NFTs
                msg.sender == from || msg.sender == getApproved(amount) || isApprovedForAll(from, msg.sender),
                "SJ741: You don't have the right"
            );

            _transfer721(from, to, uint32(amount));
            _transfer20(from, to, ONE);
            return true;
        }

        _spendAllowance(from, msg.sender, amount);
        _transfer741(from, to, amount);
        return true;
    }

    // erc721
    function safeTransferFrom(address from, address to, uint256 tokenId) public payable override {
        require(
            msg.sender == from || msg.sender == getApproved(tokenId) || isApprovedForAll(from, msg.sender),
            "SJ741: You don't have the right"
        );
        if (treasuryMintTimeStamp[from] > block.timestamp) {
            uint finalBalance = _balanceOf[from] - ONE;
            require(finalBalance >= ONE, "Can't transfer all your Gnome yet");
        }
        _transfer721(from, to, uint32(tokenId));
        _transfer20(from, to, ONE);

        if (
            to.code.length != 0 &&
            IERC721TokenReceiver(to).onERC721Received(msg.sender, from, tokenId, "") !=
            IERC721TokenReceiver.onERC721Received.selector
        ) {
            revert UnsupportedReceiver();
        }
    }

    // erc721
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public payable override {
        require(
            msg.sender == from || msg.sender == getApproved(tokenId) || isApprovedForAll(from, msg.sender),
            "SJ741: You don't have the right"
        );
        if (treasuryMintTimeStamp[from] > block.timestamp) {
            uint finalBalance = _balanceOf[from] - ONE;
            require(finalBalance >= ONE, "Can't transfer all your Gnome yet");
        }
        _transfer721(from, to, uint32(tokenId));
        _transfer20(from, to, ONE);

        if (
            to.code.length != 0 &&
            IERC721TokenReceiver(to).onERC721Received(msg.sender, from, tokenId, data) !=
            IERC721TokenReceiver.onERC721Received.selector
        ) {
            revert UnsupportedReceiver();
        }
    }

    function _spendAllowance(address owner, address spender, uint amount) internal virtual {
        require(_allowance[owner][spender] >= amount, "SJ741: insufficient allowance");
        _allowance[owner][spender] -= amount;
    }

    function getApproved(uint256 tokenId) public view override returns (address) {
        if (ownerOf[tokenId] == address(0)) revert();
        return _nftApprovals[tokenId];
    }

    function setApprovalForAll(address operator, bool approved) public override {
        _operatorApprovals[msg.sender][operator] = approved;
        libSJ721.emitApprovalForAll(msg.sender, operator, approved);
    }

    function isApprovedForAll(address owner, address operator) public view override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    function toString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(value % 10) + 48);
            value /= 10;
        }
        return string(buffer);
    }

    function withdraw() external onlyDev {
        payable(dev).transfer(address(this).balance);
    }

    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        return
            // Even though we support ERC721 and should return true, etherscan wants to treat us as ERC721 instead of ERC20
            // @DEV ERC165 for ERC721 can be toggled on for reasons of frontend/dapp/script implementations, but is very specific
            (supportsNFTinterface && interfaceId == 0x80ac58cd) || // ERC165 interface ID for ERC721
            interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165
            interfaceId == 0x36372b07; // ERC165 interface ID for ERC20
    }

    // Modifier to restrict access to owner only
    function getGnomeIds(address _gnome) public view returns (uint32[] memory) {
        return ownedNFTs[_gnome];
    }

    function getIdGnome(uint256 _id) public view returns (address) {
        return ownerOf[_id];
    }

    function factoryMint(address to) external onlyAuth returns (uint32) {
        require(factoryMints < maxfactoryMints, "No more Gnomies to Mint!");
        factoryMints++;

        return _mintGnomes(to, false);
    }

    function authMint(address to) external onlyAuth returns (uint32) {
        return _mintGnomes(to, false);
    }

    function fatalizeGnomeAuth(uint32 tokenId) public onlyAuth {
        _burn(ownerOf[tokenId], tokenId);
    }

    modifier onlyAuth() {
        require(msg.sender == owner() || isAuth[msg.sender], "Caller is not the authorized");
        _;
    }

    function setChainId(string memory _chain, uint16 _ID) external onlyAuth {
        destChainId[_chain] = _ID;
    }

    function setTokenURI(string memory _tokenURI) public onlyAuth {
        baseTokenURI = _tokenURI;
    }

    function tokenURI(uint256 id) public view returns (string memory) {
        if (!gameActive) {
            return baseTokenURI;
        }

        // Check if gnomeGamePlay is set to a valid address
        require(address(gnomeGamePlay) != address(0), "gnomeGamePlay address is not set");

        if (gnomeGamePlay.isGnomeSignedUp(id)) {
            return gnomeURI._tokenURI(id);
        }

        return baseTokenURI;
    }

    function setGnomeUri(IGnomeURI _renderer) external onlyAuth {
        gnomeURI = _renderer;
    }

    function setGnomeGamePlay(IGnomeGamePlay _gnomeGamePlay, bool _gameActive) external onlyAuth {
        gnomeGamePlay = _gnomeGamePlay;
        gameActive = _gameActive;
    }

    function setIsAuth(address fren, bool isAuthorized) external onlyAuth {
        isAuth[fren] = isAuthorized;
    }

    function setTreasuryMintTimeStamp(address gnome, uint256 timeStamp) external onlyAuth {
        treasuryMintTimeStamp[gnome] = timeStamp;
    }

    function getTreasuryMintTimeStamp(address gnome) external view returns (uint256) {
        return treasuryMintTimeStamp[gnome];
    }
}

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

Context size (optional):