Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/Leaderboard.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ZkArcadeNft} from "./ZkArcadeNft.sol";
import {ZkArcadePublicNft} from "./ZkArcadePublicNft.sol";
contract Leaderboard is UUPSUpgradeable, OwnableUpgradeable {
// ======== Constants ========
uint256 constant BEAST_SCORE_MULTIPLIER = 60000;
uint256 constant PARITY_SCORE_MULTIPLIER = 28000;
// ======== Storage ========
address public alignedServiceManager;
address public alignedBatcherPaymentService;
address[10] public top10Score;
mapping(address => uint256) public usersScore;
struct BeastGame {
uint256 endsAtTime;
// Note: each level takes 4 bytes (i.e 32 bits) in total we can have as much as 8 levels per config
// The first byte represent the number of blocks in the map
// The second byte represent the number of static blocks in the map
// The third byte represent the number of common beasts in the map
// The fourth byte represent the number of super beasts in the map
uint256 gameConfig;
uint256 startsAtTime;
}
struct ParityGame {
uint256 endsAtTime;
// Note: each level takes 10 bytes (i.e 80 bits) in total we can have as much as 3 levels per config
// The first byte is for the position (first 4 bits for x, last 4 bits for y)
// And the rest 9 bytes represent the number in the board
uint256 gameConfig;
uint256 startsAtTime;
}
BeastGame[] public beastGames;
ParityGame[] public parityGames;
mapping(bytes32 => uint256) public usersBeastLevelCompleted;
mapping(bytes32 => uint256) public usersParityLevelCompleted;
bytes32 internal beastVkCommitment;
bytes32 internal parityVkCommitment;
address public zkArcadeNft;
address public zkArcadePublicNft;
bool public useWhitelist;
uint256 constant MAX_PARITY_LEVELS = 3; // Must match circom circuit
uint256 constant BITS_PER_PARITY_LEVEL = 80; // 10 bytes per level
event BeastPointsClaimed(address user, uint256 level, uint256 score, uint256 gameConfig);
event ParityPointsClaimed(address user, uint256 level, uint256 score, uint256 gameConfig);
event BeastGamesUpdated(BeastGame[] beastGames);
event ParityGamesUpdated(ParityGame[] parityGames);
event WhitelistEnabled();
event WhitelistDisabled();
event ZkArcadeNftAddressUpdated(address nftContractAddress);
event ZkArcadePublicNftAddressUpdated(address nftContractAddress);
event BeastProgramIdUpdated(bytes32 newProgramId);
event ParityProgramIdUpdated(bytes32 newProgramId);
error CallToAlignedContractFailed();
error ProofNotVerifiedOnAligned();
error UserHasAlreadyCompletedThisLevel(uint256 level);
error UserAddressMismatch(address expected, address actual);
error UserIsNotWhitelisted(address);
error InvalidGame(uint256 expected, uint256 provided);
error NoActiveBeastGame();
error NoActiveParityGame();
error GameEnded();
error GameNotStarted();
error ParityLevelTooLarge();
// ======== Initialization & Upgrades ========
constructor() {
_disableInitializers();
}
function initialize(
address owner,
address _alignedServiceManager,
address _alignedBatcherPaymentService,
address _zkArcadeNft,
BeastGame[] calldata _beastGames,
ParityGame[] calldata _parityGames,
bool _useWhitelist,
bytes32 _beastVkCommitment,
bytes32 _parityVkCommitment
) public initializer {
require(_alignedServiceManager != address(0) &&
_alignedServiceManager.code.length > 0, "invalid alignedServiceManager");
require(_alignedBatcherPaymentService != address(0) &&
_alignedBatcherPaymentService.code.length > 0, "invalid alignedBatcherPaymentService");
alignedServiceManager = _alignedServiceManager;
alignedBatcherPaymentService = _alignedBatcherPaymentService;
beastGames = _beastGames;
zkArcadeNft = _zkArcadeNft;
zkArcadePublicNft = address(0);
useWhitelist = _useWhitelist;
parityGames = _parityGames;
beastVkCommitment = _beastVkCommitment;
parityVkCommitment = _parityVkCommitment;
__Ownable_init(owner);
__UUPSUpgradeable_init();
emit BeastGamesUpdated(_beastGames);
emit ParityGamesUpdated(_parityGames);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// ======== Core Game Functions ========
function claimBeastPoints(
uint256 gameIndex,
bytes32 proofCommitment,
bytes calldata publicInputs,
bytes20 proofGeneratorAddr,
bytes32 batchMerkleRoot,
bytes memory merkleProof,
uint256 verificationDataBatchIndex
) public {
(uint256 levelCompleted, uint256 gameConfig, address userAddress) =
abi.decode(publicInputs, (uint256, uint256, address));
if (userAddress != msg.sender) {
revert UserAddressMismatch({expected: userAddress, actual: msg.sender});
}
if (useWhitelist && !isUserWhitelisted(userAddress)) {
revert UserIsNotWhitelisted(userAddress);
}
bytes32 pubInputCommitment = keccak256(abi.encodePacked(publicInputs));
(bool callWasSuccessful, bytes memory proofIsIncluded) = alignedServiceManager.staticcall(
abi.encodeWithSignature(
"verifyBatchInclusion(bytes32,bytes32,bytes32,bytes20,bytes32,bytes,uint256,address)",
proofCommitment,
pubInputCommitment,
beastVkCommitment,
proofGeneratorAddr,
batchMerkleRoot,
merkleProof,
verificationDataBatchIndex,
alignedBatcherPaymentService
)
);
if (!callWasSuccessful) {
revert CallToAlignedContractFailed();
}
bool proofIncluded = abi.decode(proofIsIncluded, (bool));
if (!proofIncluded) {
revert ProofNotVerifiedOnAligned();
}
// Validate the game is available and the config is correct
BeastGame memory game = beastGames[gameIndex];
if (block.timestamp >= game.endsAtTime) {
revert GameEnded();
}
if (block.timestamp < game.startsAtTime) {
revert GameNotStarted();
}
if (game.gameConfig != gameConfig) {
revert InvalidGame(game.gameConfig, gameConfig);
}
bytes32 key = getBeastKey(msg.sender, gameConfig);
uint256 currentLevelCompleted = usersBeastLevelCompleted[key];
if (levelCompleted <= currentLevelCompleted) {
revert UserHasAlreadyCompletedThisLevel(currentLevelCompleted);
}
usersBeastLevelCompleted[key] = levelCompleted;
usersScore[msg.sender] += (levelCompleted - currentLevelCompleted) * BEAST_SCORE_MULTIPLIER;
verifyAndReplaceInTop10(msg.sender);
emit BeastPointsClaimed(msg.sender, levelCompleted, usersScore[msg.sender], gameConfig);
}
function claimParityPoints(
uint256 gameIndex,
bytes32 proofCommitment,
bytes calldata publicInputs,
bytes20 proofGeneratorAddr,
bytes32 batchMerkleRoot,
bytes memory merkleProof,
uint256 verificationDataBatchIndex
) public {
(uint256 levelCompleted, uint256 gameConfig, uint256 userAddressNum) =
abi.decode(publicInputs, (uint256, uint256, uint256));
address userAddress = address(uint160(userAddressNum));
if (userAddress != msg.sender) {
revert UserAddressMismatch({expected: userAddress, actual: msg.sender});
}
if (useWhitelist && !isUserWhitelisted(userAddress)) {
revert UserIsNotWhitelisted(userAddress);
}
if (levelCompleted > MAX_PARITY_LEVELS) revert ParityLevelTooLarge();
bytes32 pubInputCommitment = keccak256(publicInputs);
(bool callWasSuccessful, bytes memory proofIsIncluded) = alignedServiceManager.staticcall(
abi.encodeWithSignature(
"verifyBatchInclusion(bytes32,bytes32,bytes32,bytes20,bytes32,bytes,uint256,address)",
proofCommitment,
pubInputCommitment,
parityVkCommitment,
proofGeneratorAddr,
batchMerkleRoot,
merkleProof,
verificationDataBatchIndex,
alignedBatcherPaymentService
)
);
if (!callWasSuccessful) {
revert CallToAlignedContractFailed();
}
bool proofIncluded = abi.decode(proofIsIncluded, (bool));
if (!proofIncluded) {
revert ProofNotVerifiedOnAligned();
}
ParityGame memory currentGame = parityGames[gameIndex];
if (block.timestamp >= currentGame.endsAtTime) {
revert GameEnded();
}
if (block.timestamp < currentGame.startsAtTime) {
revert GameNotStarted();
}
// The circom program proves the user knows solutions to (3) parity games.
// When fewer games are played, all public inputs for unplayed levels are set to 0.
// This means only the first `levelCompleted` levels contain meaningful gameConfig data.
// To compare configurations, we right-shift the data to discard the zero-filled remainder.
uint256 bits = BITS_PER_PARITY_LEVEL * levelCompleted;
uint256 shiftAmount = 256 - bits;
uint256 currentTruncatedConfig = currentGame.gameConfig >> shiftAmount;
uint256 newTruncatedConfig = gameConfig >> shiftAmount;
if (currentTruncatedConfig != newTruncatedConfig) {
revert InvalidGame(currentGame.gameConfig, gameConfig);
}
bytes32 key = getParityKey(msg.sender, currentGame.gameConfig);
uint256 currentLevelCompleted = usersParityLevelCompleted[key];
if (levelCompleted <= currentLevelCompleted) {
revert UserHasAlreadyCompletedThisLevel(currentLevelCompleted);
}
usersParityLevelCompleted[key] = levelCompleted;
usersScore[msg.sender] += (levelCompleted - currentLevelCompleted) * PARITY_SCORE_MULTIPLIER;
verifyAndReplaceInTop10(msg.sender);
emit ParityPointsClaimed(msg.sender, levelCompleted, usersScore[msg.sender], gameConfig);
}
// ======== View Functions ========
function getUserScore(address user) public view returns (uint256) {
return usersScore[user];
}
function getUserBeastLevelCompleted(bytes32 key) public view returns (uint256) {
return usersBeastLevelCompleted[key];
}
function getCurrentBeastGame() public view returns (BeastGame memory, uint256 idx) {
for (uint256 i = beastGames.length; i > 0; i--) {
uint256 j = i - 1;
BeastGame memory game = beastGames[j];
if (block.timestamp >= game.startsAtTime && block.timestamp < game.endsAtTime) {
return (game, j);
}
}
revert NoActiveBeastGame();
}
function getCurrentParityGame() public view returns (ParityGame memory, uint256 idx) {
for (uint256 i = parityGames.length; i > 0; i--) {
uint256 j = i - 1;
ParityGame memory game = parityGames[j];
if (block.timestamp >= game.startsAtTime && block.timestamp < game.endsAtTime) {
return (game, j);
}
}
revert NoActiveParityGame();
}
function getTop10Score() external view returns (address[10] memory) {
return top10Score;
}
// ======== Admin Functions ========
/// @notice Sets the beast games configuration
/// @param _beastGames The new beast games configuration
function setBeastGames(BeastGame[] calldata _beastGames) public onlyOwner {
beastGames = _beastGames;
emit BeastGamesUpdated(_beastGames);
}
/// @notice Adds new beast games configuration
/// @param _newBeastGames The new beast games configuration to add
function addBeastGames(BeastGame[] calldata _newBeastGames) public onlyOwner {
for (uint256 i = 0; i < _newBeastGames.length; i++) {
beastGames.push(_newBeastGames[i]);
}
emit BeastGamesUpdated(_newBeastGames);
}
/// @notice Sets the parity games configuration
/// @param _parityGames The new parity games configuration
function setParityGames(ParityGame[] calldata _parityGames) public onlyOwner {
parityGames = _parityGames;
emit ParityGamesUpdated(parityGames);
}
/// @notice Adds new parity games configuration
/// @param _newParityGames The new parity games configuration to add
function addParityGames(ParityGame[] calldata _newParityGames) public onlyOwner {
for (uint256 i = 0; i < _newParityGames.length; i++) {
parityGames.push(_newParityGames[i]);
}
emit ParityGamesUpdated(_newParityGames);
}
function enableWhitelist() public onlyOwner {
useWhitelist = true;
emit WhitelistEnabled();
}
function disableWhitelist() public onlyOwner {
useWhitelist = false;
emit WhitelistDisabled();
}
function setZkArcadeNftAddress(address nftContractAddress) public onlyOwner {
zkArcadeNft = nftContractAddress;
emit ZkArcadeNftAddressUpdated(nftContractAddress);
}
function setZkArcadePublicNftAddress(address nftContractAddress) public onlyOwner {
zkArcadePublicNft = nftContractAddress;
emit ZkArcadePublicNftAddressUpdated(nftContractAddress);
}
function setBeastVkCommitment(bytes32 vkCommitment) public onlyOwner {
beastVkCommitment = vkCommitment;
emit BeastProgramIdUpdated(beastVkCommitment);
}
function setParityVkCommitment(bytes32 vkCommitment) public onlyOwner {
parityVkCommitment = vkCommitment;
emit ParityProgramIdUpdated(parityVkCommitment);
}
// ======== Internal Helper Functions ========
function getBeastKey(address user, uint256 game) internal pure returns (bytes32) {
return keccak256(abi.encode(user, game));
}
function getParityKey(address user, uint256 gameConfig) internal pure returns (bytes32) {
return keccak256(abi.encode(user, gameConfig));
}
function verifyAndReplaceInTop10(address user) internal {
uint256 userScore = usersScore[user];
uint256 lastScore = top10Score[9] == address(0) ? 0 : usersScore[top10Score[9]];
// early return to not run the whole alg if the user does not have enough points to be in the top 10
if (top10Score[9] != user && userScore <= lastScore) {
return;
}
int256 existingIndex = -1;
int256 insertIndex = -1;
for (uint256 i = 0; i < 10; i++) {
address addr = top10Score[i];
if (addr == user) {
existingIndex = int256(i);
}
if (insertIndex == -1 && userScore > usersScore[addr]) {
insertIndex = int256(i);
}
}
if (insertIndex == -1 || (existingIndex != -1 && existingIndex <= insertIndex)) {
return;
}
// If the user is already in the leaderboard
// shift all the elements from the insert place to existing
if (existingIndex != -1) {
for (uint256 i = uint256(existingIndex); i > uint256(insertIndex); i--) {
top10Score[i] = top10Score[i - 1];
}
} else {
// else (if not present already), simply shift down all the elements from the insert index
for (uint256 j = 9; j > uint256(insertIndex); j--) {
top10Score[j] = top10Score[j - 1];
}
}
top10Score[uint256(insertIndex)] = user;
}
function isUserWhitelisted(address user) public view returns (bool) {
if (zkArcadeNft != address(0)) {
ZkArcadeNft nftContract = ZkArcadeNft(zkArcadeNft);
if (nftContract.balanceOf(user) > 0) {
return true;
}
}
if (zkArcadePublicNft != address(0)) {
ZkArcadePublicNft publicNftContract = ZkArcadePublicNft(zkArcadePublicNft);
if (publicNftContract.balanceOf(user) > 0) {
return true;
}
}
return false;
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @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.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
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) {
OwnableStorage storage $ = _getOwnableStorage();
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 {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
"
},
"src/ZkArcadeNft.sol": {
"content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract ZkArcadeNft is ERC721Upgradeable, UUPSUpgradeable, OwnableUpgradeable {
uint256 private _nextTokenId;
bytes32[] public merkleRoots;
mapping(address => bool) public hasClaimed;
bool internal transfersEnabled;
bool internal claimsEnabled;
string private _baseTokenURI;
/**
* Events
*/
event MerkleRootUpdated(bytes32 indexed newRoot, uint256 indexed rootIndex);
event NFTClaimed(address indexed account);
event TransfersEnabled();
event TransfersDisabled();
event ClaimsEnabled();
event ClaimsDisabled();
/**
* Errors
*/
error TransfersPaused();
error ClaimsPaused();
// ======== Initialization & Upgrades ========
constructor() {
_disableInitializers();
}
function initialize(address owner, string memory name, string memory symbol, string memory baseURI)
public
initializer
{
__ERC721_init(name, symbol);
__Ownable_init(owner);
_baseTokenURI = baseURI;
transfersEnabled = false;
claimsEnabled = true;
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// ======== Core NFT Functions ========
function claimNFT(bytes32[] calldata merkleProof, uint256 rootIndex) public returns (uint256) {
if (!claimsEnabled) {
revert ClaimsPaused();
}
require(!hasClaimed[msg.sender], "NFT already claimed for this address");
require(rootIndex < merkleRoots.length, "Invalid root index");
// Verify that the address is whitelisted using Merkle Proof
bytes32 inner = keccak256(abi.encode(msg.sender));
bytes32 leaf = keccak256(abi.encode(inner));
require(MerkleProof.verify(merkleProof, merkleRoots[rootIndex], leaf), "Invalid merkle proof");
// Mark as claimed
hasClaimed[msg.sender] = true;
// Mint the NFT
uint256 tokenId = _nextTokenId++;
_mint(msg.sender, tokenId);
emit NFTClaimed(msg.sender);
return tokenId;
}
function _update(address to, uint256 tokenId, address auth) internal override returns (address from) {
from = _ownerOf(tokenId);
// only block actual transfers (not mint or burn)
if (!transfersEnabled && from != address(0) && to != address(0)) {
revert TransfersPaused();
}
return super._update(to, tokenId, auth);
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
// ======== View Functions ========
function totalSupply() external view returns (uint256) {
return _nextTokenId;
}
// ======== Whitelist & Merkle Management ========
function isWhitelisted(address user) public view returns (bool) {
return balanceOf(user) >= 1;
}
function addMerkleRoot(bytes32 _merkleRoot) external onlyOwner returns (uint256 index) {
merkleRoots.push(_merkleRoot);
index = merkleRoots.length - 1;
emit MerkleRootUpdated(_merkleRoot, index);
}
function setMerkleRoot(bytes32 _merkleRoot, uint256 rootIndex) public onlyOwner {
require(rootIndex < merkleRoots.length, "Invalid root index");
merkleRoots[rootIndex] = _merkleRoot;
emit MerkleRootUpdated(_merkleRoot, rootIndex);
}
// ======== Admin Controls ========
function enableTransfers() public onlyOwner {
transfersEnabled = true;
emit TransfersEnabled();
}
function disableTransfers() public onlyOwner {
transfersEnabled = false;
emit TransfersDisabled();
}
function enableClaims() public onlyOwner {
claimsEnabled = true;
emit ClaimsEnabled();
}
function disableClaims() public onlyOwner {
claimsEnabled = false;
emit ClaimsDisabled();
}
function endSeason() public onlyOwner {
claimsEnabled = false;
transfersEnabled = true;
emit ClaimsDisabled();
emit TransfersEnabled();
}
function setBaseURI(string memory newBaseURI) public onlyOwner {
_baseTokenURI = newBaseURI;
}
}
"
},
"src/ZkArcadePublicNft.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
contract ZkArcadePublicNft is ERC721Upgradeable, UUPSUpgradeable, OwnableUpgradeable {
uint256 private _nextTokenId;
uint256 public maxSupply;
bool public mintingEnabled;
bool public transfersEnabled;
string private _baseTokenURI;
/**
* Events
*/
event MintingEnabled();
event MintingDisabled();
event TransfersEnabled();
event TransfersDisabled();
event NFTMinted(address indexed account, uint256 tokenId);
/**
* Errors
*/
error MintingPaused();
error MaxSupplyExceeded();
error AlreadyOwnsNFT();
error TransfersPaused();
// ======== Initialization & Upgrades ========
constructor() {
_disableInitializers();
}
function initialize(
address owner,
string memory name,
string memory symbol,
string memory baseURI,
uint256 _maxSupply
) public initializer {
__ERC721_init(name, symbol);
__Ownable_init(owner);
_baseTokenURI = baseURI;
maxSupply = _maxSupply;
mintingEnabled = false;
transfersEnabled = false;
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
// ======== Core NFT Functions ========
function mint() public returns (uint256) {
if (!mintingEnabled) {
revert MintingPaused();
}
if (balanceOf(msg.sender) > 0) {
revert AlreadyOwnsNFT();
}
if (_nextTokenId >= maxSupply) {
revert MaxSupplyExceeded();
}
uint256 tokenId = _nextTokenId++;
_mint(msg.sender, tokenId);
emit NFTMinted(msg.sender, tokenId);
return tokenId;
}
function _update(address to, uint256 tokenId, address auth) internal override returns (address from) {
from = _ownerOf(tokenId);
// only block actual transfers (not mint or burn)
if (!transfersEnabled && from != address(0) && to != address(0)) {
revert TransfersPaused();
}
return super._update(to, tokenId, auth);
}
// ======== View Functions ========
function totalSupply() external view returns (uint256) {
return _nextTokenId;
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
// ======== Admin Functions ========
function enableMinting() external onlyOwner {
mintingEnabled = true;
emit MintingEnabled();
}
function disableMinting() external onlyOwner {
mintingEnabled = false;
emit MintingDisabled();
}
function enableTransfers() external onlyOwner {
transfersEnabled = true;
emit TransfersEnabled();
}
function disableTransfers() external onlyOwner {
transfersEnabled = false;
emit TransfersDisabled();
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
_baseTokenURI = newBaseURI;
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
"
},
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.22;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
"
},
"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {ERC721Utils} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";
import {IERC721Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC721
struct ERC721Storage {
// Token name
string _name;
// Token symbol
string _symbol;
mapping(uint256 tokenId => address) _owners;
mapping(address owner => uint256) _balances;
mapping(uint256 tokenId => address) _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) _operatorApprovals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;
function _getERC721Storage() private pure returns (ERC721Storage storage $) {
assembly {
$.slot := ERC721StorageLocation
}
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC721Storage storage $ = _getERC721Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, 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) {
ERC721Storage storage $ = _getERC721Storage();
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) {
ERC721Storage storage $ = _getERC721Storage();
return $._name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual returns (string memory) {
ERC721Storage storage $ = _getERC721Storage();
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) {
ERC721Storage storage $ = _getERC721Storage();
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);
ERC721Utils.checkOnERC721Received(_msgSender(), 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 ERC-721 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) {
ERC721Storage storage $ = _getERC721Storage();
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) {
ERC721Storage storage $ = _getERC721Storage();
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 `owner` for `tokenId`.
* - `spender` does not have approval to manage all of `owner`'s assets.
*
* 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 _increas
Submitted on: 2025-10-27 20:42:03
Comments
Log in to comment.
No comments yet.