// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol)pragmasolidity ^0.8.0;import"./IAccessControl.sol";
import"../utils/Context.sol";
import"../utils/Strings.sol";
import"../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/abstractcontractAccessControlisContext, IAccessControl, ERC165{
structRoleData {
mapping(address=>bool) members;
bytes32 adminRole;
}
mapping(bytes32=> RoleData) private _roles;
bytes32publicconstant DEFAULT_ADMIN_ROLE =0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/modifieronlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IAccessControl).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) publicviewvirtualoverridereturns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/function_checkRole(bytes32 role) internalviewvirtual{
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/function_checkRole(bytes32 role, address account) internalviewvirtual{
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) publicviewvirtualoverridereturns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functiongrantRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functionrevokeRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/functionrenounceRole(bytes32 role, address account) publicvirtualoverride{
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/function_setupRole(bytes32 role, address account) internalvirtual{
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/function_setRoleAdmin(bytes32 role, bytes32 adminRole) internalvirtual{
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/function_grantRole(bytes32 role, address account) internalvirtual{
if (!hasRole(role, account)) {
_roles[role].members[account] =true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/function_revokeRole(bytes32 role, address account) internalvirtual{
if (hasRole(role, account)) {
_roles[role].members[account] =false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import"@openzeppelin/contracts/access/AccessControl.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import"@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {LockRegistry} from"./abstract/LockRegistry.sol";
import {IBrawlerBearz} from"./interfaces/IBrawlerBearz.sol";
import {IBrawlerBearzFaction} from"./interfaces/IBrawlerBearzFaction.sol";
import {IBrawlerBearzRenderer} from"./interfaces/IBrawlerBearzRenderer.sol";
import {IBrawlerBearzDynamicItems} from"./interfaces/IBrawlerBearzDynamicItems.sol";
import {ERC721Psi, ERC721PsiRandomSeedReveal, ERC721PsiRandomSeedRevealBurnable} from"./ERC721PsiRandomSeedRevealBurnable.sol";
/*******************************************************************************
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|(@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|,|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&@@@@@@@@@@@|,*|&@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%,**%@@@@@@@@%|******%&@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&##*****|||**,(%%%%%**|%@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@***,#%%%%**#&@@@@@#**,|@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@*,(@@@@@@@@@@**,(&@@@@#**%@@@@@@||(%@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@%|,****&@((@&***&@@@@@@%||||||||#%&@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@&%#*****||||||**#%&@%%||||||||#@&%#(@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@&**,(&@@@@@%|||||*##&&&&##|||||(%@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@**,%@@@@@@@(|*|#%@@@@@@@@#||#%%@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@#||||#@@@@||*|%@@@@@@@@&|||%%&@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@#,,,,,,*|**||%|||||||###&@@@@@@@#|||#%@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@&#||*|||||%%%@%%%#|||%@@@@@@@@&(|(%&@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@&&%%(||||@@@@@@&|||||(%&((||(#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@%%(||||||||||#%#(|||||%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@&%#######%%@@**||(#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%##%%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
********************************************************************************//**************************************************
* @title BrawlerBearz
* @author @ScottMitchell18
**************************************************/contractBrawlerBearzisIBrawlerBearz,
ERC721PsiRandomSeedRevealBurnable,
LockRegistry,
ReentrancyGuard,
AccessControl{
addresspublicconstant DEAD_ADDRESS =0x000000000000000000000000000000000000dEaD;
// Rolesbytes32constant XP_MUTATOR_ROLE =keccak256("XP_MUTATOR_ROLE");
bytes32constant OWNER_ROLE =keccak256("OWNER_ROLE");
// Equip typesbytes32constant HEAD_ITEM_TYPE =keccak256(abi.encodePacked("HEAD"));
bytes32constant WEAPON_ITEM_TYPE =keccak256(abi.encodePacked("WEAPON"));
bytes32constant BACKGROUND_ITEM_TYPE =keccak256(abi.encodePacked("BACKGROUND"));
bytes32constant ARMOR_ITEM_TYPE =keccak256(abi.encodePacked("ARMOR"));
bytes32constant FACE_ARMOR_ITEM_TYPE =keccak256(abi.encodePacked("FACE_ARMOR"));
bytes32constant EYEWEAR_ITEM_TYPE =keccak256(abi.encodePacked("EYEWEAR"));
bytes32constant MISC_ITEM_TYPE =keccak256(abi.encodePacked("MISC"));
/// @notice bytes32 of Chainlink keyhashbytes32publicimmutable keyHash;
/// @notice value of Chainlink subscription iduint64publicimmutable subscriptionId;
/// @notice 4% of total minteduint256public teamMintAmount =128;
/// @notice address of treasury (e.g, gnosis safe)addresspublic treasury =payable(0x39bfA2b4319581bc885A2d4b9F0C90C2e1c24B87);
/*
* @notice Whitelist Live ~ September 16th, 2022, 10AM EST
* @dev timestamp for whitelist
*/uint256public whitelistLiveAt =1663336800;
/*
* @notice Public / Free Claim Live ~ September 16th, 2022, 5PM EST
* @dev timestamp for public and free claim
*/uint256public liveAt =1663362000;
/// @notice amount of the total supply of the collection (n - 1)uint256public maxSupply =3335; // Excludes 2666 access passes/// @notice price in etheruint256public price =0.045ether;
/// @notice amount of transactions allowed per wallet (n - 1)uint256public maxPerWallet =3;
/// @notice boolean for if the shop drop is enabledboolprivate isShopDropEnabled =true;
/// @notice boolean for if its revealedboolpublic isRevealed =false;
/// @notice bytes32 hash of the merkle rootbytes32public merkleRoot;
/// @notice map from token id to custom metadatamapping(uint256=> CustomMetadata) internal metadata;
// @dev An address mapping for max mint per walletmapping(address=>uint256) public addressToMinted;
/// @notice Vendor contract
IBrawlerBearzDynamicItems public vendorContract;
/// @notice Access pass contract
IERC721 public accessPassContract;
/// @notice The rendering library contract
IBrawlerBearzRenderer public renderer;
/// @notice Faction contract
IBrawlerBearzFaction public factionContract;
// ========================================// Modifiers// ========================================modifierisTokenOwner(uint256 tokenId) {
if (ownerOf(tokenId) != _msgSender()) {
revert InvalidOwner();
}
_;
}
modifierisItemTokenOwner(uint256 itemTokenId) {
if (vendorContract.balanceOf(_msgSender(), itemTokenId) ==0) {
revert InvalidOwner();
}
_;
}
modifierisItemValidType(uint256 itemTokenId, stringmemory validTypeOf) {
if (
keccak256(abi.encodePacked(validTypeOf)) !=keccak256(abi.encodePacked(vendorContract.getItemType(itemTokenId)))
) {
revert InvalidItemType();
}
_;
}
modifierisItemXPMet(uint256 itemTokenId, uint256 tokenId) {
if (metadata[tokenId].xp < vendorContract.getItemXPReq(itemTokenId)) {
revert ItemRequiresMoreXP();
}
_;
}
// " and \ are not validmodifierisValidString(stringcalldata value) {
bytesmemory str =bytes(value);
for (uint256 i; i < str.length; i++) {
bytes1 char = str[i];
if ((char ==0x22) || (char ==0x5c)) revert InvalidString();
}
_;
}
constructor(address _vrfV2Coordinator,
bytes32 keyHash_,
uint64 subscriptionId_,
address _accessPassContract,
address _factionContract,
address _renderingContract,
address _vendorContract
)
ERC721Psi("Brawler Bearz", "BB")
ERC721PsiRandomSeedReveal(_vrfV2Coordinator, 400000, 3)
{
// Chainlink VRF initialization
keyHash = keyHash_;
subscriptionId = subscriptionId_;
// Setup access control
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(OWNER_ROLE, _msgSender());
// NFT integration contracts
accessPassContract = IERC721(_accessPassContract);
factionContract = IBrawlerBearzFaction(_factionContract);
// On-chain metadata rendering contract
renderer = IBrawlerBearzRenderer(_renderingContract);
// Shop integration contract
vendorContract = IBrawlerBearzDynamicItems(_vendorContract);
// Placeholder mint for collection protection
_safeMint(_msgSender(), 1, "");
}
// ========================================// Dynamic metadata// ========================================/**
* @notice Sets the name of a particular token id
* @dev only token owner call this function
* @param tokenId The token id
* @param name The name to set
*/functionsetName(uint256 tokenId, stringcalldata name)
publicoverrideisTokenOwner(tokenId)
isValidString(name)
{
bytesmemory n =bytes(name);
if (n.length>25) revert InvalidLength();
if (keccak256(n) ==keccak256(bytes(metadata[tokenId].name)))
revert InvalidValue();
metadata[tokenId].name= name;
emit NameChanged(tokenId, name);
}
/**
* @notice Sets the lore/backstory of a particular token id
* @dev only token owner call this function
* @param tokenId The token id
* @param lore The name to set
*/functionsetLore(uint256 tokenId, stringcalldata lore)
publicoverrideisTokenOwner(tokenId)
isValidString(lore)
{
bytesmemory n =bytes(lore);
if (keccak256(n) ==keccak256(bytes(metadata[tokenId].lore)))
revert InvalidValue();
metadata[tokenId].lore = lore;
emit LoreChanged(tokenId, lore);
}
/**
* @notice Sets the equipped items of a particular token id and item type
* @dev only token owner call this function
* @param tokenId The token id of the bear
* @param typeOf The type of item to equip
* @param itemTokenId The token id of the item
*/functionequip(uint256 tokenId,
stringcalldata typeOf,
uint256 itemTokenId
)
publicoverrideisTokenOwner(tokenId)
isItemTokenOwner(itemTokenId)
isItemValidType(itemTokenId, typeOf)
isItemXPMet(itemTokenId, tokenId)
nonReentrant{
bytes32 itemType =keccak256(abi.encodePacked(typeOf));
CustomMetadata storage instance = metadata[tokenId];
if (WEAPON_ITEM_TYPE == itemType) {
require(instance.weapon ==0, "96");
instance.weapon = itemTokenId;
} elseif (HEAD_ITEM_TYPE == itemType) {
require(instance.head ==0, "96");
instance.head = itemTokenId;
} elseif (ARMOR_ITEM_TYPE == itemType) {
require(instance.armor ==0, "96");
instance.armor = itemTokenId;
} elseif (BACKGROUND_ITEM_TYPE == itemType) {
require(instance.background ==0, "96");
instance.background = itemTokenId;
} elseif (FACE_ARMOR_ITEM_TYPE == itemType) {
require(instance.faceArmor ==0, "96");
instance.faceArmor = itemTokenId;
} elseif (EYEWEAR_ITEM_TYPE == itemType) {
require(instance.eyewear ==0, "96");
instance.eyewear = itemTokenId;
} elseif (MISC_ITEM_TYPE == itemType) {
require(instance.misc ==0, "96");
instance.misc = itemTokenId;
} else {
revert InvalidItemType();
}
// Burn item
vendorContract.burnItemForOwnerAddress(itemTokenId, 1, _msgSender());
emit Equipped(tokenId, typeOf, itemTokenId);
}
/**
* @notice Unsets the equipped items of a particular token id
* @dev only token owner call this function
* @param typeOf The type of item to equip
* @param tokenId The token id
*/functionunequip(uint256 tokenId, stringcalldata typeOf)
publicoverrideisTokenOwner(tokenId)
nonReentrant{
uint256 itemTokenId;
bytes32 itemType =keccak256(abi.encodePacked(typeOf));
CustomMetadata storage instance = metadata[tokenId];
if (WEAPON_ITEM_TYPE == itemType) {
itemTokenId = instance.weapon;
instance.weapon =0;
} elseif (HEAD_ITEM_TYPE == itemType) {
itemTokenId = instance.head;
instance.head =0;
} elseif (ARMOR_ITEM_TYPE == itemType) {
itemTokenId = instance.armor;
instance.armor =0;
} elseif (BACKGROUND_ITEM_TYPE == itemType) {
itemTokenId = instance.background;
instance.background =0;
} elseif (FACE_ARMOR_ITEM_TYPE == itemType) {
itemTokenId = instance.faceArmor;
instance.faceArmor =0;
} elseif (EYEWEAR_ITEM_TYPE == itemType) {
itemTokenId = instance.eyewear;
instance.eyewear =0;
} elseif (MISC_ITEM_TYPE == itemType) {
itemTokenId = instance.misc;
instance.misc =0;
} else {
revert InvalidItemType();
}
require(itemTokenId >0, "6969");
// Mint item
vendorContract.mintItemToAddress(itemTokenId, 1, _msgSender());
emit Unequipped(tokenId, typeOf, itemTokenId);
}
// ========================================// NFT display helpers// ========================================/// @notice Reveal called by the governance to reveal the seed of the NFTfunctionreveal() externalonlyRole(OWNER_ROLE) {
_reveal();
emit Revealed(totalSupply());
}
/// @notice The custom metadata associated to a given tokenIdfunctiongetMetadata(uint256 tokenId)
externalviewoverridereturns (CustomMetadata memory)
{
require(_exists(tokenId), "0");
return metadata[tokenId];
}
/// @notice The token uri for a given tokenIdfunctiontokenURI(uint256 tokenId)
publicviewoverridereturns (stringmemory)
{
if (isRevealed ==false) {
return renderer.hiddenURI(tokenId);
}
require(_exists(tokenId), "0");
CustomMetadata memory md = metadata[tokenId];
md.isUnlocked = isUnlocked(tokenId);
md.faction = factionContract.getFaction(ownerOf(tokenId));
return renderer.tokenURI(tokenId, seed(tokenId), md);
}
// ========================================// Mint Helpers// ========================================/**
* @notice Free claim mint, requires access pass ownership
* @param _tokenIds of the access pass
*/functionclaim(uint256[] calldata _tokenIds) externalnonReentrant{
require(isPublicLive(), "0");
for (uint256 i =0; i < _tokenIds.length; i++) {
accessPassContract.transferFrom(
_msgSender(),
DEAD_ADDRESS,
_tokenIds[i]
);
}
_safeMint(_msgSender(), _tokenIds.length, "");
}
/**
* @notice Whitelisted mint, requires a merkle proof
* @param _amount of mints
* @param _proof hashed array proof
*/functionwhitelistMint(uint256 _amount, bytes32[] calldata _proof)
externalpayablenonReentrant{
require(isWhitelistLive(), "0");
require(totalSupply() + _amount < maxSupply, "9");
require(msg.value>= _amount * price, "1");
require(addressToMinted[_msgSender()] + _amount < maxPerWallet, "2");
bytes32 leaf =keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_proof, merkleRoot, leaf), "4");
addressToMinted[_msgSender()] += _amount;
_safeMint(_msgSender(), _amount, "");
// Shop drop chance gameif (isShopDropEnabled) {
vendorContract.shopDrop(_msgSender(), _amount);
}
}
/**
* @notice Public mint
* @param _amount of mints
*/functionmint(uint256 _amount) externalpayable{
require(isPublicLive(), "0");
require(totalSupply() + _amount < maxSupply, "9");
require(msg.value>= _amount * price, "1");
require(addressToMinted[_msgSender()] + _amount < maxPerWallet, "2");
addressToMinted[_msgSender()] += _amount;
_safeMint(_msgSender(), _amount, "");
}
/**
* @notice Sets public price in wei
* @dev only owner call this function
* @param _price The new public price in wei
*/functionsetPrice(uint256 _price) publiconlyRole(OWNER_ROLE) {
price = _price;
}
/**
* @notice Sets the treasury recipient
* @dev only owner call this function
* @param _treasury The new price in wei
*/functionsetTreasury(address _treasury) publiconlyRole(OWNER_ROLE) {
treasury =payable(_treasury);
}
/**
* @notice Sets the reveal status of the metadata
* @dev only owner call this function
* @param _isRevealed The new boolean of the reveal
*/functionsetIsRevealed(bool _isRevealed) publiconlyRole(OWNER_ROLE) {
isRevealed = _isRevealed;
}
/**
* @notice Sets max supply for the collection
* @dev only owner call this function
* @param _maxSupply The new max supply value
*/functionsetMaxSupply(uint256 _maxSupply) externalonlyRole(OWNER_ROLE) {
maxSupply = _maxSupply;
}
/**
* @notice Sets the max mints per wallet
* @param _maxPerWallet The max per wallet (Keep mind its +1 n)
*/functionsetMaxPerWallet(uint256 _maxPerWallet)
externalonlyRole(OWNER_ROLE)
{
maxPerWallet = _maxPerWallet;
}
/**
* @notice Sets the go live timestamp for whitelist
* @param _whitelistLiveAt A base uri
*/functionsetWhitelistLiveAt(uint256 _whitelistLiveAt)
externalonlyRole(OWNER_ROLE)
{
whitelistLiveAt = _whitelistLiveAt;
}
/**
* @notice Sets the go live timestamp
* @param _liveAt A base uri
*/functionsetLiveAt(uint256 _liveAt) externalonlyRole(OWNER_ROLE) {
liveAt = _liveAt;
}
/**
* @notice Sets the merkle root for the mint
* @param _merkleRoot The merkle root to set
*/functionsetMerkleRoot(bytes32 _merkleRoot) externalonlyRole(OWNER_ROLE) {
merkleRoot = _merkleRoot;
}
/// @notice Withdraw from contractfunctionwithdraw() publiconlyRole(OWNER_ROLE) {
(bool success, ) = treasury.call{value: address(this).balance}("");
require(success, "999");
}
/// @notice Team mints ~4% of max supply - resets to 0 after team mint happensfunctionteamMints(address _to) externalonlyRole(OWNER_ROLE) {
require(teamMintAmount >0, "69");
_safeMint(_to, teamMintAmount, "");
teamMintAmount =0;
}
/**
* @notice Sets whether shop drop is enabled
* @param _isShopDropEnabled the bool value
*/functionsetShopDropEnabled(bool _isShopDropEnabled)
externalonlyRole(OWNER_ROLE)
{
isShopDropEnabled = _isShopDropEnabled;
}
// ========================================// Lock registry// ========================================/**
* @dev Overrides the normal `transferFrom` to include lock check
* @param from address
* @param to address
* @param tokenId of asset
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicoverride{
require(isUnlocked(tokenId), "1337");
super.transferFrom(from, to, tokenId);
}
/**
* @dev Overrides the normal `safeTransferFrom` to include lock check
* @param from address
* @param to address
* @param tokenId of asset
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) publicoverride{
require(isUnlocked(tokenId), "1337");
super.safeTransferFrom(from, to, tokenId, _data);
}
functionlockId(uint256 tokenId) externalonlyRole(XP_MUTATOR_ROLE) {
require(_exists(tokenId), "0");
_lockId(tokenId);
}
functionunlockId(uint256 tokenId) externalonlyRole(XP_MUTATOR_ROLE) {
require(_exists(tokenId), "0");
_unlockId(tokenId);
}
functionfreeId(uint256 tokenId, address contractAddress)
externalonlyRole(XP_MUTATOR_ROLE)
{
require(_exists(tokenId), "0");
_freeId(tokenId, contractAddress);
}
// ========================================// External contract helpers// ========================================/**
* @notice Adds XP to tokenId
* @param tokenId the token
* @param amount of xp to add
*/functionaddXP(uint256 tokenId, uint256 amount)
externalonlyRole(XP_MUTATOR_ROLE)
{
metadata[tokenId].xp += amount;
}
/**
* @notice Subtracts XP from tokenId
* @param tokenId the token
* @param amount of xp to subtract
*/functionsubtractXP(uint256 tokenId, uint256 amount)
externalonlyRole(XP_MUTATOR_ROLE)
{
metadata[tokenId].xp -= amount;
}
/**
* @notice Sets the bearz rendering library contract
* @dev only owner call this function
* @param _renderingContractAddress The new contract address
*/functionsetRenderingContractAddress(address _renderingContractAddress)
externalonlyRole(OWNER_ROLE)
{
renderer = IBrawlerBearzRenderer(_renderingContractAddress);
}
/**
* @notice Sets the bearz vendor item contract
* @dev only owner call this function
* @param _vendorContractAddress The new contract address
*/functionsetVendorContractAddress(address _vendorContractAddress)
externalonlyRole(OWNER_ROLE)
{
vendorContract = IBrawlerBearzDynamicItems(_vendorContractAddress);
}
functionsupportsInterface(bytes4 interfaceId)
publicviewvirtualoverride(ERC721Psi, AccessControl)
returns (bool)
{
returnsuper.supportsInterface(interfaceId);
}
// ========================================// Read operations// ========================================// @dev Check if mint is public livefunctionisWhitelistLive() publicviewreturns (bool) {
returnblock.timestamp> whitelistLiveAt;
}
// @dev Check if mint is public livefunctionisPublicLive() publicviewreturns (bool) {
returnblock.timestamp> liveAt;
}
// @dev Check if mint is public livefunctiongetAddressMintsRemaining(address _address)
publicviewreturns (uint256)
{
return maxPerWallet - addressToMinted[_address] -1;
}
/*
* @notice Return token ids for a given address
* @param _owner address
*/functionwalletOfOwner(address _owner)
publicviewreturns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount ==0) returnnewuint256[](0);
uint256[] memory tokensId =newuint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
// ========================================// Chainlink integrations// ========================================function_keyHash() internalviewoverridereturns (bytes32) {
return keyHash;
}
function_subscriptionId() internalviewoverridereturns (uint64) {
return subscriptionId;
}
}
Contract Source Code
File 6 of 35: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 7 of 35: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 8 of 35: ERC721Psi.sol
// SPDX-License-Identifier: MIT/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/pragmasolidity ^0.8.0;import"@openzeppelin/contracts/token/ERC721/IERC721.sol";
import"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import"@openzeppelin/contracts/utils/Context.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
import"@openzeppelin/contracts/utils/introspection/ERC165.sol";
import"./BitMaps.sol";
import"./Address.sol";
contractERC721PsiisContext,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable{
usingAddressforaddress;
usingStringsforuint256;
usingBitMapsforBitMaps.BitMap;
BitMaps.BitMap private _batchHead;
stringprivate _name;
stringprivate _symbol;
// Mapping from token ID to owner addressmapping(uint256=>address) internal _owners;
uint256internal _minted;
mapping(uint256=>address) private _tokenApprovals;
mapping(address=>mapping(address=>bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId)
publicviewvirtualoverride(ERC165, IERC165)
returns (bool)
{
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||
interfaceId ==type(IERC721Enumerable).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner)
publicviewvirtualoverridereturns (uint256)
{
require(owner !=address(0), "zero address");
uint256 count;
for (uint256 i; i < _minted; ++i) {
if (_exists(i)) {
if (owner == ownerOf(i)) {
++count;
}
}
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId)
publicviewvirtualoverridereturns (address)
{
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
return owner;
}
function_ownerAndBatchHeadOf(uint256 tokenId)
internalviewreturns (address owner, uint256 tokenIdBatchHead)
{
require(_exists(tokenId), "!exists");
tokenIdBatchHead = _getBatchHead(tokenId);
owner = _owners[tokenIdBatchHead];
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId)
publicviewvirtualoverridereturns (stringmemory)
{
require(_exists(tokenId), "!exists");
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length>0
? string(abi.encodePacked(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 overriden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return"";
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicvirtualoverride{
address owner = ownerOf(tokenId);
require(to != owner, "!approval");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"!approved"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId)
publicviewvirtualoverridereturns (address)
{
require(_exists(tokenId), "!exists");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved)
publicvirtualoverride{
require(operator != _msgSender(), "!approve");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator)
publicviewvirtualoverridereturns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
//solhint-disable-next-line max-line-lengthrequire(_isApprovedOrOwner(_msgSender(), tokenId), "!approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) publicvirtualoverride{
require(_isApprovedOrOwner(_msgSender(), tokenId), "!approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeTransfer(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) internalvirtual{
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"!ERC721Receiver"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`).
*/function_exists(uint256 tokenId) internalviewvirtualreturns (bool) {
return tokenId < _minted;
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/function_isApprovedOrOwner(address spender, uint256 tokenId)
internalviewvirtualreturns (bool)
{
require(_exists(tokenId), "!exist");
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/function_safeMint(address to, uint256 quantity) internalvirtual{
_safeMint(to, quantity, "");
}
function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internalvirtual{
uint256 tokenIdBatchHead = _minted;
require(quantity >0, "zero");
require(to !=address(0), "!zeroaddress");
_beforeTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
for (uint256 i =0; i < quantity; i++) {
uint256 tokenId = tokenIdBatchHead + i;
emit Transfer(address(0), to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"!ERC721Receiver"
);
}
_owners[tokenIdBatchHead] = to;
_batchHead.set(tokenIdBatchHead);
_minted += quantity;
_afterTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
require(owner ==from, "notown");
require(to !=address(0), "zeroaddress");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
uint256 nextTokenId = tokenId +1;
if (!_batchHead.get(nextTokenId) && nextTokenId < _minted) {
_owners[nextTokenId] =from;
_batchHead.set(nextTokenId);
}
_owners[tokenId] = to;
if (tokenId != tokenIdBatchHead) {
_batchHead.set(tokenId);
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/function_checkOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert("!ERC721Receiver");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
function_getBatchHead(uint256 tokenId)
internalviewreturns (uint256 tokenIdBatchHead)
{
tokenIdBatchHead = _batchHead.scanForward(tokenId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _minted;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/functiontokenByIndex(uint256 index)
publicviewvirtualoverridereturns (uint256)
{
require(index < totalSupply(), "oob");
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i)) {
if (count == index) return i;
else count++;
}
}
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/functiontokenOfOwnerByIndex(address owner, uint256 index)
publicviewvirtualoverridereturns (uint256 tokenId)
{
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i) && owner == ownerOf(i)) {
if (count == index) return i;
else count++;
}
}
revert("oob");
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/function_beforeTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/function_afterTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
}
Contract Source Code
File 9 of 35: ERC721PsiBatchMetaData.sol
// SPDX-License-Identifier: MIT/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/pragmasolidity ^0.8.0;import"./ERC721Psi.sol";
import"./BitMaps.sol";
abstractcontractERC721PsiBatchMetaDataisERC721Psi{
usingBitMapsforBitMaps.BitMap;
BitMaps.BitMap private _metaDataBatchHead;
function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internalvirtualoverride{
uint256 tokenIdBatchHead = _minted;
_metaDataBatchHead.set(tokenIdBatchHead);
super._safeMint(to, quantity, _data);
}
/**
* @dev Return the batch head tokenId where the on-chain metadata is stored during minting.
*
* The returned tokenId will remain the same after the token transfer.
*/function_getMetaDataBatchHead(uint256 tokenId)
internalviewreturns (uint256 tokenIdMetaDataBatchHead)
{
tokenIdMetaDataBatchHead = _metaDataBatchHead.scanForward(tokenId);
}
}
Contract Source Code
File 10 of 35: ERC721PsiRandomSeedReveal.sol
// SPDX-License-Identifier: MIT/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/pragmasolidity ^0.8.0;import"@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import"@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import"./interfaces/IERC721RandomSeed.sol";
import"./BitMaps.sol";
import"./ERC721PsiBatchMetaData.sol";
abstractcontractERC721PsiRandomSeedRevealisIERC721RandomSeed,
ERC721PsiBatchMetaData,
VRFConsumerBaseV2{
// Chainklink VRF V2
VRFCoordinatorV2Interface immutable COORDINATOR;
uint32immutable callbackGasLimit;
uint16immutable requestConfirmations;
uint16constant numWords =1;
// requestId => genIdmapping(uint256=>uint256) private requestIdToGenId;
// genId => seedmapping(uint256=>uint256) private genSeed;
// batchHeadTokenId => genIdmapping(uint256=>uint256) private _batchHeadtokenGen;
// current genId for mintinguint256private currentGen =1;
eventRandomnessRequest(uint256 requestId);
constructor(address coordinator,
uint32 _callbackGasLimit,
uint16 _requestConfirmations
) VRFConsumerBaseV2(coordinator) {
COORDINATOR = VRFCoordinatorV2Interface(coordinator);
callbackGasLimit = _callbackGasLimit;
requestConfirmations = _requestConfirmations;
}
/**
* Callback function used by VRF Coordinator
*/functionfulfillRandomWords(uint256 requestId, uint256[] memory randomWords)
internaloverride{
uint256 randomness = randomWords[0];
uint256 genId = requestIdToGenId[requestId];
delete requestIdToGenId[genId];
genSeed[genId] = randomness;
_processRandomnessFulfillment(requestId, genId, randomness);
}
function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internalvirtualoverride{
uint256 tokenIdHead = _minted;
_batchHeadtokenGen[tokenIdHead] = currentGen;
super._safeMint(to, quantity, _data);
}
/**
@dev Query the generation of `tokenId`.
*/function_tokenGen(uint256 tokenId) internalviewreturns (uint256) {
require(_exists(tokenId), "!exists");
return _batchHeadtokenGen[_getMetaDataBatchHead(tokenId)];
}
/**
@dev Request the randomess for the tokens of the current generation.
*/function_reveal() internalvirtual{
uint256 requestId = COORDINATOR.requestRandomWords(
_keyHash(),
_subscriptionId(),
requestConfirmations,
callbackGasLimit,
numWords
);
emit RandomnessRequest(requestId);
requestIdToGenId[requestId] = currentGen;
_processRandomnessRequest(requestId, currentGen);
currentGen++;
}
/**
@dev Return the random seed of `tokenId`.
Revert when the randomness hasn't been fulfilled.
*/functionseed(uint256 tokenId)
publicviewvirtualoverridereturns (uint256)
{
require(_exists(tokenId), "!exists");
unchecked {
uint256 _genSeed = genSeed[_tokenGen(tokenId)];
require(_genSeed !=0, "!fullfilled");
returnuint256(keccak256(abi.encode(_genSeed, tokenId)));
}
}
/**
@dev Override the function to provide the corrosponding keyHash for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/vrf-contracts/
*/function_keyHash() internalvirtualreturns (bytes32);
/**
@dev Override the function to provide the corrosponding subscription id for the Chainlink VRF V2.
see also: https://docs.chain.link/docs/get-a-random-number/#create-and-fund-a-subscription
*/function_subscriptionId() internalvirtualreturns (uint64);
function_processRandomnessRequest(uint256 requestId, uint256 genId)
internal{}
function_processRandomnessFulfillment(uint256 requestId,
uint256 genId,
uint256 randomness
) internal{}
}
Contract Source Code
File 11 of 35: ERC721PsiRandomSeedRevealBurnable.sol
// SPDX-License-Identifier: MIT/**
______ _____ _____ ______ ___ __ _ _ _
| ____| __ \ / ____|____ |__ \/_ | || || |
| |__ | |__) | | / / ) || | \| |/ |
| __| | _ /| | / / / / | |\_ _/
| |____| | \ \| |____ / / / /_ | | | |
|______|_| \_\\_____|/_/ |____||_| |_|
*/pragmasolidity ^0.8.0;import"./BitMaps.sol";
import"./ERC721PsiRandomSeedReveal.sol";
abstractcontractERC721PsiRandomSeedRevealBurnableisERC721PsiRandomSeedReveal{
usingBitMapsforBitMaps.BitMap;
BitMaps.BitMap private _burnedToken;
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
addressfrom= ownerOf(tokenId);
_beforeTokenTransfers(from, address(0), tokenId, 1);
_burnedToken.set(tokenId);
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/function_exists(uint256 tokenId)
internalviewvirtualoverridereturns (bool)
{
if (_burnedToken.get(tokenId)) {
returnfalse;
}
returnsuper._exists(tokenId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _minted - _burned();
}
/**
* @dev Returns number of token burned.
*/function_burned() internalviewreturns (uint256 burned) {
uint256 totalBucket = (_minted >>8) +1;
for (uint256 i =0; i < totalBucket; i++) {
uint256 bucket = _burnedToken.getBucket(i);
burned += _popcount(bucket);
}
}
/**
* @dev Returns number of set bits.
*/function_popcount(uint256 x) privatepurereturns (uint256 count) {
unchecked {
for (count =0; x !=0; count++) x &= x -1;
}
}
}
Contract Source Code
File 12 of 35: IAccessControl.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)pragmasolidity ^0.8.0;/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/interfaceIAccessControl{
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/eventRoleAdminChanged(bytes32indexed role, bytes32indexed previousAdminRole, bytes32indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/eventRoleGranted(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/eventRoleRevoked(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) externalviewreturns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) externalviewreturns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functiongrantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functionrevokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/functionrenounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/interfaceIERC1155isIERC165{
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/eventTransferSingle(addressindexed operator, addressindexedfrom, addressindexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/eventTransferBatch(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/eventApprovalForAll(addressindexed account, addressindexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/eventURI(string value, uint256indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) externalviewreturns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
externalviewreturns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address account, address operator) externalviewreturns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytescalldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytescalldata data
) external;
}
Contract Source Code
File 21 of 35: IERC1155Upgradeable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/interfaceIERC1155UpgradeableisIERC165Upgradeable{
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/eventTransferSingle(addressindexed operator, addressindexedfrom, addressindexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/eventTransferBatch(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/eventApprovalForAll(addressindexed account, addressindexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/eventURI(string value, uint256indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) externalviewreturns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
externalviewreturns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address account, address operator) externalviewreturns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytescalldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytescalldata data
) external;
}
Contract Source Code
File 22 of 35: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 23 of 35: IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165Upgradeable{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 24 of 35: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
}
Contract Source Code
File 25 of 35: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/interfaceIERC721EnumerableisIERC721{
/**
* @dev Returns the total amount of tokens stored by the contract.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) externalviewreturns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol)pragmasolidity ^0.8.0;/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/libraryMerkleProof{
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/functionverify(bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internalpurereturns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/functionprocessProof(bytes32[] memory proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function_efficientHash(bytes32 a, bytes32 b) privatepurereturns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value :=keccak256(0x00, 0x40)
}
}
}
Contract Source Code
File 31 of 35: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. 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.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 32 of 35: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)pragmasolidity ^0.8.0;/**
* @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].
*/abstractcontractReentrancyGuard{
// 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.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _status;
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.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
Contract Source Code
File 33 of 35: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
}
Contract Source Code
File 34 of 35: VRFConsumerBaseV2.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/abstractcontractVRFConsumerBaseV2{
errorOnlyCoordinatorCanFulfill(address have, address want);
addressprivateimmutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/functionfulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internalvirtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF// proof. rawFulfillRandomness then calls fulfillRandomness, after validating// the origin of the callfunctionrawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external{
if (msg.sender!= vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
Contract Source Code
File 35 of 35: VRFCoordinatorV2Interface.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;interfaceVRFCoordinatorV2Interface{
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/functiongetRequestConfig()
externalviewreturns (uint16,
uint32,
bytes32[] memory);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/functionrequestRandomWords(bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) externalreturns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/functioncreateSubscription() externalreturns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/functiongetSubscription(uint64 subId)
externalviewreturns (uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/functionrequestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/functionacceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/functionaddConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/functionremoveConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/functioncancelSubscription(uint64 subId, address to) external;
}