Verified contractExactMIT
DNACardSaleAllowlist
Address0xd5042b342a0b33dfabe2e5e34ebf498aae71f760
- Balance
0 ETH
- Transactions
46
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,631,451
- Creation transaction
- 0x7adcb2116b…ecac4f1831
48 files
- contracts/DNACardSaleAllowlist.solmain4.48 KB
- @limitbreak/creator-token-standards/src/access/OwnableBasic.sol320 B
- @limitbreak/creator-token-standards/src/access/OwnablePermissions.sol230 B
- @limitbreak/creator-token-standards/src/erc1155c/ERC1155C.sol7.03 KB
- @limitbreak/creator-token-standards/src/erc721c/ERC721C.sol6.58 KB
- @limitbreak/creator-token-standards/src/interfaces/ICreatorToken.sol422 B
- @limitbreak/creator-token-standards/src/interfaces/ICreatorTokenLegacy.sol313 B
- @limitbreak/creator-token-standards/src/interfaces/ITransferValidator.sol1.09 KB
- @limitbreak/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol187 B
- @limitbreak/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol1.54 KB
- @limitbreak/creator-token-standards/src/token/erc1155/ERC1155OpenZeppelin.sol865 B
- @limitbreak/creator-token-standards/src/token/erc721/ERC721OpenZeppelin.sol1.7 KB
- @limitbreak/creator-token-standards/src/utils/AutomaticValidatorTransferApproval.sol1.39 KB
- @limitbreak/creator-token-standards/src/utils/CreatorTokenBase.sol8.25 KB
- @limitbreak/creator-token-standards/src/utils/TransferValidation.sol6.45 KB
- @limitbreak/permit-c/src/Constants.sol3.54 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/interfaces/IERC2981.sol888 B
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.84 KB
- @openzeppelin/contracts/token/ERC1155/ERC1155.sol17.26 KB
- @openzeppelin/contracts/token/ERC1155/IERC1155.sol4.07 KB
- @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol2.5 KB
- @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol675 B
- @openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol974 B
- @openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol611 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- @openzeppelin/contracts/token/ERC721/ERC721.sol17.31 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.98 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol987 B
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- @openzeppelin/contracts/token/common/ERC2981.sol4.1 KB
- @openzeppelin/contracts/utils/Address.sol9.16 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.25 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- @openzeppelin/contracts/utils/math/Math.sol12.51 KB
- @openzeppelin/contracts/utils/math/SafeMath.sol6.78 KB
- contracts/BioCanvas.sol3.81 KB
- contracts/DNACard.sol10.14 KB
- contracts/DNACardLib.sol164 B
- contracts/DNACardReveal.sol27.06 KB
- contracts/Drifter.sol9.47 KB
- contracts/DrifterEquip.sol4.56 KB
- contracts/DrifterName.sol9.94 KB
- contracts/GEAR.sol8.14 KB
- contracts/GEARMetadata.sol12.12 KB
- contracts/SplitRoyalties.sol10.75 KB
contracts/DNACardSaleAllowlist.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./DNACard.sol";
import "./BioCanvas.sol";
contract DNACardSaleAllowlist is Ownable, ReentrancyGuard {
using SafeMath for uint256;
DNACard public dnaCard;
BioCanvas public bioCanvas;
bool public saleIsActive = false;
bool public publicSaleIsActive = false;
uint256 public SMALL_PRICE = 0.01 ether;
uint256 public MEDIUM_PRICE = 0.02 ether;
uint256 public LARGE_PRICE = 0.03 ether;
mapping(address => bool) public allowlist;
mapping(address => uint256) public allowlistMinted;
uint256 public MAX_ALLOWLIST_MINT = 21;
modifier whenSaleIsActive() {
require(saleIsActive, "Sale is not active");
_;
}
modifier whenPublicSaleIsActiveOrAllowlisted() {
require(publicSaleIsActive || allowlist[msg.sender], "Not in allowlist");
_;
}
constructor(address payable _dnaCardAddress, address payable _bioCanvasAddress) {
dnaCard = DNACard(_dnaCardAddress);
bioCanvas = BioCanvas(_bioCanvasAddress);
}
function addToAllowlist(address[] memory _allowlist) external onlyOwner {
for (uint256 i = 0; i < _allowlist.length; i++) {
allowlist[_allowlist[i]] = true;
}
}
function removeFromAllowlist(address[] memory _addresses) external onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
allowlist[_addresses[i]] = false;
}
}
function setMaxAllowlistMint(uint256 _maxAllowlistMint) external onlyOwner {
require(_maxAllowlistMint > 0, "Max allowlist mint must be greater than 0");
MAX_ALLOWLIST_MINT = _maxAllowlistMint;
}
function setSaleState(bool _state) external onlyOwner {
saleIsActive = _state;
}
function setPublicSaleActive(bool _state) external onlyOwner {
publicSaleIsActive = _state;
}
function setSalePrice(uint8 cardType, uint256 price) external onlyOwner {
require(cardType >= 0 && cardType <= 2, "Invalid card type");
if (cardType == 0) {
SMALL_PRICE = price;
} else if (cardType == 1) {
MEDIUM_PRICE = price;
} else {
LARGE_PRICE = price;
}
}
function _processPurchase(address buyer, uint256 smallAmount, uint256 mediumAmount, uint256 largeAmount) internal {
uint256 currentSmallMinted = dnaCard.smallMinted();
uint256 currentMediumMinted = dnaCard.mediumMinted();
uint256 currentLargeMinted = dnaCard.largeMinted();
require(currentSmallMinted.add(smallAmount) <= dnaCard.SMALL_SUPPLY(), "Exceeds small card supply");
require(currentMediumMinted.add(mediumAmount) <= dnaCard.MEDIUM_SUPPLY(), "Exceeds medium card supply");
require(currentLargeMinted.add(largeAmount) <= dnaCard.LARGE_SUPPLY(), "Exceeds large card supply");
for (uint256 i = 0; i < smallAmount; i++) {
dnaCard.mint(buyer, 0);
}
for (uint256 i = 0; i < mediumAmount; i++) {
dnaCard.mint(buyer, 1);
}
for (uint256 i = 0; i < largeAmount; i++) {
dnaCard.mint(buyer, 2);
}
// Mint one BioCanvas for each DNA card minted
bioCanvas.mint(buyer, 1, smallAmount.add(mediumAmount).add(largeAmount));
}
function remainingAllowlistMint(address _address) external view returns (uint256) {
if (publicSaleIsActive) {
return 7777 - dnaCard.totalSupply();
}
if (!allowlist[_address]) {
return 0;
}
if (allowlistMinted[_address] >= MAX_ALLOWLIST_MINT) {
return 0;
} else {
return MAX_ALLOWLIST_MINT - allowlistMinted[_address];
}
}
function buy(
uint256 smallAmount,
uint256 mediumAmount,
uint256 largeAmount
) external payable nonReentrant whenSaleIsActive whenPublicSaleIsActiveOrAllowlisted {
uint256 totalCost = SMALL_PRICE.mul(smallAmount).add(MEDIUM_PRICE.mul(mediumAmount)).add(LARGE_PRICE.mul(largeAmount));
require(msg.value >= totalCost, "Insufficient payment");
if (!publicSaleIsActive) {
require(allowlistMinted[msg.sender] + smallAmount + mediumAmount + largeAmount <= MAX_ALLOWLIST_MINT, "Exceeds allowlist mint limit");
allowlistMinted[msg.sender] += smallAmount + mediumAmount + largeAmount;
}
_processPurchase(msg.sender, smallAmount, mediumAmount, largeAmount);
if (msg.value > totalCost) {
payable(msg.sender).transfer(msg.value - totalCost);
}
}
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
@limitbreak/creator-token-standards/src/access/OwnableBasic.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./OwnablePermissions.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract OwnableBasic is OwnablePermissions, Ownable {
function _requireCallerIsContractOwner() internal view virtual override {
_checkOwner();
}
}
@limitbreak/creator-token-standards/src/access/OwnablePermissions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
abstract contract OwnablePermissions is Context {
function _requireCallerIsContractOwner() internal view virtual;
}
@limitbreak/creator-token-standards/src/erc1155c/ERC1155C.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../utils/AutomaticValidatorTransferApproval.sol";
import "../utils/CreatorTokenBase.sol";
import "../token/erc1155/ERC1155OpenZeppelin.sol";
import {TOKEN_TYPE_ERC1155} from "@limitbreak/permit-c/src/Constants.sol";
/**
* @title ERC1155C
* @author Limit Break, Inc.
* @notice Extends OpenZeppelin's ERC1155 implementation with Creator Token functionality, which
* allows the contract owner to update the transfer validation logic by managing a security policy in
* an external transfer validation security policy registry. See {CreatorTokenTransferValidator}.
*/
abstract contract ERC1155C is ERC1155OpenZeppelin, CreatorTokenBase, AutomaticValidatorTransferApproval {
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256,uint256)"));
isViewFunction = false;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateBeforeTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateAfterTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC1155);
}
}
/**
* @title ERC1155CInitializable
* @author Limit Break, Inc.
* @notice Initializable implementation of ERC1155C to allow for EIP-1167 proxy clones.
*/
abstract contract ERC1155CInitializable is ERC1155OpenZeppelinInitializable, CreatorTokenBase, AutomaticValidatorTransferApproval {
function initializeERC1155(string memory uri_) public override {
super.initializeERC1155(uri_);
_emitDefaultTransferValidator();
_registerTokenType(getTransferValidator());
}
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256,uint256)"));
isViewFunction = false;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateBeforeTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateAfterTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC1155);
}
}
@limitbreak/creator-token-standards/src/erc721c/ERC721C.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../utils/AutomaticValidatorTransferApproval.sol";
import "../utils/CreatorTokenBase.sol";
import "../token/erc721/ERC721OpenZeppelin.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
import {TOKEN_TYPE_ERC721} from "@limitbreak/permit-c/src/Constants.sol";
/**
* @title ERC721C
* @author Limit Break, Inc.
* @notice Extends OpenZeppelin's ERC721 implementation with Creator Token functionality, which
* allows the contract owner to update the transfer validation logic by managing a security policy in
* an external transfer validation security policy registry. See {CreatorTokenTransferValidator}.
*/
abstract contract ERC721C is ERC721OpenZeppelin, CreatorTokenBase, AutomaticValidatorTransferApproval {
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256)"));
isViewFunction = true;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateBeforeTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateAfterTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC721);
}
}
/**
* @title ERC721CInitializable
* @author Limit Break, Inc.
* @notice Initializable implementation of ERC721C to allow for EIP-1167 proxy clones.
*/
abstract contract ERC721CInitializable is ERC721OpenZeppelinInitializable, CreatorTokenBase, AutomaticValidatorTransferApproval {
function initializeERC721(string memory name_, string memory symbol_) public override {
super.initializeERC721(name_, symbol_);
_emitDefaultTransferValidator();
_registerTokenType(getTransferValidator());
}
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256)"));
isViewFunction = true;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateBeforeTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize) internal virtual override {
for (uint256 i = 0; i < batchSize;) {
_validateAfterTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC721);
}
}@limitbreak/creator-token-standards/src/interfaces/ICreatorToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorToken {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}@limitbreak/creator-token-standards/src/interfaces/ICreatorTokenLegacy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorTokenLegacy {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}
@limitbreak/creator-token-standards/src/interfaces/ITransferValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidator {
function applyCollectionTransferPolicy(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount) external;
function beforeAuthorizedTransfer(address operator, address token, uint256 tokenId) external;
function afterAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransfer(address operator, address token) external;
function afterAuthorizedTransfer(address token) external;
function beforeAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransferWithAmount(address token, uint256 tokenId, uint256 amount) external;
function afterAuthorizedTransferWithAmount(address token, uint256 tokenId) external;
}@limitbreak/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}@limitbreak/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/common/ERC2981.sol";
/**
* @title BasicRoyaltiesBase
* @author Limit Break, Inc.
* @dev Base functionality of an NFT mix-in contract implementing the most basic form of programmable royalties.
*/
abstract contract BasicRoyaltiesBase is ERC2981 {
event DefaultRoyaltySet(address indexed receiver, uint96 feeNumerator);
event TokenRoyaltySet(uint256 indexed tokenId, address indexed receiver, uint96 feeNumerator);
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual override {
super._setDefaultRoyalty(receiver, feeNumerator);
emit DefaultRoyaltySet(receiver, feeNumerator);
}
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual override {
super._setTokenRoyalty(tokenId, receiver, feeNumerator);
emit TokenRoyaltySet(tokenId, receiver, feeNumerator);
}
}
/**
* @title BasicRoyalties
* @author Limit Break, Inc.
* @notice Constructable BasicRoyalties Contract implementation.
*/
abstract contract BasicRoyalties is BasicRoyaltiesBase {
constructor(address receiver, uint96 feeNumerator) {
_setDefaultRoyalty(receiver, feeNumerator);
}
}
/**
* @title BasicRoyaltiesInitializable
* @author Limit Break, Inc.
* @notice Initializable BasicRoyalties Contract implementation to allow for EIP-1167 clones.
*/
abstract contract BasicRoyaltiesInitializable is BasicRoyaltiesBase {}@limitbreak/creator-token-standards/src/token/erc1155/ERC1155OpenZeppelin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../../access/OwnablePermissions.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
abstract contract ERC1155OpenZeppelinBase is ERC1155 {
}
abstract contract ERC1155OpenZeppelin is ERC1155OpenZeppelinBase {
constructor(string memory uri_) ERC1155(uri_) {}
}
abstract contract ERC1155OpenZeppelinInitializable is OwnablePermissions, ERC1155OpenZeppelinBase {
error ERC1155OpenZeppelinInitializable__AlreadyInitializedERC1155();
bool private _erc1155Initialized;
function initializeERC1155(string memory uri_) public virtual {
_requireCallerIsContractOwner();
if(_erc1155Initialized) {
revert ERC1155OpenZeppelinInitializable__AlreadyInitializedERC1155();
}
_erc1155Initialized = true;
_setURI(uri_);
}
}@limitbreak/creator-token-standards/src/token/erc721/ERC721OpenZeppelin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../../access/OwnablePermissions.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
abstract contract ERC721OpenZeppelinBase is ERC721 {
// Token name
string internal _contractName;
// Token symbol
string internal _contractSymbol;
function name() public view virtual override returns (string memory) {
return _contractName;
}
function symbol() public view virtual override returns (string memory) {
return _contractSymbol;
}
function _setNameAndSymbol(string memory name_, string memory symbol_) internal {
_contractName = name_;
_contractSymbol = symbol_;
}
}
abstract contract ERC721OpenZeppelin is ERC721OpenZeppelinBase {
constructor(string memory name_, string memory symbol_) ERC721("", "") {
_setNameAndSymbol(name_, symbol_);
}
}
abstract contract ERC721OpenZeppelinInitializable is OwnablePermissions, ERC721OpenZeppelinBase {
error ERC721OpenZeppelinInitializable__AlreadyInitializedERC721();
/// @notice Specifies whether or not the contract is initialized
bool private _erc721Initialized;
/// @dev Initializes parameters of ERC721 tokens.
/// These cannot be set in the constructor because this contract is optionally compatible with EIP-1167.
function initializeERC721(string memory name_, string memory symbol_) public virtual {
_requireCallerIsContractOwner();
if(_erc721Initialized) {
revert ERC721OpenZeppelinInitializable__AlreadyInitializedERC721();
}
_erc721Initialized = true;
_setNameAndSymbol(name_, symbol_);
}
}
@limitbreak/creator-token-standards/src/utils/AutomaticValidatorTransferApproval.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
/**
* @title AutomaticValidatorTransferApproval
* @author Limit Break, Inc.
* @notice Base contract mix-in that provides boilerplate code giving the contract owner the
* option to automatically approve a 721-C transfer validator implementation for transfers.
*/
abstract contract AutomaticValidatorTransferApproval is OwnablePermissions {
/// @dev Emitted when the automatic approval flag is modified by the creator.
event AutomaticApprovalOfTransferValidatorSet(bool autoApproved);
/// @dev If true, the collection's transfer validator is automatically approved to transfer holder's tokens.
bool public autoApproveTransfersFromValidator;
/**
* @notice Sets if the transfer validator is automatically approved as an operator for all token owners.
*
* @dev Throws when the caller is not the contract owner.
*
* @param autoApprove If true, the collection's transfer validator will be automatically approved to
* transfer holder's tokens.
*/
function setAutomaticApprovalOfTransfersFromValidator(bool autoApprove) external {
_requireCallerIsContractOwner();
autoApproveTransfersFromValidator = autoApprove;
emit AutomaticApprovalOfTransferValidatorSet(autoApprove);
}
}@limitbreak/creator-token-standards/src/utils/CreatorTokenBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
import "../interfaces/ICreatorToken.sol";
import "../interfaces/ICreatorTokenLegacy.sol";
import "../interfaces/ITransferValidator.sol";
import "./TransferValidation.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
/**
* @title CreatorTokenBase
* @author Limit Break, Inc.
* @notice CreatorTokenBaseV3 is an abstract contract that provides basic functionality for managing token
* transfer policies through an implementation of ICreatorTokenTransferValidator/ICreatorTokenTransferValidatorV2/ICreatorTokenTransferValidatorV3.
* This contract is intended to be used as a base for creator-specific token contracts, enabling customizable transfer
* restrictions and security policies.
*
* <h4>Features:</h4>
* <ul>Ownable: This contract can have an owner who can set and update the transfer validator.</ul>
* <ul>TransferValidation: Implements the basic token transfer validation interface.</ul>
*
* <h4>Benefits:</h4>
* <ul>Provides a flexible and modular way to implement custom token transfer restrictions and security policies.</ul>
* <ul>Allows creators to enforce policies such as account and codehash blacklists, whitelists, and graylists.</ul>
* <ul>Can be easily integrated into other token contracts as a base contract.</ul>
*
* <h4>Intended Usage:</h4>
* <ul>Use as a base contract for creator token implementations that require advanced transfer restrictions and
* security policies.</ul>
* <ul>Set and update the ICreatorTokenTransferValidator implementation contract to enforce desired policies for the
* creator token.</ul>
*
* <h4>Compatibility:</h4>
* <ul>Backward and Forward Compatible - V1/V2/V3 Creator Token Base will work with V1/V2/V3 Transfer Validators.</ul>
*/
abstract contract CreatorTokenBase is OwnablePermissions, TransferValidation, ICreatorToken {
/// @dev Thrown when setting a transfer validator address that has no deployed code.
error CreatorTokenBase__InvalidTransferValidatorContract();
/// @dev The default transfer validator that will be used if no transfer validator has been set by the creator.
address public constant DEFAULT_TRANSFER_VALIDATOR = address(0x721C002B0059009a671D00aD1700c9748146cd1B);
/// @dev Used to determine if the default transfer validator is applied.
/// @dev Set to true when the creator sets a transfer validator address.
bool private isValidatorInitialized;
/// @dev Address of the transfer validator to apply to transactions.
address private transferValidator;
constructor() {
_emitDefaultTransferValidator();
_registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
}
/**
* @notice Sets the transfer validator for the token contract.
*
* @dev Throws when provided validator contract is not the zero address and does not have code.
* @dev Throws when the caller is not the contract owner.
*
* @dev <h4>Postconditions:</h4>
* 1. The transferValidator address is updated.
* 2. The `TransferValidatorUpdated` event is emitted.
*
* @param transferValidator_ The address of the transfer validator contract.
*/
function setTransferValidator(address transferValidator_) public {
_requireCallerIsContractOwner();
bool isValidTransferValidator = transferValidator_.code.length > 0;
if(transferValidator_ != address(0) && !isValidTransferValidator) {
revert CreatorTokenBase__InvalidTransferValidatorContract();
}
emit TransferValidatorUpdated(address(getTransferValidator()), transferValidator_);
isValidatorInitialized = true;
transferValidator = transferValidator_;
_registerTokenType(transferValidator_);
}
/**
* @notice Returns the transfer validator contract address for this token contract.
*/
function getTransferValidator() public view override returns (address validator) {
validator = transferValidator;
if (validator == address(0)) {
if (!isValidatorInitialized) {
validator = DEFAULT_TRANSFER_VALIDATOR;
}
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId);
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Used for ERC20 and ERC1155 token transfers which have an amount value to validate in the transfer validator.
* @dev The `tokenId` for ERC20 tokens should be set to `0`.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
* @param amount The amount of token being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 amount,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId, amount);
}
}
function _tokenType() internal virtual pure returns(uint16);
function _registerTokenType(address validator) internal {
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if(validatorCodeSize > 0) {
try ITransferValidatorSetTokenType(validator).setTokenTypeOfCollection(address(this), _tokenType()) {
} catch { }
}
}
}
/**
* @dev Used during contract deployment for constructable and cloneable creator tokens
* @dev to emit the `TransferValidatorUpdated` event signaling the validator for the contract
* @dev is the default transfer validator.
*/
function _emitDefaultTransferValidator() internal {
emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
}
}
@limitbreak/creator-token-standards/src/utils/TransferValidation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title TransferValidation
* @author Limit Break, Inc.
* @notice A mix-in that can be combined with ERC-721 contracts to provide more granular hooks.
* Openzeppelin's ERC721 contract only provides hooks for before and after transfer. This allows
* developers to validate or customize transfers within the context of a mint, a burn, or a transfer.
*/
abstract contract TransferValidation is Context {
/// @dev Thrown when the from and to address are both the zero address.
error ShouldNotMintToBurnAddress();
/*************************************************************************/
/* Transfers Without Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/*************************************************************************/
/* Transfers With Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
}
@limitbreak/permit-c/src/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Constant bytes32 value of 0x000...000
bytes32 constant ZERO_BYTES32 = bytes32(0);
/// @dev Constant value of 0
uint256 constant ZERO = 0;
/// @dev Constant value of 1
uint256 constant ONE = 1;
/// @dev Constant value representing an open order in storage
uint8 constant ORDER_STATE_OPEN = 0;
/// @dev Constant value representing a filled order in storage
uint8 constant ORDER_STATE_FILLED = 1;
/// @dev Constant value representing a cancelled order in storage
uint8 constant ORDER_STATE_CANCELLED = 2;
/// @dev Constant value representing the ERC721 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC721 = 721;
/// @dev Constant value representing the ERC1155 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC1155 = 1155;
/// @dev Constant value representing the ERC20 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC20 = 20;
/// @dev Constant value to mask the upper bits of a signature that uses a packed `vs` value to extract `s`
bytes32 constant UPPER_BIT_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev EIP-712 typehash used for validating signature based stored approvals
bytes32 constant UPDATE_APPROVAL_TYPEHASH =
keccak256("UpdateApprovalBySignature(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 approvalExpiration,uint256 sigDeadline,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit without additional data
bytes32 constant SINGLE_USE_PERMIT_TYPEHASH =
keccak256("PermitTransferFrom(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit with additional data
string constant SINGLE_USE_PERMIT_TRANSFER_ADVANCED_TYPEHASH_STUB =
"PermitTransferFromWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev EIP-712 typehash used for validating an order permit that updates storage as it fills
string constant PERMIT_ORDER_ADVANCED_TYPEHASH_STUB =
"PermitOrderWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 salt,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev Pausable flag for stored approval transfers of ERC721 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC721 = 1 << 0;
/// @dev Pausable flag for stored approval transfers of ERC1155 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC1155 = 1 << 1;
/// @dev Pausable flag for stored approval transfers of ERC20 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC20 = 1 << 2;
/// @dev Pausable flag for single use permit transfers of ERC721 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC721 = 1 << 3;
/// @dev Pausable flag for single use permit transfers of ERC1155 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC1155 = 1 << 4;
/// @dev Pausable flag for single use permit transfers of ERC20 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC20 = 1 << 5;
/// @dev Pausable flag for order fill transfers of ERC1155 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC1155 = 1 << 6;
/// @dev Pausable flag for order fill transfers of ERC20 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC20 = 1 << 7;@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^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.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
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.
*/
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 {
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) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/interfaces/IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^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].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@openzeppelin/contracts/token/ERC1155/ERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: address zero is not a valid owner");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `ids` and `amounts` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
@openzeppelin/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^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._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `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 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.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata 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.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(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 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 override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or 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(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @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) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @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(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being 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`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
@openzeppelin/contracts/token/common/ERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^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.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^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.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^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}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/math/SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contracts/BioCanvas.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@limitbreak/creator-token-standards/src/access/OwnableBasic.sol";
import "@limitbreak/creator-token-standards/src/erc1155c/ERC1155C.sol";
import "@limitbreak/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./Drifter.sol";
contract BioCanvas is ERC1155C, BasicRoyalties, OwnableBasic {
using Strings for uint256;
uint96 public constant ROYALTY_FEE_NUMERATOR = 500; // 5% royalty
uint256 public minted;
string public baseURI = "https://m.cyberbrokers.com/base/biocanvas/";
address public DRIFTER_ADDRESS;
address[] public BIO_CANVAS_MINTER_ADDRESSES;
modifier onlyBioCanvasMinters() {
bool isMinter = false;
for (uint256 i = 0; i < BIO_CANVAS_MINTER_ADDRESSES.length; i++) {
if (BIO_CANVAS_MINTER_ADDRESSES[i] == msg.sender) {
isMinter = true;
break;
}
}
require(isMinter, "Caller is not a BioCanvas minter");
_;
}
modifier onlyDrifterAddress() {
require(msg.sender == DRIFTER_ADDRESS, "Caller is not the Drifter contract");
_;
}
function name() public pure returns (string memory) {
return "Drifter BioCanvases";
}
function symbol() public pure returns (string memory) {
return "DRIFTERBIOCANVAS";
}
// Required to use ERC1155OpenZeppelin instead of ERC1155C due to a fuckup from LimitBreak
constructor(string memory uri_, address _royaltyReceiver) ERC1155OpenZeppelin(uri_) BasicRoyalties(_royaltyReceiver, ROYALTY_FEE_NUMERATOR) OwnableBasic() {
baseURI = uri_;
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function addBioCanvasMinter(address minterAddress) external onlyOwner {
require(minterAddress != address(0), "Invalid minter address");
// Make sure the minter address is not already in the array
for (uint256 i = 0; i < BIO_CANVAS_MINTER_ADDRESSES.length; i++) {
if (BIO_CANVAS_MINTER_ADDRESSES[i] == minterAddress) {
return;
}
}
BIO_CANVAS_MINTER_ADDRESSES.push(minterAddress);
}
function removeBioCanvasMinter(address minterAddress) external onlyOwner {
for (uint256 i = 0; i < BIO_CANVAS_MINTER_ADDRESSES.length; i++) {
if (BIO_CANVAS_MINTER_ADDRESSES[i] == minterAddress) {
BIO_CANVAS_MINTER_ADDRESSES[i] = BIO_CANVAS_MINTER_ADDRESSES[BIO_CANVAS_MINTER_ADDRESSES.length - 1];
BIO_CANVAS_MINTER_ADDRESSES.pop();
break;
}
}
}
function setDrifterAddress(address drifterAddress) external onlyOwner {
DRIFTER_ADDRESS = drifterAddress;
}
function mint(address to, uint256 tokenId, uint256 amount) external onlyBioCanvasMinters {
_mint(to, tokenId, amount, "");
minted += amount;
}
function convertToDrifter(uint256 id, uint256 value, address to) external onlyDrifterAddress returns (bool) {
// Require that the caller owns the BioCanvas token
require(balanceOf(to, id) >= value, "Caller does not own enough BioCanvas tokens");
_burn(to, id, value);
return true;
}
function totalSupply() public view returns (uint256) {
return minted;
}
function uri(uint256 tokenId) public view virtual override returns (string memory) {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155C, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
_setDefaultRoyalty(receiver, feeNumerator);
}
function setTokenRoyalty(address receiver, uint256 tokenId, uint96 feeNumerator) external onlyOwner {
_setTokenRoyalty(tokenId, receiver, feeNumerator);
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
contracts/DNACard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@limitbreak/creator-token-standards/src/access/OwnableBasic.sol";
import "@limitbreak/creator-token-standards/src/erc721c/ERC721C.sol";
import "@limitbreak/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DNACardReveal.sol";
import "./DNACardLib.sol";
contract DNACard is OwnableBasic, ERC721C, BasicRoyalties {
using Address for address;
using Strings for uint256;
uint96 public constant ROYALTY_FEE_NUMERATOR = 500; // 5% royalty
string public baseURI = "https://m.cyberbrokers.com/base/dnapack/";
// Mapping from token ID to its type (1-9)
mapping(uint256 => uint8) public cardSkins;
uint256 public constant SMALL_SUPPLY = 2707;
uint256 public constant MEDIUM_SUPPLY = 3907;
uint256 public constant LARGE_SUPPLY = 1163;
uint256 public smallMinted;
uint256 public mediumMinted;
uint256 public largeMinted;
uint256 public totalRevealed;
// Array-as-mapping from skin type (1-9) to its supply info
// small pack is 1 * 2707, medium pack is 3 * 1303, large pack is 5 * 233
uint256[] public cardSkinSupplies = [0, 2707, 1303, 1303, 1303, 233, 233, 233, 233, 233];
address[] public DNA_CARD_MINTER_ADDRESSES;
DNACardReveal public dnaCardRevealContract;
// Mapping to store the card type for each token ID
mapping(uint256 => DNACardLib.CardSize) public cardSizes;
// Mapping of ownership of revealed dna cards
mapping(uint256 => address) public revealedOwners;
event DNACardRevealed(uint256 indexed tokenId, uint256[] gearIds);
event DNACardHarvested(uint256 indexed tokenId, uint256[] harvestedGearIds);
modifier onlyDnaCardMinters() {
bool isMinter = false;
for (uint256 i = 0; i < DNA_CARD_MINTER_ADDRESSES.length; i++) {
if (DNA_CARD_MINTER_ADDRESSES[i] == msg.sender) {
isMinter = true;
break;
}
}
require(isMinter, "Caller is not a DNA Card minter");
_;
}
constructor(
address royaltyReceiver_,
string memory name_,
string memory symbol_
) ERC721OpenZeppelin(name_, symbol_) BasicRoyalties(royaltyReceiver_, ROYALTY_FEE_NUMERATOR) {}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721C, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
function addDnaCardMinter(address minterAddress) external onlyOwner {
require(minterAddress != address(0), "Invalid minter address");
// Make sure the minter address is not already in the array
for (uint256 i = 0; i < DNA_CARD_MINTER_ADDRESSES.length; i++) {
if (DNA_CARD_MINTER_ADDRESSES[i] == minterAddress) {
return;
}
}
DNA_CARD_MINTER_ADDRESSES.push(minterAddress);
}
function removeDnaCardMinter(address minterAddress) external onlyOwner {
for (uint256 i = 0; i < DNA_CARD_MINTER_ADDRESSES.length; i++) {
if (DNA_CARD_MINTER_ADDRESSES[i] == minterAddress) {
DNA_CARD_MINTER_ADDRESSES[i] = DNA_CARD_MINTER_ADDRESSES[DNA_CARD_MINTER_ADDRESSES.length - 1];
DNA_CARD_MINTER_ADDRESSES.pop();
break;
}
}
}
function setDnaCardRevealContract(address payable dnaCardRevealAddress) external onlyOwner {
require(dnaCardRevealAddress != address(0), "Invalid DNA Card Reveal contract address");
dnaCardRevealContract = DNACardReveal(dnaCardRevealAddress);
}
function reveal(uint256 tokenId) external {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
// Require that the token exists
require(_exists(tokenId), "Token does not exist");
// Require that the caller owns the token
require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is not owner nor approved");
// Require that the token is not already revealed
require(revealedOwners[tokenId] == address(0), "Token already revealed");
// Store the caller as the owner of the revealed DNA card
revealedOwners[tokenId] = _msgSender();
// Reveal the DNA card
uint256[] memory selectedGear = dnaCardRevealContract.reveal(_msgSender(), tokenId, getCardSize(tokenId), getCardSkin(tokenId));
// Burn the DNA card
_burn(tokenId);
totalRevealed++;
emit DNACardRevealed(tokenId, selectedGear);
}
function harvestReveal(uint256 tokenId, uint256[] calldata selectedGearIds) external {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
// Require that the token is revealed by the caller
require(revealedOwners[tokenId] != address(0), "DNA Card not revealed yet");
require(revealedOwners[tokenId] == _msgSender(), "Only revealed owner can harvest");
uint256[] memory harvestedGear = dnaCardRevealContract.harvestReveal(_msgSender(), tokenId, getCardSize(tokenId), selectedGearIds);
emit DNACardHarvested(tokenId, harvestedGear);
}
function getRevealedGear(uint256 tokenId) external view returns (uint256[] memory) {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
return dnaCardRevealContract.getRevealedGear(tokenId);
}
function getRemainingSelectionTime(uint256 tokenId) external view returns (uint256) {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
return dnaCardRevealContract.getRemainingSelectionTime(tokenId);
}
function isRevealed(uint256 tokenId) external view returns (bool) {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
return dnaCardRevealContract.isRevealed(tokenId);
}
function isHarvested(uint256 tokenId) external view returns (bool) {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
return dnaCardRevealContract.isHarvested(tokenId);
}
function SELECTION_TIME_LIMIT() external view returns (uint256) {
// Require that the DNA Card Reveal contract is set
require(address(dnaCardRevealContract) != address(0), "DNA Card Reveal contract not set");
return dnaCardRevealContract.SELECTION_TIME_LIMIT();
}
function _selectCardSkin(DNACardLib.CardSize cardSize) internal view returns (uint8) {
if (cardSize == DNACardLib.CardSize.SMALL) {
// Small pack - only type 1
require(cardSkinSupplies[1] > 0, "Small pack type depleted");
return 1;
} else if (cardSize == DNACardLib.CardSize.MEDIUM) {
// Medium pack - types 2-4
uint256 totalRemaining = 0;
for (uint8 i = 2; i <= 4; i++) {
totalRemaining += cardSkinSupplies[i];
}
require(totalRemaining > 0, "Medium pack types depleted");
// Generate random number
uint256 randomNum = uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao, msg.sender))) % totalRemaining;
// Select type based on weighted probabilities
uint256 cumulative = 0;
for (uint8 i = 2; i <= 4; i++) {
cumulative += cardSkinSupplies[i];
if (randomNum < cumulative) {
return i;
}
}
return 4; // Fallback to last type (shouldn't reach here)
} else {
// Large pack - types 5-9
uint256 totalRemaining = 0;
for (uint8 i = 5; i <= 9; i++) {
totalRemaining += cardSkinSupplies[i];
}
require(totalRemaining > 0, "Large pack types depleted");
// Generate random number
uint256 randomNum = uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao, msg.sender))) % totalRemaining;
// Select type based on weighted probabilities
uint256 cumulative = 0;
for (uint8 i = 5; i <= 9; i++) {
cumulative += cardSkinSupplies[i];
if (randomNum < cumulative) {
return i;
}
}
return 9; // Fallback to last type (shouldn't reach here)
}
}
function mint(address to, uint8 cardSize) external onlyDnaCardMinters returns (uint256) {
require(cardSize >= 0 && cardSize <= 2, "Invalid card type");
// Select token type based on weighted probabilities
uint8 cardSkin = _selectCardSkin(DNACardLib.CardSize(cardSize));
require(cardSkinSupplies[cardSkin] > 0, "Type supply depleted");
// Decrement the selected type's supply
cardSkinSupplies[cardSkin]--;
uint256 tokenId;
// Validate and update card size tracking, calculate tokenId
if (cardSize == 0) {
require(smallMinted < SMALL_SUPPLY, "Small card supply exceeded");
smallMinted++;
tokenId = smallMinted;
} else if (cardSize == 1) {
require(mediumMinted < MEDIUM_SUPPLY, "Medium card supply exceeded");
mediumMinted++;
tokenId = SMALL_SUPPLY + mediumMinted;
} else {
require(largeMinted < LARGE_SUPPLY, "Large card supply exceeded");
largeMinted++;
tokenId = SMALL_SUPPLY + MEDIUM_SUPPLY + largeMinted;
}
_mint(to, tokenId);
cardSizes[tokenId] = DNACardLib.CardSize(cardSize);
cardSkins[tokenId] = cardSkin;
return tokenId;
}
function totalSupply() public view returns (uint256) {
return smallMinted + mediumMinted + largeMinted - totalRevealed;
}
function getCardSize(uint256 tokenId) public view returns (DNACardLib.CardSize) {
return cardSizes[tokenId];
}
function getCardSkin(uint256 tokenId) public view returns (uint8) {
return cardSkins[tokenId];
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
baseURI = newBaseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
_setDefaultRoyalty(receiver, feeNumerator);
}
function setTokenRoyalty(address receiver, uint256 tokenId, uint96 feeNumerator) external onlyOwner {
_setTokenRoyalty(tokenId, receiver, feeNumerator);
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
contracts/DNACardLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library DNACardLib {
// Enum to represent DNA Card sizes
enum CardSize {
SMALL,
MEDIUM,
LARGE
}
}
contracts/DNACardReveal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@limitbreak/creator-token-standards/src/access/OwnableBasic.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DNACardLib.sol";
import "./GEAR.sol";
contract DNACardReveal is OwnableBasic {
using Address for address;
using Strings for uint256;
// Initial supply limits for each rarity
uint256 public constant COMMON_SUPPLY = 777;
uint256 public constant UNCOMMON_SUPPLY = 400;
uint256 public constant RARE_SUPPLY = 100;
uint256 public constant EPIC_SUPPLY = 50;
uint256 public constant LEGENDARY_SUPPLY = 28;
// Mapping to track remaining supply for each gear token ID
mapping(uint256 => uint256) public gearRemainingSupply;
address public DNA_CARD_ADDRESS;
GEAR public gearContract;
// Time limit for manual gear selection (20 minutes)
uint256 public constant SELECTION_TIME_LIMIT = 20 minutes;
uint256 public constant SELECTION_TIME_LIMIT_BUFFER = 5 minutes;
// Mapping to store reveal timestamps
mapping(uint256 => uint256) public revealTimestamps;
// Struct to track category requirements during reveal
struct CategoryTracker {
bool hasTopBodysuit;
bool hasPantsSkirt;
bool hasShoesBoots;
bool hasHair;
uint256 remainingItems;
}
// Mapping to store the card type for each token ID
mapping(uint256 => DNACardLib.CardSize) public cardTypes;
// Mapping to track if a token has been revealed
mapping(uint256 => bool) public isRevealed;
// Mapping to track if a token has been harvested
mapping(uint256 => bool) public isHarvested;
// Mapping to store revealed GEAR IDs for each DNA Card
mapping(uint256 => uint256[]) public revealedGear;
// Reveal configuration for different card sizes
struct RevealConfig {
uint256 legendaryCount;
uint256 epicOrRareCount;
uint256 uncommonCount;
uint256 commonCount;
uint256 totalGearCount;
}
// Harvest configuration for different card sizes
struct HarvestConfig {
uint256 legendaryCount;
uint256 rareOrEpicCount;
uint256 uncommonCount;
uint256 commonCount;
uint256 totalHarvestCount;
}
struct SelectionParams {
GEARMetadata.Rarity rarity;
address to;
uint256 tokenId;
uint256 nonce;
uint256[] alreadyRevealedGear;
CategoryTracker tracker;
}
struct ValidationParams {
uint256 candidate;
uint256[] alreadyRevealedGear;
bool needsForcedCategories;
string[] forcedCategories;
CategoryTracker tracker;
}
struct GearCounts {
uint256 legendaryCount;
uint256 epicCount;
uint256 rareCount;
uint256 uncommonCount;
uint256 commonCount;
}
// Mapping of card sizes to their reveal configurations
mapping(DNACardLib.CardSize => RevealConfig) public revealConfigs;
// Mapping of card sizes to their harvest configurations
mapping(DNACardLib.CardSize => HarvestConfig) public harvestConfigs;
function setGearContract(address payable gearContractAddress) external onlyOwner {
require(gearContractAddress != address(0), "Invalid gear contract address");
gearContract = GEAR(gearContractAddress);
}
function setDnaCardAddress(address dnaCardAddress) external onlyOwner {
require(dnaCardAddress != address(0), "Invalid DNA Card contract address");
DNA_CARD_ADDRESS = dnaCardAddress;
}
modifier onlyDnaCard() {
require(msg.sender == DNA_CARD_ADDRESS, "Caller is not the DNA Card contract");
_;
}
constructor(address payable gearContractAddress_) {
gearContract = GEAR(gearContractAddress_);
resetGearRemainingSupply();
// Initialize reveal configurations
revealConfigs[DNACardLib.CardSize.SMALL] = RevealConfig({
legendaryCount: 0,
epicOrRareCount: 1,
uncommonCount: 3,
commonCount: 6,
totalGearCount: 11 // 10 base + 1 skin
});
revealConfigs[DNACardLib.CardSize.MEDIUM] = RevealConfig({
legendaryCount: 0,
epicOrRareCount: 2,
uncommonCount: 8,
commonCount: 18,
totalGearCount: 29 // 28 base + 1 skin
});
revealConfigs[DNACardLib.CardSize.LARGE] = RevealConfig({
legendaryCount: 1,
epicOrRareCount: 3,
uncommonCount: 6,
commonCount: 10,
totalGearCount: 21 // 20 base + 1 skin
});
// Initialize harvest configurations
harvestConfigs[DNACardLib.CardSize.SMALL] = HarvestConfig({
legendaryCount: 0,
rareOrEpicCount: 1,
uncommonCount: 2,
commonCount: 4,
totalHarvestCount: 7
});
harvestConfigs[DNACardLib.CardSize.MEDIUM] = HarvestConfig({
legendaryCount: 0,
rareOrEpicCount: 1,
uncommonCount: 6,
commonCount: 12,
totalHarvestCount: 19
});
harvestConfigs[DNACardLib.CardSize.LARGE] = HarvestConfig({
legendaryCount: 1,
rareOrEpicCount: 1,
uncommonCount: 4,
commonCount: 6,
totalHarvestCount: 12
});
}
function resetGearRemainingSupply() public onlyOwner {
require(address(gearContract) != address(0), "Gear contract not set");
uint256[] memory commonGear = gearContract.getRarityNFTAssetIds(GEARMetadata.Rarity.COMMON);
uint256[] memory uncommonGear = gearContract.getRarityNFTAssetIds(GEARMetadata.Rarity.UNCOMMON);
uint256[] memory rareGear = gearContract.getRarityNFTAssetIds(GEARMetadata.Rarity.RARE);
uint256[] memory epicGear = gearContract.getRarityNFTAssetIds(GEARMetadata.Rarity.EPIC);
uint256[] memory legendaryGear = gearContract.getRarityNFTAssetIds(GEARMetadata.Rarity.LEGENDARY);
// Set initial supply for each gear token
for (uint256 i = 0; i < commonGear.length; i++) {
if (commonGear[i] != 0) {
gearRemainingSupply[commonGear[i]] = COMMON_SUPPLY;
}
}
for (uint256 i = 0; i < uncommonGear.length; i++) {
if (uncommonGear[i] != 0) {
gearRemainingSupply[uncommonGear[i]] = UNCOMMON_SUPPLY;
}
}
for (uint256 i = 0; i < rareGear.length; i++) {
if (rareGear[i] != 0) {
gearRemainingSupply[rareGear[i]] = RARE_SUPPLY;
}
}
for (uint256 i = 0; i < epicGear.length; i++) {
if (epicGear[i] != 0) {
gearRemainingSupply[epicGear[i]] = EPIC_SUPPLY;
}
}
for (uint256 i = 0; i < legendaryGear.length; i++) {
if (legendaryGear[i] != 0) {
gearRemainingSupply[legendaryGear[i]] = LEGENDARY_SUPPLY;
}
}
}
function overrideGearCategoryRemainingSupply(string memory category, uint256 remainingSupply) external onlyOwner {
require(address(gearContract) != address(0), "Gear contract not set");
require(remainingSupply > 0, "Remaining supply must be greater than 0");
uint256[] memory categoryGear = gearContract.getCategoryNFTAssetIds(category);
// Set initial supply for each gear token
for (uint256 i = 0; i < categoryGear.length; i++) {
if (categoryGear[i] != 0) {
gearRemainingSupply[categoryGear[i]] = remainingSupply;
}
}
}
function overrideGearRemainingSupply(uint256 tokenId, uint256 remainingSupply) external onlyOwner {
require(remainingSupply > 0, "Remaining supply must be greater than 0");
gearRemainingSupply[tokenId] = remainingSupply;
}
function reveal(address to, uint256 tokenId, DNACardLib.CardSize cardSize, uint8 cardSkin) public onlyDnaCard returns (uint256[] memory) {
require(address(gearContract) != address(0), "Gear contract not set");
require(!isRevealed[tokenId], "DNA Card already revealed");
RevealConfig memory config = revealConfigs[cardSize];
uint256[] memory selectedGear = new uint256[](config.totalGearCount);
uint256 selectedCount = 0;
uint256 nonce = 0;
// Store reveal timestamp
revealTimestamps[tokenId] = block.timestamp;
// Initialize category tracker in memory
CategoryTracker memory tracker = CategoryTracker({
hasTopBodysuit: false,
hasPantsSkirt: false,
hasShoesBoots: false,
hasHair: false,
remainingItems: config.totalGearCount - 1 // Exclude skin type
});
// Reveal Legendary (if applicable)
if (config.legendaryCount > 0) {
selectedGear[selectedCount++] = _selectGearByRarity(GEARMetadata.Rarity.LEGENDARY, to, tokenId, nonce++, selectedGear, tracker);
}
// Reveal Epic or Rare
for (uint256 i = 0; i < config.epicOrRareCount; i++) {
selectedGear[selectedCount++] = _selectGearByRarity(
_randomEpicRareRoll(tokenId, nonce++) ? GEARMetadata.Rarity.EPIC : GEARMetadata.Rarity.RARE,
to,
tokenId,
nonce++,
selectedGear,
tracker
);
}
// Reveal Uncommons
for (uint256 i = 0; i < config.uncommonCount; i++) {
selectedGear[selectedCount++] = _selectGearByRarity(GEARMetadata.Rarity.UNCOMMON, to, tokenId, nonce++, selectedGear, tracker);
}
// Reveal Commons
for (uint256 i = 0; i < config.commonCount; i++) {
selectedGear[selectedCount++] = _selectGearByRarity(GEARMetadata.Rarity.COMMON, to, tokenId, nonce++, selectedGear, tracker);
}
// Add skin type based on pack size
selectedGear[selectedCount++] = _selectSkinType(cardSkin);
// For all revealed gear, decrease the supply by 1, because it is now revealed and can be harvested
// If a piece of gear is not selected in the harvest, it will be available for selection again
for (uint256 i = 0; i < selectedGear.length; i++) {
gearRemainingSupply[selectedGear[i]]--;
}
revealedGear[tokenId] = selectedGear;
isRevealed[tokenId] = true;
return selectedGear;
}
function _selectGearByRarity(
GEARMetadata.Rarity rarity,
address to,
uint256 tokenId,
uint256 nonce,
uint256[] memory alreadyRevealedGear,
CategoryTracker memory tracker
) internal view returns (uint256) {
SelectionParams memory params = SelectionParams({
rarity: rarity,
to: to,
tokenId: tokenId,
nonce: nonce,
alreadyRevealedGear: alreadyRevealedGear,
tracker: tracker
});
return _performGearSelection(params);
}
function _performGearSelection(SelectionParams memory params) internal view returns (uint256) {
uint256[] memory rarityTokens = gearContract.getRarityNFTAssetIds(params.rarity);
require(rarityTokens.length > 0, "No tokens available for this rarity");
uint256 maxAttempts = 1000; // Prevent infinite loops
uint256 attempts = 0;
// Check if we need to force a specific category
string[] memory forcedCategories = _needsForcedCategories(params.tracker);
bool needsForcedCategories = forcedCategories.length > 0;
// Calculate total remaining supply for this rarity
uint256 totalRemaining = 0;
for (uint256 i = 0; i < rarityTokens.length; i++) {
if (rarityTokens[i] != 0) {
totalRemaining += gearRemainingSupply[rarityTokens[i]];
}
}
require(totalRemaining > 0, "No remaining supply for this rarity");
while (attempts < maxAttempts) {
// Generate random number based on total remaining supply
bytes32 randomHash = keccak256(abi.encodePacked(block.timestamp, block.prevrandao, params.to, params.tokenId, params.nonce, attempts));
uint256 randomNum = uint256(randomHash) % totalRemaining;
// Select gear based on weighted probabilities
uint256 cumulative = 0;
for (uint256 i = 0; i < rarityTokens.length; i++) {
uint256 candidate = rarityTokens[i];
if (candidate == 0) continue;
cumulative += gearRemainingSupply[candidate];
if (randomNum < cumulative) {
ValidationParams memory validationParams = ValidationParams({
candidate: candidate,
alreadyRevealedGear: params.alreadyRevealedGear,
needsForcedCategories: needsForcedCategories,
forcedCategories: forcedCategories,
tracker: params.tracker
});
if (_isValidCandidate(validationParams)) {
return candidate;
}
break;
}
}
attempts++;
}
revert("Could not find valid gear after maximum attempts");
}
function _isValidCandidate(ValidationParams memory params) internal view returns (bool) {
// Must be in DNA packs
if (!gearContract.isInDnaPacks(params.candidate)) {
return false;
}
// Check for duplicates
for (uint256 i = 0; i < params.alreadyRevealedGear.length; i++) {
if (params.candidate == params.alreadyRevealedGear[i]) {
return false;
}
}
string memory category = gearContract.getDrifterAssetCategory(params.candidate);
// If we need a forced category, only accept matching items
if (params.needsForcedCategories) {
// Check if the candidate's category matches any in the forced categories
if (_categoryMatches(category, params.forcedCategories)) {
_updateCategoryTracker(params.tracker, category);
return true;
}
} else {
// Normal selection process
_updateCategoryTracker(params.tracker, category);
return true;
}
return false;
}
function _packTypeToSkinType(uint8 packType) internal view returns (uint256) {
uint256[] memory skinTokens = gearContract.getCategoryNFTAssetIds("Skin Type");
require(skinTokens.length > 0, "No skin types available");
require(packType <= skinTokens.length, "Token type exceeds available skin types");
if (packType == 1) return gearContract.findAssetByName(skinTokens, "HaloShell");
if (packType == 2) return gearContract.findAssetByName(skinTokens, "Cherry Sugar");
if (packType == 3) return gearContract.findAssetByName(skinTokens, "Duskfallen");
if (packType == 4) return gearContract.findAssetByName(skinTokens, "Opaline");
if (packType == 5) return gearContract.findAssetByName(skinTokens, "Enigma Aura");
if (packType == 6) return gearContract.findAssetByName(skinTokens, "Topo Flow");
if (packType == 7) return gearContract.findAssetByName(skinTokens, "Thermaform");
if (packType == 8) return gearContract.findAssetByName(skinTokens, "Rosy Nova");
if (packType == 9) return gearContract.findAssetByName(skinTokens, "Alpha Alloy");
return 0;
}
function _selectSkinType(uint8 cardSkin) internal view returns (uint256) {
require(cardSkin > 0 && cardSkin <= 9, "Invalid token type");
// Get all skin type tokens
uint256 skinToken = _packTypeToSkinType(cardSkin);
require(skinToken != 0, "Invalid skin type");
return skinToken;
}
function _isSpecialCategory(string memory category) internal pure returns (bool) {
return _isSkinType(category);
}
function _isSkinType(string memory category) internal pure returns (bool) {
bytes32 categoryHash = keccak256(abi.encodePacked(category));
bytes32 skinTypeHash = keccak256(abi.encodePacked("Skin Type"));
return categoryHash == skinTypeHash;
}
function _updateCategoryTracker(CategoryTracker memory tracker, string memory category) internal pure {
if (_categoryMatches(category, _getRequiredCategory(0))) {
tracker.hasTopBodysuit = true;
} else if (_categoryMatches(category, _getRequiredCategory(1))) {
tracker.hasPantsSkirt = true;
} else if (_categoryMatches(category, _getRequiredCategory(2))) {
tracker.hasShoesBoots = true;
} else if (_categoryMatches(category, _getRequiredCategory(3))) {
tracker.hasHair = true;
}
if (tracker.remainingItems > 0) {
tracker.remainingItems--;
}
}
function _needsForcedCategories(CategoryTracker memory tracker) internal pure returns (string[] memory) {
// Only force categories in the last N items
uint256 FORCE_THRESHOLD = 4; // Adjust this value as needed
if (tracker.remainingItems > FORCE_THRESHOLD) {
return new string[](0);
}
// Check which categories are still missing
// Return the first category in the array for the required category index
if (!tracker.hasTopBodysuit) return _getRequiredCategory(0);
if (!tracker.hasPantsSkirt) return _getRequiredCategory(1);
if (!tracker.hasShoesBoots) return _getRequiredCategory(2);
if (!tracker.hasHair) return _getRequiredCategory(3);
return new string[](0);
}
function _randomEpicRareRoll(uint256 tokenId, uint256 nonce) internal pure returns (bool) {
// 20% chance to return true (epic), 80% chance to return false (rare)
return uint256(keccak256(abi.encodePacked(tokenId, nonce))) % 5 == 0;
}
// Split _autoSelectAndHarvestGear into multiple functions to avoid stack too deep
function _autoSelectAndHarvestGear(address to, uint256 tokenId, DNACardLib.CardSize cardSize) internal returns (uint256[] memory) {
(uint256[] memory selectedGear, uint256[] memory specialGear) = _selectGearForHarvest(tokenId, cardSize);
return _performHarvest(to, tokenId, selectedGear, specialGear);
}
function _selectGearForHarvest(uint256 tokenId, DNACardLib.CardSize cardSize) private view returns (uint256[] memory, uint256[] memory) {
HarvestConfig memory config = harvestConfigs[cardSize];
uint256[] memory availableGear = revealedGear[tokenId];
uint256[] memory selectedGear = new uint256[](config.totalHarvestCount);
uint256[] memory specialGear = new uint256[](1);
uint256 selectedCount;
uint256 specialCount;
// First pass: collect special gear and categorize non-special gear
uint256[] memory legendaryGear = new uint256[](availableGear.length);
uint256[] memory epicGear = new uint256[](availableGear.length);
uint256[] memory rareGear = new uint256[](availableGear.length);
uint256[] memory uncommonGear = new uint256[](availableGear.length);
uint256[] memory commonGear = new uint256[](availableGear.length);
GearCounts memory counts;
for (uint256 i = 0; i < availableGear.length; i++) {
uint256 gearId = availableGear[i];
string memory category = gearContract.getDrifterAssetCategory(gearId);
if (_isSpecialCategory(category) && !gearContract.isInDnaPacks(gearId)) {
specialGear[specialCount++] = gearId;
continue;
}
GEARMetadata.Rarity rarity = gearContract.getDrifterAssetRarity(gearId);
if (rarity == GEARMetadata.Rarity.LEGENDARY) {
legendaryGear[counts.legendaryCount++] = gearId;
} else if (rarity == GEARMetadata.Rarity.EPIC) {
epicGear[counts.epicCount++] = gearId;
} else if (rarity == GEARMetadata.Rarity.RARE) {
rareGear[counts.rareCount++] = gearId;
} else if (rarity == GEARMetadata.Rarity.UNCOMMON) {
uncommonGear[counts.uncommonCount++] = gearId;
} else if (rarity == GEARMetadata.Rarity.COMMON) {
commonGear[counts.commonCount++] = gearId;
}
}
// Add legendaries first
for (uint256 i = 0; i < config.legendaryCount && i < counts.legendaryCount; i++) {
selectedGear[selectedCount++] = legendaryGear[i];
}
// Add epics first, then rares if needed
uint256 epicRareNeeded = config.rareOrEpicCount;
uint256 epicsTaken = 0;
// Take epics first
for (uint256 i = 0; i < counts.epicCount && epicRareNeeded > 0; i++) {
selectedGear[selectedCount++] = epicGear[i];
epicsTaken++;
epicRareNeeded--;
}
// Only take rares if we still need more after epics
if (epicRareNeeded > 0) {
for (uint256 i = 0; i < counts.rareCount && epicRareNeeded > 0; i++) {
selectedGear[selectedCount++] = rareGear[i];
epicRareNeeded--;
}
}
// Add uncommons
for (uint256 i = 0; i < config.uncommonCount && i < counts.uncommonCount; i++) {
selectedGear[selectedCount++] = uncommonGear[i];
}
// Add commons
for (uint256 i = 0; i < config.commonCount && i < counts.commonCount; i++) {
selectedGear[selectedCount++] = commonGear[i];
}
return (selectedGear, specialGear);
}
function _performHarvest(address to, uint256 tokenId, uint256[] memory selectedGear, uint256[] memory specialGear) private returns (uint256[] memory) {
// Mint selected gear
for (uint256 i = 0; i < selectedGear.length; i++) {
if (selectedGear[i] != 0) {
gearContract.mint(to, selectedGear[i], 1);
if (gearRemainingSupply[selectedGear[i]] > 0) {
gearRemainingSupply[selectedGear[i]]--;
}
}
}
// Mint special gear
for (uint256 i = 0; i < specialGear.length; i++) {
if (specialGear[i] != 0) {
gearContract.mint(to, specialGear[i], 1);
}
}
// Create combined array for event
uint256 totalLength = selectedGear.length;
for (uint256 i = 0; i < specialGear.length; i++) {
if (specialGear[i] != 0) totalLength++;
}
uint256[] memory allGear = new uint256[](totalLength);
uint256 index = 0;
for (uint256 i = 0; i < selectedGear.length; i++) {
if (selectedGear[i] != 0) {
allGear[index++] = selectedGear[i];
}
}
for (uint256 i = 0; i < specialGear.length; i++) {
if (specialGear[i] != 0) {
allGear[index++] = specialGear[i];
}
}
isHarvested[tokenId] = true;
return allGear;
}
function getRevealedGear(uint256 tokenId) external view returns (uint256[] memory) {
require(isRevealed[tokenId], "DNA Card not revealed yet");
return revealedGear[tokenId];
}
function getRemainingSelectionTime(uint256 tokenId) external view returns (uint256) {
uint256 revealTime = revealTimestamps[tokenId];
if (revealTime == 0) return 0;
uint256 endTime = revealTime + SELECTION_TIME_LIMIT;
if (block.timestamp >= endTime) return 0;
return endTime - block.timestamp;
}
function _validateSelectedGear(
uint256[] calldata selectedGearIds,
uint256[] memory availableGear,
HarvestConfig memory config
) private view returns (uint256[] memory) {
require(selectedGearIds.length == config.totalHarvestCount, "Invalid number of selected gear");
uint256 selectedLegendary;
uint256 selectedRareOrEpic;
uint256 selectedUncommon;
uint256 selectedCommon;
// Verify all selected gear exists in revealed gear and count rarities
for (uint256 i = 0; i < selectedGearIds.length; i++) {
// Disallow choosing a non-DNA pack item as a gear
require(gearContract.isInDnaPacks(selectedGearIds[i]), "Cannot choose a non-DNA pack item as a gear");
bool found = false;
for (uint256 j = 0; j < availableGear.length; j++) {
if (selectedGearIds[i] == availableGear[j]) {
found = true;
GEARMetadata.Rarity rarity = gearContract.getDrifterAssetRarity(selectedGearIds[i]);
if (rarity == GEARMetadata.Rarity.LEGENDARY) {
selectedLegendary++;
} else if (rarity == GEARMetadata.Rarity.EPIC || rarity == GEARMetadata.Rarity.RARE) {
selectedRareOrEpic++;
} else if (rarity == GEARMetadata.Rarity.UNCOMMON) {
selectedUncommon++;
} else if (rarity == GEARMetadata.Rarity.COMMON) {
selectedCommon++;
}
break;
}
}
require(found, "Selected gear not in revealed set");
}
// Verify rarity counts
require(selectedLegendary == config.legendaryCount, "Invalid legendary count");
require(selectedRareOrEpic == config.rareOrEpicCount, "Invalid rare/epic count");
require(selectedUncommon == config.uncommonCount, "Invalid uncommon count");
require(selectedCommon == config.commonCount, "Invalid common count");
return selectedGearIds;
}
function _getSpecialGear(uint256[] memory availableGear) private view returns (uint256[] memory, uint256) {
uint256[] memory specialGear = new uint256[](1);
uint256 specialCount;
for (uint256 i = 0; i < availableGear.length; i++) {
string memory category = gearContract.getDrifterAssetCategory(availableGear[i]);
// Only include special gear that is not in DNA packs
if (_isSpecialCategory(category) && !gearContract.isInDnaPacks(availableGear[i])) {
specialGear[specialCount++] = availableGear[i];
}
}
return (specialGear, specialCount);
}
function _mintSelectedGear(
address to,
uint256[] memory selectedGear,
uint256[] memory specialGear,
uint256 specialCount
) private returns (uint256[] memory) {
uint256 totalGear = selectedGear.length + specialCount;
for (uint256 i = 0; i < selectedGear.length; i++) {
gearContract.mint(to, selectedGear[i], 1);
if (gearRemainingSupply[selectedGear[i]] > 0) {
gearRemainingSupply[selectedGear[i]]--;
}
}
for (uint256 i = 0; i < specialCount; i++) {
gearContract.mint(to, specialGear[i], 1);
}
// Create array for event emission
uint256[] memory allGear = new uint256[](totalGear);
for (uint256 i = 0; i < selectedGear.length; i++) {
allGear[i] = selectedGear[i];
}
for (uint256 i = 0; i < specialCount; i++) {
allGear[selectedGear.length + i] = specialGear[i];
}
return allGear;
}
function harvestReveal(
address to,
uint256 tokenId,
DNACardLib.CardSize cardSize,
uint256[] calldata selectedGearIds
) public onlyDnaCard returns (uint256[] memory) {
require(address(gearContract) != address(0), "Gear contract not set");
require(isRevealed[tokenId], "DNA Card not revealed yet");
require(!isHarvested[tokenId], "DNA Card already harvested");
uint256 revealTime = revealTimestamps[tokenId];
require(revealTime > 0, "Invalid reveal timestamp");
uint256[] memory availableGear = revealedGear[tokenId];
// For all revealed gear, increase the supply by 1
// This is because unselected gear should be available for selection again, and the supply will be reduced by 1 if it is selected
for (uint256 i = 0; i < availableGear.length; i++) {
gearRemainingSupply[availableGear[i]]++;
}
// If time limit has expired, auto-select gear
if (block.timestamp > revealTime + SELECTION_TIME_LIMIT + SELECTION_TIME_LIMIT_BUFFER) {
return _autoSelectAndHarvestGear(to, tokenId, cardSize);
}
HarvestConfig memory config = harvestConfigs[cardSize];
require(availableGear.length > 0, "No revealed gear found");
// Validate selected gear
uint256[] memory validatedGear = _validateSelectedGear(selectedGearIds, availableGear, config);
// Get special gear (skin type)
(uint256[] memory specialGear, uint256 specialCount) = _getSpecialGear(availableGear);
// Mint all gear and emit event
uint256[] memory allGear = _mintSelectedGear(to, validatedGear, specialGear, specialCount);
// Mark as harvested
isHarvested[tokenId] = true;
return allGear;
}
function _getRequiredCategory(uint256 index) internal pure returns (string[] memory) {
string[] memory categories;
if (index == 0) {
categories = new string[](6);
categories[0] = "Tops/Bodysuits";
categories[1] = "Bras";
categories[2] = "Jackets & Coats";
categories[3] = "Vests";
categories[4] = "Dresses";
categories[5] = "Jumpsuits";
} else if (index == 1) {
categories = new string[](5);
categories[0] = "Leggings";
categories[1] = "Leggings/Tights";
categories[2] = "Pants/Shorts";
categories[3] = "Skirts";
categories[4] = "Tights";
} else if (index == 2) {
categories = new string[](7);
categories[0] = "Boots";
categories[1] = "Flats";
categories[2] = "Heels";
categories[3] = "Sandals";
categories[4] = "Slippers";
categories[5] = "Sneakers";
categories[6] = "Formal";
} else if (index == 3) {
categories = new string[](5);
categories[0] = "Hair";
categories[1] = "Hats";
categories[2] = "Head Hovers";
categories[3] = "Headbands";
categories[4] = "Helmets";
} else {
revert("Invalid category index");
}
return categories;
}
// Helper to check if a category matches any in the list
function _categoryMatches(string memory category, string[] memory categories) internal pure returns (bool) {
for (uint256 i = 0; i < categories.length; i++) {
if (_compareStrings(category, categories[i])) {
return true;
}
}
return false;
}
function _compareStrings(string memory a, string memory b) internal pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
contracts/Drifter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@limitbreak/creator-token-standards/src/erc721c/ERC721C.sol";
import "@limitbreak/creator-token-standards/src/access/OwnableBasic.sol";
import "@limitbreak/creator-token-standards/src/programmable-royalties/BasicRoyalties.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./GEAR.sol";
import "./BioCanvas.sol";
import "./DrifterName.sol";
import "./DrifterEquip.sol";
contract Drifter is ERC721C, DrifterName, DrifterEquip, BasicRoyalties, OwnableBasic {
using Address for address;
using Strings for uint256;
uint96 public constant ROYALTY_FEE_NUMERATOR = 500; // 5% royalty
uint256 public latestTokenId = 0;
uint256 public totalSupply = 0;
string public baseURI = "https://m.cyberbrokers.com/base/drifter/";
BioCanvas public bioCanvasContract;
mapping(uint256 => uint256) public drifterAttributeCount;
mapping(uint256 => string[]) public drifterAttributeKeys;
mapping(uint256 => uint256[]) public drifterAttributeValues;
event DrifterCreated(
uint256 indexed drifterId,
uint256 bioCanvasId,
uint256[] assetIds,
uint256[] assetColors,
string[] attributeKeys,
uint256[] attributeValues,
string name
);
event DrifterEdited(uint256 indexed drifterId, uint256[] assetIds, uint256[] assetColors, string[] attributeKeys, uint256[] attributeValues, string name);
modifier onlyBioCanvas() {
require(msg.sender == address(bioCanvasContract), "Caller is not the bio canvas contract");
_;
}
modifier onlyTokenOwner(uint256 tokenId) {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
_;
}
constructor(
string memory name_,
string memory symbol_,
address payable bioCanvasAddress_,
address payable gearAddress_,
address payable royaltyReceiver_
) ERC721OpenZeppelin(name_, symbol_) DrifterName() DrifterEquip(gearAddress_) BasicRoyalties(royaltyReceiver_, ROYALTY_FEE_NUMERATOR) {
bioCanvasContract = BioCanvas(bioCanvasAddress_);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721C, ERC1155Receiver, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Creates a new Drifter from a BioCanvas and optionally equips GEAR
* @param bioCanvasId The ID of the BioCanvas token to convert
* @param assetIds Array of GEAR token IDs to equip (can be empty)
* @param assetColors Array of color indexes to update
* @param namePlacement The placement index for name generation
* @param expectedName The expected name to be generated
* @param _attributeKeys The keys of the attributes to update
* @param _attributeValues The values of the attributes to update
* @return The ID of the newly created Drifter
*/
function createDrifter(
uint256 bioCanvasId,
uint256[] calldata assetIds,
uint256[] calldata assetColors,
string[] calldata _attributeKeys,
uint256[] calldata _attributeValues,
uint256 namePlacement,
string calldata expectedName
) external payable returns (uint256) {
// Verify caller owns the BioCanvas
require(bioCanvasContract.balanceOf(_msgSender(), bioCanvasId) > 0, "Caller does not own the BioCanvas");
// Convert BioCanvas to Drifter
require(bioCanvasContract.convertToDrifter(bioCanvasId, 1, _msgSender()), "Failed to convert BioCanvas to Drifter");
// Mint the Drifter
uint256 drifterId = mint(_msgSender());
// Confirm the name rolled or set a custom name
if (namePlacement < 2 ** 255) {
_confirmRolledName(drifterId, namePlacement, expectedName, _msgSender());
} else {
setDrifterName(drifterId, expectedName);
}
// If GEAR was provided, store it as equipped
if (assetIds.length > 0) {
_equipGear(drifterId, assetIds, _msgSender());
}
if (assetColors.length > 0) {
_updateDrifterColors(drifterId, assetColors);
}
drifterAttributeCount[drifterId] = _attributeKeys.length;
drifterAttributeKeys[drifterId] = _attributeKeys;
drifterAttributeValues[drifterId] = _attributeValues;
emit DrifterCreated(drifterId, bioCanvasId, assetIds, assetColors, _attributeKeys, _attributeValues, expectedName);
return drifterId;
}
/**
* @dev Edits the equipped GEAR for an existing Drifter
* @param drifterId The ID of the Drifter to edit
* @param assetIds Array of GEAR token IDs to equip (can be empty to unequip all)
* @param assetColors Array of color indexes to update
* @param _attributeKeys The keys of the attributes to update
* @param _attributeValues The values of the attributes to update
*/
function editDrifterGear(
uint256 drifterId,
uint256[] calldata assetIds,
uint256[] calldata assetColors,
string[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external onlyTokenOwner(drifterId) {
// Update equipped GEAR
_equipGear(drifterId, assetIds, msg.sender);
if (assetColors.length > 0) {
_updateDrifterColors(drifterId, assetColors);
}
// Gender is set within the gear management UI, separate from the other attributes
_updateDrifterAttributes(drifterId, _attributeKeys, _attributeValues);
emit DrifterEdited(drifterId, assetIds, assetColors, drifterAttributeKeys[drifterId], drifterAttributeValues[drifterId], drifterNames[drifterId]);
}
function editDrifterAttributes(
uint256 drifterId,
string[] calldata _attributeKeys,
uint256[] calldata _attributeValues
) external onlyTokenOwner(drifterId) {
_updateDrifterAttributes(drifterId, _attributeKeys, _attributeValues);
emit DrifterEdited(
drifterId,
equippedGear[drifterId],
equippedGearColors[drifterId],
drifterAttributeKeys[drifterId],
drifterAttributeValues[drifterId],
drifterNames[drifterId]
);
}
function _updateDrifterAttributes(uint256 drifterId, string[] calldata _attributeKeys, uint256[] calldata _attributeValues) internal {
// For each provided key, see if the key exists in the drifterAttributeKeys array
// If it does, update the value at the corresponding index in the drifterAttributeValues array
// If it doesn't, add the key and value to the arrays
for (uint256 i = 0; i < _attributeKeys.length; i++) {
string memory key = _attributeKeys[i];
uint256 value = _attributeValues[i];
bool found = false;
for (uint256 j = 0; j < drifterAttributeKeys[drifterId].length; j++) {
if (keccak256(abi.encodePacked(drifterAttributeKeys[drifterId][j])) == keccak256(abi.encodePacked(key))) {
drifterAttributeValues[drifterId][j] = value;
found = true;
break;
}
}
if (!found) {
drifterAttributeCount[drifterId]++;
drifterAttributeKeys[drifterId].push(key);
drifterAttributeValues[drifterId].push(value);
}
}
}
/**
* @dev Wrapper function to confirm a rolled name for a Drifter
* @param drifterId The ID of the Drifter
* @param placement The placement index for name generation
* @param expectedName The expected generated name
*/
function confirmDrifterName(uint256 drifterId, uint256 placement, string calldata expectedName) external onlyTokenOwner(drifterId) {
_confirmRolledName(drifterId, placement, expectedName, _msgSender());
}
/**
* @dev Wrapper function to create a custom name for a Drifter
* @param drifterId The ID of the Drifter
* @param name The custom name to set
*/
function setDrifterName(uint256 drifterId, string calldata name) public payable onlyTokenOwner(drifterId) {
require(msg.value >= getNameCreationCost(name), "Insufficient payment");
_createName(drifterId, name);
}
function mint(address to) internal returns (uint256) {
_mint(to, ++latestTokenId);
totalSupply++;
return latestTokenId;
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
baseURI = newBaseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function setDrifterNamePrices(uint64[] memory ethPrices) external onlyOwner {
_setDrifterNamePrices(ethPrices);
}
// DrifterName admin functions exposed through Drifter with onlyOwner access control
function addNames(string[] memory newNames) external onlyOwner {
_addNames(newNames);
}
function addDisallowedNames(string[] memory newNames) external onlyOwner {
_addDisallowedNames(newNames);
}
function addRestrictedWords(string[] memory words) external onlyOwner {
_addRestrictedWords(words);
}
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
_setDefaultRoyalty(receiver, feeNumerator);
}
function setTokenRoyalty(address receiver, uint256 tokenId, uint96 feeNumerator) external onlyOwner {
_setTokenRoyalty(tokenId, receiver, feeNumerator);
}
/**
* @dev Admin function to set any name for a Drifter, bypassing restrictions
* @param drifterId The ID of the Drifter
* @param name The name to set
*/
function adminSetDrifterName(uint256 drifterId, string calldata name) external onlyOwner {
require(_exists(drifterId), "ERC721: operator query for nonexistent token");
require(!usedNames[_strToLower(name)], "Name already in use");
_setName(drifterId, name);
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
contracts/DrifterEquip.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "./GEAR.sol";
abstract contract DrifterEquip is ERC1155Holder {
GEAR public gearContract;
// Mapping to track equipped GEAR for each Drifter
mapping(uint256 => uint256[]) public equippedGear;
mapping(uint256 => uint256[]) public equippedGearColors;
constructor(address payable gearAddress_) {
gearContract = GEAR(gearAddress_);
}
/**
* @dev Gets all equipped GEAR for a Drifter
* @param drifterId The ID of the Drifter
* @return Array of equipped GEAR token IDs
*/
function getEquippedGear(uint256 drifterId) external view returns (uint256[] memory) {
return equippedGear[drifterId];
}
function getEquippedGearColors(uint256 drifterId) external view returns (uint256[] memory) {
return equippedGearColors[drifterId];
}
/**
* @dev Internal function to validate color assignments for a Drifter's gear
* @param drifterId The ID of the Drifter
* @param colorIndexes Array of color indexes
*/
function _updateDrifterColors(uint256 drifterId, uint256[] calldata colorIndexes) internal {
// Require that the colorIndexes array is the same length as the equippedGear array
uint256[] memory currentGear = equippedGear[drifterId];
require(colorIndexes.length == currentGear.length, "Color indexes array must be the same length as equipped gear array");
// Need to verify that all colors are valid color types
for (uint256 i = 0; i < colorIndexes.length; i++) {
uint256 colorIndex = colorIndexes[i];
// If this color index is 0, then it's a default color and we don't need to verify it
if (colorIndex == 0) continue;
// Verify it's a Color category
string memory category = gearContract.getDrifterAssetCategory(colorIndex);
require(keccak256(abi.encodePacked(category)) == keccak256(abi.encodePacked("Color")), "Asset must be of category Color");
}
// All checks passed, update the equipped gear colors
equippedGearColors[drifterId] = colorIndexes;
}
/**
* @dev Internal function to equip GEAR to a Drifter
* @param drifterId The ID of the Drifter
* @param gearIds Array of GEAR token IDs to equip
* @param owner The owner of the Drifter and GEAR
*/
function _equipGear(uint256 drifterId, uint256[] calldata gearIds, address owner) internal {
uint256[] memory oldGearIds = equippedGear[drifterId];
// Unequip GEAR that isn't in the new configuration
if (oldGearIds.length > 0) {
for (uint256 i = 0; i < oldGearIds.length; i++) {
// Skip Non-NFT gear
if (gearContract.isNonNFT(oldGearIds[i])) continue;
bool keepGear = false;
for (uint256 j = 0; j < gearIds.length; j++) {
if (oldGearIds[i] == gearIds[j]) {
keepGear = true;
break;
}
}
if (!keepGear) {
gearContract.safeTransferFrom(address(this), owner, oldGearIds[i], 1, "");
}
}
}
// Verify and transfer only new GEAR tokens
if (gearIds.length > 0) {
string[] memory usedCategories = new string[](gearIds.length);
uint256 categoryCount = 0;
for (uint256 i = 0; i < gearIds.length; i++) {
bool isAlreadyEquipped = false;
for (uint256 j = 0; j < oldGearIds.length; j++) {
if (gearIds[i] == oldGearIds[j]) {
isAlreadyEquipped = true;
string memory category = gearContract.getDrifterAssetCategory(gearIds[i]);
bool categoryExists = false;
for (uint256 k = 0; k < categoryCount; k++) {
if (keccak256(abi.encodePacked(usedCategories[k])) == keccak256(abi.encodePacked(category))) {
categoryExists = true;
break;
}
}
if (!categoryExists) {
usedCategories[categoryCount++] = category;
}
break;
}
}
if (!isAlreadyEquipped) {
if (!gearContract.isNonNFT(gearIds[i])) {
require(gearContract.balanceOf(owner, gearIds[i]) > 0, "Owner does not own all specified GEAR");
gearContract.safeTransferFrom(owner, address(this), gearIds[i], 1, "");
}
string memory category = gearContract.getDrifterAssetCategory(gearIds[i]);
// Require unique categories
bool categoryExists = false;
for (uint256 k = 0; k < categoryCount; k++) {
if (keccak256(abi.encodePacked(usedCategories[k])) == keccak256(abi.encodePacked(category))) {
categoryExists = true;
break;
}
}
require(!categoryExists, "Duplicate category not allowed");
usedCategories[categoryCount++] = category;
}
}
}
equippedGear[drifterId] = gearIds;
}
}
contracts/DrifterName.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
abstract contract DrifterName {
using Strings for uint256;
// Single array to store all name components
string[] public names;
// Mapping for disallowed names and array for restricted words
mapping(string => bool) public disallowedNames;
string[] public restrictedWords;
// Mapping to track used names
mapping(string => bool) public usedNames;
// Mapping to track drifter names
mapping(uint256 => string) public drifterNames;
// Drifter name prices
uint64[5] public drifterNamePricesETH = [0.1 ether, 0.05 ether, 0.02 ether, 0.01 ether, 0.002 ether];
event NameSet(uint256 indexed tokenId, string name);
function _setDrifterNamePrices(uint64[] memory ethPrices) internal {
require(ethPrices.length == 5, "Invalid number of ETH prices");
// Check prices are greater than 0
for (uint256 i = 0; i < 5; i++) {
require(ethPrices[i] > 0, "Invalid ETH price");
}
drifterNamePricesETH[0] = ethPrices[0];
drifterNamePricesETH[1] = ethPrices[1];
drifterNamePricesETH[2] = ethPrices[2];
drifterNamePricesETH[3] = ethPrices[3];
drifterNamePricesETH[4] = ethPrices[4];
}
// Function to calculate name creation cost based on length
function getNameCreationCost(string memory name) public view returns (uint256) {
uint256 length = bytes(name).length;
// Max length is 32 characters
require(length <= 32, "Name too long");
// Make sure name isn't already taken
require(!usedNames[_strToLower(name)], "Name already in use");
// Check for invalid names
require(!_isNameInvalid(name), "Name contains restricted word");
if (length <= 3) return drifterNamePricesETH[0];
if (length == 4) return drifterNamePricesETH[1];
if (length == 5) return drifterNamePricesETH[2];
if (length == 6) return drifterNamePricesETH[3];
return drifterNamePricesETH[4]; // 7 or more characters
}
// Admin functions to populate arrays
function _addNames(string[] memory newNames) internal {
for (uint256 i = 0; i < newNames.length; i++) {
if (bytes(newNames[i]).length > 0) {
names.push(newNames[i]);
}
}
}
function _addDisallowedNames(string[] memory newNames) internal {
for (uint256 i = 0; i < newNames.length; i++) {
if (bytes(newNames[i]).length > 0) {
string memory lowerName = _strToLower(newNames[i]);
disallowedNames[lowerName] = true;
}
}
}
function _addRestrictedWords(string[] memory words) internal {
for (uint256 i = 0; i < words.length; i++) {
if (bytes(words[i]).length > 0) {
string memory lowerWord = _strToLower(words[i]);
restrictedWords.push(lowerWord);
}
}
}
// Public function to generate a random name based on address and placement
function rollName(address sender, uint256 placement) public view returns (string memory) {
return _rollName(sender, placement);
}
// View function to generate a random name based on address and placement
function _rollName(address rollSender, uint256 placement) internal view returns (string memory) {
require(names.length > 0, "Name list not initialized");
// Cap the number of placements to 10,000, just roll over back to 0 if exceeded
placement = placement % 10000;
string memory generatedName;
uint256 seed = uint256(keccak256(abi.encodePacked(rollSender, placement, "seed")));
do {
// Generate first index
uint256 firstIndex = uint256(keccak256(abi.encodePacked(rollSender, placement, "first", seed))) % names.length;
// Generate second index and re-roll if it matches first
seed = uint256(keccak256(abi.encodePacked(rollSender, placement, "second", seed)));
uint256 secondIndex = seed % names.length;
while (secondIndex == firstIndex) {
seed = uint256(keccak256(abi.encodePacked(seed)));
secondIndex = seed % names.length;
}
// Determine if we should use three names (25% chance)
uint256 useThreeNames = uint256(keccak256(abi.encodePacked(rollSender, placement, "length", seed))) % 4;
if (useThreeNames == 0) {
// 25% chance for three names
// Generate third index and re-roll if it matches first or second
seed = uint256(keccak256(abi.encodePacked(rollSender, placement, "third", seed)));
uint256 thirdIndex = seed % names.length;
while (thirdIndex == firstIndex || thirdIndex == secondIndex) {
seed = uint256(keccak256(abi.encodePacked(seed)));
thirdIndex = seed % names.length;
}
generatedName = string(abi.encodePacked(names[firstIndex], " ", names[secondIndex], " ", names[thirdIndex]));
} else {
// 75% chance for two names
generatedName = string(abi.encodePacked(names[firstIndex], " ", names[secondIndex]));
}
seed = uint256(keccak256(abi.encodePacked(seed)));
} while (usedNames[_strToLower(generatedName)]);
return generatedName;
}
// Internal function to validate name characters
function _isValidNameFormat(string memory name) internal pure returns (bool) {
bytes memory nameBytes = bytes(name);
uint256 length = nameBytes.length;
// Check for leading/trailing spaces
if (nameBytes[0] == 0x20 || nameBytes[length - 1] == 0x20) {
return false;
}
// Track consecutive spaces
bool lastWasSpace = false;
for (uint256 i = 0; i < length; i++) {
bytes1 char = nameBytes[i];
// Check for consecutive spaces
if (char == 0x20) {
if (lastWasSpace) {
return false;
}
lastWasSpace = true;
continue;
}
lastWasSpace = false;
// Allow a-z
if (char >= 0x61 && char <= 0x7A) {
continue;
}
// Allow A-Z
if (char >= 0x41 && char <= 0x5A) {
continue;
}
// Allow 0-9
if (char >= 0x30 && char <= 0x39) {
continue;
}
// Allow hyphen
if (char == 0x2D) {
continue;
}
// Allow underscore
if (char == 0x5F) {
continue;
}
// Allow apostrophe
if (char == 0x27) {
continue;
}
// If we get here, we found an invalid character
return false;
}
return true;
}
// Internal function to confirm a rolled name
function _confirmRolledName(uint256 tokenId, uint256 placement, string memory expectedName, address rollSender) internal {
require(bytes(drifterNames[tokenId]).length == 0, "Name already set for this token");
string memory generatedName = _rollName(rollSender, placement);
require(keccak256(abi.encodePacked(generatedName)) == keccak256(abi.encodePacked(expectedName)), "Generated name does not match expected name");
require(!_isNameInvalid(expectedName), "Invalid name");
require(!usedNames[_strToLower(expectedName)], "Name already in use");
_setName(tokenId, expectedName);
}
// Internal function to create a custom name
function _createName(uint256 tokenId, string memory name) internal {
require(_isValidNameFormat(name), "Invalid name format");
require(!_isNameInvalid(name), "Invalid name");
require(!usedNames[_strToLower(name)], "Name already in use");
require(bytes(name).length <= 32, "Name too long");
_setName(tokenId, name);
}
// Internal function to check if a name is invalid
function _isNameInvalid(string memory name) internal view returns (bool) {
// Check against disallowed names
if (disallowedNames[_strToLower(name)]) {
return true;
}
// Check for restricted words (whole word matches only)
bytes memory nameBytes = bytes(name);
for (uint i = 0; i < restrictedWords.length; i++) {
bytes memory restrictedWord = bytes(restrictedWords[i]);
if (_containsWholeWord(nameBytes, restrictedWord)) {
return true;
}
}
return false;
}
// Helper function for case-insensitive character comparison
function _strToLower(string memory str) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(strBytes.length);
for (uint256 i = 0; i < strBytes.length; i++) {
result[i] = _toLower(strBytes[i]);
}
return string(result);
}
function _toLower(bytes1 char) internal pure returns (bytes1) {
// Convert uppercase A-Z to lowercase a-z
if (char >= 0x41 && char <= 0x5A) {
return bytes1(uint8(char) + 32);
}
return char;
}
// Helper function to check if a character is a word character (alphanumeric)
function _isWordChar(bytes1 char) internal pure returns (bool) {
return
(char >= 0x30 && char <= 0x39) || // 0-9
(char >= 0x41 && char <= 0x5A) || // A-Z
(char >= 0x61 && char <= 0x7A); // a-z
}
// Internal function to check if a string contains another string as a whole word (case-insensitive)
function _containsWholeWord(bytes memory text, bytes memory word) internal pure returns (bool) {
if (word.length == 0 || text.length < word.length) {
return false;
}
for (uint256 i = 0; i <= text.length - word.length; i++) {
// Check if the word matches at this position
bool wordMatches = true;
for (uint256 j = 0; j < word.length; j++) {
if (_toLower(text[i + j]) != _toLower(word[j])) {
wordMatches = false;
break;
}
}
if (wordMatches) {
// Check word boundaries
bool validStart = (i == 0) || !_isWordChar(text[i - 1]);
bool validEnd = (i + word.length >= text.length) || !_isWordChar(text[i + word.length]);
if (validStart && validEnd) {
return true;
}
}
}
return false;
}
// Internal function to set a name
function _setName(uint256 tokenId, string memory name) internal {
// If this Drifter already has a name, unset that name
if (bytes(drifterNames[tokenId]).length > 0) {
usedNames[_strToLower(drifterNames[tokenId])] = false;
}
drifterNames[tokenId] = name;
usedNames[_strToLower(name)] = true;
emit NameSet(tokenId, name);
}
// View function to get a drifter's name
function getName(uint256 tokenId) external view returns (string memory) {
string memory name = drifterNames[tokenId];
require(bytes(name).length > 0, "No name set for this token");
return name;
}
}
contracts/GEAR.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@limitbreak/creator-token-standards/src/erc1155c/ERC1155C.sol";
import "@limitbreak/creator-token-standards/src/access/OwnableBasic.sol";
import "./SplitRoyalties.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./Drifter.sol";
import "./GEARMetadata.sol";
contract GEAR is ERC1155C, SplitRoyalties, GEARMetadata, OwnableBasic {
using Strings for uint256;
uint96 private constant ROYALTY_FEE_NUMERATOR = 500; // 5% royalty
uint256 public minted;
string public baseURI;
address[] public GEAR_MINTER_ADDRESSES;
address public DRIFTER_ADDRESS;
// Mapping of Token ID to number minted
mapping(uint256 => uint256) public tokenMintCount;
modifier onlyGearMinters() {
bool isMinter = false;
for (uint256 i = 0; i < GEAR_MINTER_ADDRESSES.length; i++) {
if (GEAR_MINTER_ADDRESSES[i] == msg.sender) {
isMinter = true;
break;
}
}
require(isMinter, "Caller is not a Gear minter");
_;
}
constructor(string memory _baseURI, address _royaltyReceiver) ERC1155OpenZeppelin(_baseURI) SplitRoyalties(_royaltyReceiver, ROYALTY_FEE_NUMERATOR) {
baseURI = _baseURI;
}
function name() public pure returns (string memory) {
return "Drifter G.E.A.R.";
}
function symbol() public pure returns (string memory) {
return "DRIFTERGEAR";
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function addGearMinter(address minterAddress) external onlyOwner {
require(minterAddress != address(0), "Invalid minter address");
// Make sure the minter address is not already in the array
for (uint256 i = 0; i < GEAR_MINTER_ADDRESSES.length; i++) {
if (GEAR_MINTER_ADDRESSES[i] == minterAddress) {
return;
}
}
GEAR_MINTER_ADDRESSES.push(minterAddress);
}
function removeGearMinter(address minterAddress) external onlyOwner {
for (uint256 i = 0; i < GEAR_MINTER_ADDRESSES.length; i++) {
if (GEAR_MINTER_ADDRESSES[i] == minterAddress) {
GEAR_MINTER_ADDRESSES[i] = GEAR_MINTER_ADDRESSES[GEAR_MINTER_ADDRESSES.length - 1];
GEAR_MINTER_ADDRESSES.pop();
break;
}
}
}
function setDrifterAddress(address drifterAddress) external onlyOwner {
DRIFTER_ADDRESS = drifterAddress;
}
function mint(address to, uint256 tokenId, uint256 amount) external onlyGearMinters {
_mint(to, tokenId, amount, "");
minted += amount;
tokenMintCount[tokenId] += amount;
}
/**
* @notice Sets split royalty information for a specific token ID
* @param tokenId The token ID to set royalties for
* @param recipients Array of addresses to share royalties equally
*/
function setTokenSplitRoyalty(uint256 tokenId, address[] memory recipients) external onlyOwner {
setTokenRoyalty(tokenId, ROYALTY_FEE_NUMERATOR, recipients);
}
/**
* @notice Sets split royalty information for multiple token IDs
* @param tokenIds Array of token IDs to set royalties for
* @param recipients Array of addresses to share royalties equally
*/
function setTokenSplitRoyaltyBatch(uint256[] memory tokenIds, address[] memory recipients) external onlyOwner {
setTokenRoyaltyBatch(tokenIds, ROYALTY_FEE_NUMERATOR, recipients);
}
function totalSupply() public view returns (uint256) {
return minted;
}
function uri(uint256 tokenId) public view virtual override returns (string memory) {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
// Always approve the Drifter contract
if (operator == DRIFTER_ADDRESS) {
return true;
}
return super.isApprovedForAll(account, operator);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155C, SplitRoyalties) returns (bool) {
return super.supportsInterface(interfaceId);
}
// =========================================================================
// GEARMetadata public-facing functions
// =========================================================================
/**
* @notice Check if an asset ID is a non-NFT asset
* @param assetId The asset ID to check
* @return Whether the asset ID is a non-NFT asset
*/
function isNonNFTAsset(uint256 assetId) public pure returns (bool) {
return isNonNFT(assetId);
}
/**
* @notice Get the total number of assets (NFTs + non-NFTs)
* @return The total number of assets
*/
function getTotalAssets() public view returns (uint256) {
return totalAssets;
}
/**
* @notice Get the total number of NFT assets
* @return The total number of NFT assets
*/
function getTotalNFTAssets() public view returns (uint256) {
return totalNFTAssets;
}
/**
* @notice Create a category batch
* @param _categories Array of category names to create
*/
function createCategoryBatch(string[] memory _categories) external onlyOwner {
_createCategoryBatch(_categories);
}
/**
* @notice Create a category
* @param category The category name to create
*/
function createCategory(string memory category) external onlyOwner {
_createCategory(category);
}
/**
* @notice Create a drifter asset batch
* @param assetIds Array of asset IDs to create
* @param keys Array of keys for each asset
* @param names Array of names for each asset
* @param _categories Array of categories for each asset
* @param genders Array of genders for each asset
* @param rarities Array of rarities for each asset
* @param inDnaCardPacks Array of whether each asset is in a DNA card pack
*/
function createDrifterAssetBatch(
uint256[] memory assetIds,
string[] memory keys,
string[] memory names,
string[] memory _categories,
string[] memory genders,
Rarity[] memory rarities,
bool[] memory inDnaCardPacks
) external onlyOwner {
_createDrifterAssetBatch(assetIds, keys, names, _categories, genders, rarities, inDnaCardPacks);
}
/**
* @notice Create a drifter asset
* @param assetId The asset ID to create
* @param key The key for the asset
* @param _name The name for the asset
* @param category The category for the asset
* @param gender The gender for the asset
* @param rarity The rarity for the asset
* @param inDnaCardPack Whether the asset is in a DNA card pack
*/
function createDrifterAsset(
uint256 assetId,
string memory key,
string memory _name,
string memory category,
string memory gender,
Rarity rarity,
bool inDnaCardPack
) external onlyOwner {
_createDrifterAsset(assetId, key, _name, category, gender, rarity, inDnaCardPack);
}
/**
* @notice Edit a drifter asset
* @param assetId The asset ID to edit
* @param key The new key for the asset
* @param _name The new name for the asset
* @param category The new category for the asset
* @param gender The new gender for the asset
* @param rarity The new rarity for the asset
* @param inDnaCardPack Whether the asset is in a DNA card pack
*/
function editDrifterAsset(
uint256 assetId,
string memory key,
string memory _name,
string memory category,
string memory gender,
Rarity rarity,
bool inDnaCardPack
) external onlyOwner {
_editDrifterAsset(assetId, key, _name, category, gender, rarity, inDnaCardPack);
}
/**
* @notice Get a category by index
* @param index The index of the category to get
* @return The category name at the index
*/
function getCategory(uint256 index) external view returns (string memory) {
return getCategoryByIndex(index);
}
/**
* @notice Get the category of an asset
* @param assetId The asset ID to get the category for
* @return The category of the asset
*/
function getAssetCategory(uint256 assetId) external view returns (string memory) {
return getDrifterAssetCategory(assetId);
}
/**
* @notice Get the rarity of an asset
* @param assetId The asset ID to get the rarity for
* @return The rarity of the asset
*/
function getAssetRarity(uint256 assetId) external view returns (Rarity) {
return getDrifterAssetRarity(assetId);
}
// Reject direct ETH transfers
receive() external payable {
revert("Direct ETH transfers not allowed");
}
}
contracts/GEARMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
abstract contract GEARMetadata {
// There is a split between Asset ID and Asset ID:
// Asset ID guarantees an NFT, mintable and transferable
// Asset ID is inclusive of all Asset IDs, but also includes non-NFT assets
uint256 public constant NON_NFT_BIT = 1 << 24; // 2^24 = 16777216
// All non-NFT assets are above the NON_NFT_BIT
// Mapping of Asset ID (Asset ID + Non NFT Assets) to Drifter Asset Info
mapping(uint256 => DrifterAssetInfo) public assetInfo;
// Rarities
enum Rarity {
COMMON,
UNCOMMON,
RARE,
EPIC,
LEGENDARY,
MYTHIC
}
// Array to store all category names
string[] public categories;
// Struct of Drifter Asset Info
struct DrifterAssetInfo {
string key;
string name;
string category;
string gender;
Rarity rarity;
bool inDnaCardPack;
}
// Mapping of rarity to array of asset IDs
mapping(Rarity => uint256[]) public rarityAssetIds;
// Mapping of rarity to array of NFT asset IDs
mapping(Rarity => uint256[]) public rarityNFTAssetIds;
// Mapping of category to array of asset IDs
mapping(string => uint256[]) public categoryAssetIds;
// Mapping of category to array of NFT asset IDs
mapping(string => uint256[]) public categoryNFTAssetIds;
// Current total number of assets (NFTs + non-NFTs)
uint256 public totalAssets;
// Current total number of NFT assets
uint256 public totalNFTAssets;
function isNonNFT(uint256 assetId) public pure returns (bool) {
return assetId & NON_NFT_BIT > 0;
}
// Create a category batch
function _createCategoryBatch(string[] memory _categories) internal {
for (uint256 i = 0; i < _categories.length; i++) {
_createCategory(_categories[i]);
}
}
function _createCategory(string memory category) internal {
// Require valid name
require(bytes(category).length > 0, "Category cannot be empty");
// Require that the category does not start or end with a space
// This is to prevent accidental creation of categories with spaces
require(bytes(category)[0] != " ", "Category cannot start with a space");
require(bytes(category)[bytes(category).length - 1] != " ", "Category cannot end with a space");
// Require unique name
for (uint256 i = 0; i < categories.length; i++) {
if (keccak256(abi.encodePacked(categories[i])) == keccak256(abi.encodePacked(category))) {
revert("Category already exists");
}
}
categories.push(category);
}
// Create a drifter asset batch
function _createDrifterAssetBatch(
uint256[] memory assetIds,
string[] memory keys,
string[] memory names,
string[] memory _categories,
string[] memory genders,
Rarity[] memory rarities,
bool[] memory inDnaCardPacks
) internal {
require(
assetIds.length == keys.length &&
assetIds.length == names.length &&
assetIds.length == _categories.length &&
assetIds.length == genders.length &&
assetIds.length == rarities.length &&
assetIds.length == inDnaCardPacks.length,
"Invalid array lengths"
);
for (uint256 i = 0; i < assetIds.length; i++) {
_createDrifterAsset(assetIds[i], keys[i], names[i], _categories[i], genders[i], rarities[i], inDnaCardPacks[i]);
}
}
function _createDrifterAsset(
uint256 assetId,
string memory key,
string memory name,
string memory category,
string memory gender,
Rarity rarity,
bool inDnaCardPack
) internal {
// Disallow overwriting existing drifter asset
require(bytes(assetInfo[assetId].key).length == 0, "Drifter asset already exists for this asset ID");
// Set drifter asset info
internalEditDrifterAsset(assetId, key, name, category, gender, rarity, inDnaCardPack);
// Add the asset ID to the rarity
internalAddAssetIdToRarity(assetId, rarity);
// Add the asset ID to the category
internalAddAssetIdToCategory(assetId, category);
// If the asset ID is an NFT, add it to the total number of NFT assets
if (!isNonNFT(assetId)) {
totalNFTAssets++;
}
// Increment total number of assets
totalAssets++;
}
function _editDrifterAsset(
uint256 assetId,
string memory key,
string memory name,
string memory category,
string memory gender,
Rarity rarity,
bool inDnaCardPack
) internal {
// Require that the drifter asset exists
require(bytes(assetInfo[assetId].key).length > 0, "Drifter asset does not exist for this asset ID");
// If the rarity has changed, remove the asset ID from the old rarity and add it to the new rarity
bool changedRarity = false;
if (assetInfo[assetId].rarity != rarity) {
changedRarity = true;
}
string memory oldCategory = assetInfo[assetId].category;
Rarity oldRarity = assetInfo[assetId].rarity;
// Update drifter asset info
internalEditDrifterAsset(assetId, key, name, category, gender, rarity, inDnaCardPack);
// If the rarity has changed, remove the asset ID from the old rarity and add it to the new rarity
if (changedRarity) {
internalRemoveAssetIdFromRarity(assetId, oldRarity);
internalAddAssetIdToRarity(assetId, rarity);
}
// If the category has changed, remove the asset ID from the old category and add it to the new category
if (keccak256(abi.encodePacked(oldCategory)) != keccak256(abi.encodePacked(category)) && bytes(oldCategory).length > 0) {
internalRemoveAssetIdFromCategory(assetId, oldCategory);
internalAddAssetIdToCategory(assetId, category);
}
}
function internalEditDrifterAsset(
uint256 assetId,
string memory key,
string memory name,
string memory category,
string memory gender,
Rarity rarity,
bool inDnaCardPack
) internal {
// Require valid name
require(bytes(name).length > 0, "Name cannot be empty");
// Require valid category
require(bytes(category).length > 0, "Category cannot be empty");
// Require that the category exists
bool categoryExists = false;
for (uint256 i = 0; i < categories.length; i++) {
if (keccak256(abi.encodePacked(categories[i])) == keccak256(abi.encodePacked(category))) {
categoryExists = true;
}
}
require(categoryExists, "Category does not exist");
// Require valid rarity if it is an NFT
require(rarity >= Rarity.COMMON && rarity <= Rarity.MYTHIC, "Invalid rarity");
// Set drifter asset info to mapping
assetInfo[assetId] = DrifterAssetInfo(key, name, category, gender, rarity, inDnaCardPack);
}
function internalAddAssetIdToCategory(uint256 assetId, string memory category) internal {
categoryAssetIds[category].push(assetId);
// If the asset ID is an NFT, add it to the total number of NFT assets
if (!isNonNFT(assetId)) {
categoryNFTAssetIds[category].push(assetId);
}
}
function internalAddAssetIdToRarity(uint256 assetId, Rarity rarity) internal {
rarityAssetIds[rarity].push(assetId);
// If the asset ID is an NFT, add it to the total number of NFT assets
if (!isNonNFT(assetId)) {
rarityNFTAssetIds[rarity].push(assetId);
}
}
function findItemInArray(uint256[] memory array, uint256 item) internal pure returns (bool found, uint256 index) {
// Find the index of the item
for (uint256 i = 0; i < array.length; i++) {
if (array[i] == item) {
index = i;
found = true;
break;
}
}
return (found, index);
}
function findAssetByName(uint256[] memory assetIds, string memory name) public view returns (uint256 assetId) {
// Find the asset ID with the matching name
for (uint256 i = 0; i < assetIds.length; i++) {
if (keccak256(abi.encodePacked(assetInfo[assetIds[i]].name)) == keccak256(abi.encodePacked(name))) {
return assetIds[i];
}
}
return 0;
}
function isInDnaPacks(uint256 assetId) public view returns (bool) {
return assetInfo[assetId].inDnaCardPack;
}
function internalRemoveAssetIdFromCategory(uint256 assetId, string memory category) internal {
// Find the index of the asset ID
(bool found, uint256 index) = findItemInArray(categoryAssetIds[category], assetId);
// Require that the asset ID was found
require(found, "Asset ID not found in category");
// Replace the asset ID with the last asset ID
categoryAssetIds[category][index] = categoryAssetIds[category][categoryAssetIds[category].length - 1];
// Remove the last asset ID
categoryAssetIds[category].pop();
// Perform the same operation for the NFT asset IDs if this is an NFT
if (!isNonNFT(assetId)) {
// Find the index of the asset ID
(bool _found, uint256 _index) = findItemInArray(categoryNFTAssetIds[category], assetId);
// Require that the asset ID was found
require(_found, "Asset ID not found in category NFT asset IDs");
// Replace the asset ID with the last asset ID
categoryNFTAssetIds[category][_index] = categoryNFTAssetIds[category][categoryNFTAssetIds[category].length - 1];
// Remove the last asset ID
categoryNFTAssetIds[category].pop();
}
}
function internalRemoveAssetIdFromRarity(uint256 assetId, Rarity rarity) internal {
// Find the index of the asset ID
(bool found, uint256 index) = findItemInArray(rarityAssetIds[rarity], assetId);
// Require that the asset ID was found
require(found, "Asset ID not found in rarity");
// Replace the asset ID with the last asset ID
rarityAssetIds[rarity][index] = rarityAssetIds[rarity][rarityAssetIds[rarity].length - 1];
// Remove the last asset ID
rarityAssetIds[rarity].pop();
// Perform the same operation for the NFT asset IDs
if (!isNonNFT(assetId)) {
// Find the index of the asset ID
(bool _found, uint256 _index) = findItemInArray(rarityNFTAssetIds[rarity], assetId);
// Require that the asset ID was found
require(_found, "Asset ID not found in rarity NFT asset IDs");
// Replace the asset ID with the last asset ID
rarityNFTAssetIds[rarity][_index] = rarityNFTAssetIds[rarity][rarityNFTAssetIds[rarity].length - 1];
// Remove the last asset ID
rarityNFTAssetIds[rarity].pop();
}
}
// Internal getters
function getRarityAssetIds(Rarity rarity) public view returns (uint256[] memory) {
return rarityAssetIds[rarity];
}
function getRarityNFTAssetIds(Rarity rarity) public view returns (uint256[] memory) {
return rarityNFTAssetIds[rarity];
}
function getCategoryAssetIds(string memory category) public view returns (uint256[] memory) {
return categoryAssetIds[category];
}
function getCategoryNFTAssetIds(string memory category) public view returns (uint256[] memory) {
return categoryNFTAssetIds[category];
}
function getCategoryAssetIdsForRarity(string memory category, Rarity rarity) public view returns (uint256[] memory) {
uint256[] memory _categoryAssetIds = new uint256[](categoryAssetIds[category].length);
uint256 index = 0;
for (uint256 i = 0; i < categoryAssetIds[category].length; i++) {
if (assetInfo[categoryAssetIds[category][i]].rarity == rarity) {
_categoryAssetIds[index] = categoryAssetIds[category][i];
index++;
}
}
// Resize the array to the actual number of asset IDs
assembly {
mstore(_categoryAssetIds, index)
}
return _categoryAssetIds;
}
function getCategoryNFTAssetIdsForRarity(string memory category, Rarity rarity) public view returns (uint256[] memory) {
uint256[] memory _categoryNFTAssetIds = new uint256[](categoryNFTAssetIds[category].length);
uint256 index = 0;
for (uint256 i = 0; i < categoryNFTAssetIds[category].length; i++) {
if (assetInfo[categoryNFTAssetIds[category][i]].rarity == rarity) {
_categoryNFTAssetIds[index] = categoryNFTAssetIds[category][i];
index++;
}
}
// Resize the array to the actual number of asset IDs
assembly {
mstore(_categoryNFTAssetIds, index)
}
return _categoryNFTAssetIds;
}
function getCategoryCount() public view returns (uint256) {
return categories.length;
}
function getCategoryByIndex(uint256 index) public view returns (string memory) {
require(index < categories.length, "Index out of bounds");
return categories[index];
}
function getDrifterAssetCategory(uint256 assetId) public view returns (string memory) {
return assetInfo[assetId].category;
}
function getDrifterAssetRarity(uint256 assetId) public view returns (Rarity) {
return assetInfo[assetId].rarity;
}
}
contracts/SplitRoyalties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @title SplitRoyalties
* @author Custom implementation for Drifters GEAR
* @notice A contract that implements ERC2981 royalty standard with support for split royalties per token ID
*/
abstract contract SplitRoyalties is IERC2981, ERC165 {
// Constants
uint256 public constant FEE_DENOMINATOR = 10_000;
// Default royalty information
address private _defaultRoyaltyReceiver;
uint96 private _defaultRoyaltyFeeNumerator;
// Per-token royalty information
struct TokenRoyaltyInfo {
uint96 feeNumerator;
address[] recipients;
bool initialized;
}
// Mapping from token ID to royalty information
mapping(uint256 => TokenRoyaltyInfo) private _tokenRoyalties;
// Events
event DefaultRoyaltySet(address receiver, uint96 feeNumerator);
event TokenRoyaltySet(uint256 tokenId, uint96 feeNumerator, address[] recipients);
event TokenRoyaltyRecipientsUpdated(uint256 tokenId, address[] recipients);
// Errors
error SplitRoyalties__RoyaltyFeeWillExceedSalePrice();
error SplitRoyalties__InvalidRoyaltyReceiver();
error SplitRoyalties__NoRecipientsProvided();
error SplitRoyalties__TokenRoyaltyNotInitialized();
constructor(address defaultRoyaltyReceiver, uint96 defaultRoyaltyFeeNumerator) {
_setDefaultRoyalty(defaultRoyaltyReceiver, defaultRoyaltyFeeNumerator);
}
/**
* @notice Sets the default royalty information
* @param receiver Address to receive royalties
* @param feeNumerator Fee numerator (out of FEE_DENOMINATOR)
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal {
if (feeNumerator > FEE_DENOMINATOR) {
revert SplitRoyalties__RoyaltyFeeWillExceedSalePrice();
}
if (receiver == address(0)) {
revert SplitRoyalties__InvalidRoyaltyReceiver();
}
_defaultRoyaltyReceiver = receiver;
_defaultRoyaltyFeeNumerator = feeNumerator;
emit DefaultRoyaltySet(receiver, feeNumerator);
}
/**
* @notice Sets royalty information for a specific token ID with multiple recipients
* @param tokenId Token ID to set royalty for
* @param feeNumerator Fee numerator (out of FEE_DENOMINATOR)
* @param recipients Array of addresses to receive equal shares of royalties
*/
function _setTokenRoyalty(uint256 tokenId, uint96 feeNumerator, address[] memory recipients) internal {
if (feeNumerator > FEE_DENOMINATOR) {
revert SplitRoyalties__RoyaltyFeeWillExceedSalePrice();
}
if (recipients.length == 0) {
revert SplitRoyalties__NoRecipientsProvided();
}
// Validate recipients
for (uint256 i = 0; i < recipients.length; i++) {
if (recipients[i] == address(0)) {
revert SplitRoyalties__InvalidRoyaltyReceiver();
}
}
_tokenRoyalties[tokenId] = TokenRoyaltyInfo({feeNumerator: feeNumerator, recipients: recipients, initialized: true});
emit TokenRoyaltySet(tokenId, feeNumerator, recipients);
}
/**
* @notice Returns royalty information for a token
* @param tokenId Token ID to get royalty info for
* @param salePrice Sale price of the token
* @return receiver Address to receive royalties
* @return royaltyAmount Amount of royalty to be paid
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
if (info.initialized) {
// If this token has specific royalty info, calculate based on that
uint256 royaltyFee = (salePrice * info.feeNumerator) / FEE_DENOMINATOR;
// For the ERC2981 interface, we return the first recipient as the receiver
// The actual distribution happens through other methods
return (info.recipients.length > 0 ? info.recipients[0] : _defaultRoyaltyReceiver, royaltyFee);
} else {
// Otherwise use default royalty info
return (_defaultRoyaltyReceiver, (salePrice * _defaultRoyaltyFeeNumerator) / FEE_DENOMINATOR);
}
}
/**
* @notice Calculates the royalty amount per recipient for a specific token and sale price
* @param tokenId Token ID
* @param salePrice Sale price of the token
* @return recipients Array of recipient addresses
* @return amounts Array of royalty amounts corresponding to each recipient
*/
function calculateRoyaltyPerRecipient(uint256 tokenId, uint256 salePrice) public view returns (address[] memory recipients, uint256[] memory amounts) {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
if (info.initialized && info.recipients.length > 0) {
recipients = info.recipients;
amounts = new uint256[](recipients.length);
uint256 totalRoyalty = (salePrice * info.feeNumerator) / FEE_DENOMINATOR;
uint256 sharePerRecipient = totalRoyalty / recipients.length;
for (uint256 i = 0; i < recipients.length; i++) {
amounts[i] = sharePerRecipient;
}
} else {
recipients = new address[](1);
amounts = new uint256[](1);
recipients[0] = _defaultRoyaltyReceiver;
amounts[0] = (salePrice * _defaultRoyaltyFeeNumerator) / FEE_DENOMINATOR;
}
return (recipients, amounts);
}
/**
* @notice Sets the default royalty information (admin only)
* @param receiver Address to receive royalties
* @param feeNumerator Fee numerator (out of FEE_DENOMINATOR)
*/
function setDefaultRoyalty(address receiver, uint96 feeNumerator) internal {
_setDefaultRoyalty(receiver, feeNumerator);
}
/**
* @notice Sets royalty information for a specific token ID with multiple recipients (admin only)
* @param tokenId Token ID to set royalty for
* @param feeNumerator Fee numerator (out of FEE_DENOMINATOR)
* @param recipients Array of addresses to receive equal shares of royalties
*/
function setTokenRoyalty(uint256 tokenId, uint96 feeNumerator, address[] memory recipients) internal {
_setTokenRoyalty(tokenId, feeNumerator, recipients);
}
/**
* @notice Sets royalty information for multiple token IDs with the same recipients
* @param tokenIds Array of token IDs
* @param feeNumerator Fee numerator (out of FEE_DENOMINATOR)
* @param recipients Array of recipient addresses
*/
function setTokenRoyaltyBatch(uint256[] memory tokenIds, uint96 feeNumerator, address[] memory recipients) internal {
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenRoyalty(tokenIds[i], feeNumerator, recipients);
}
}
/**
* @notice Updates the recipients for a specific token ID (admin only)
* @param tokenId Token ID to update
* @param recipients New array of recipient addresses
*/
function updateTokenRoyaltyRecipients(uint256 tokenId, address[] memory recipients) internal {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
if (!info.initialized) {
revert SplitRoyalties__TokenRoyaltyNotInitialized();
}
if (recipients.length == 0) {
revert SplitRoyalties__NoRecipientsProvided();
}
// Validate recipients
for (uint256 i = 0; i < recipients.length; i++) {
if (recipients[i] == address(0)) {
revert SplitRoyalties__InvalidRoyaltyReceiver();
}
}
info.recipients = recipients;
emit TokenRoyaltyRecipientsUpdated(tokenId, recipients);
}
/**
* @notice Adds a recipient to a token's royalty recipients list
* @param tokenId Token ID to update
* @param recipient New recipient address to add
*/
function addTokenRoyaltyRecipient(uint256 tokenId, address recipient) internal {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
if (!info.initialized) {
revert SplitRoyalties__TokenRoyaltyNotInitialized();
}
if (recipient == address(0)) {
revert SplitRoyalties__InvalidRoyaltyReceiver();
}
// Check if recipient already exists
for (uint256 i = 0; i < info.recipients.length; i++) {
if (info.recipients[i] == recipient) {
return; // Recipient already exists, do nothing
}
}
// Add the new recipient
info.recipients.push(recipient);
emit TokenRoyaltyRecipientsUpdated(tokenId, info.recipients);
}
/**
* @notice Removes a recipient from a token's royalty recipients list
* @param tokenId Token ID to update
* @param recipient Recipient address to remove
*/
function removeTokenRoyaltyRecipient(uint256 tokenId, address recipient) internal {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
if (!info.initialized) {
revert SplitRoyalties__TokenRoyaltyNotInitialized();
}
if (info.recipients.length <= 1) {
revert SplitRoyalties__NoRecipientsProvided();
}
// Find and remove the recipient
bool found = false;
for (uint256 i = 0; i < info.recipients.length; i++) {
if (info.recipients[i] == recipient) {
// Replace with the last element and pop
info.recipients[i] = info.recipients[info.recipients.length - 1];
info.recipients.pop();
found = true;
break;
}
}
if (found) {
emit TokenRoyaltyRecipientsUpdated(tokenId, info.recipients);
}
}
/**
* @notice Resets a token's royalty to use the default royalty
* @param tokenId Token ID to reset
*/
function resetTokenRoyalty(uint256 tokenId) internal {
delete _tokenRoyalties[tokenId];
}
/**
* @notice Resets multiple tokens' royalties to use the default royalty
* @param tokenIds Array of token IDs to reset
*/
function resetTokenRoyaltyBatch(uint256[] memory tokenIds) internal {
for (uint256 i = 0; i < tokenIds.length; i++) {
delete _tokenRoyalties[tokenIds[i]];
}
}
/**
* @notice Get the default royalty information
* @return receiver Address that receives royalties
* @return feeNumerator Fee numerator (out of FEE_DENOMINATOR)
*/
function getDefaultRoyaltyInfo() external view returns (address receiver, uint256 feeNumerator) {
return (_defaultRoyaltyReceiver, _defaultRoyaltyFeeNumerator);
}
/**
* @notice Get the royalty information for a specific token ID
* @param tokenId Token ID to query
* @return feeNumerator Fee numerator (out of FEE_DENOMINATOR)
* @return recipients Array of recipient addresses
* @return initialized Whether the token royalty has been initialized
*/
function getTokenRoyaltyInfo(uint256 tokenId) external view returns (uint256 feeNumerator, address[] memory recipients, bool initialized) {
TokenRoyaltyInfo storage info = _tokenRoyalties[tokenId];
return (info.feeNumerator, info.recipients, info.initialized);
}
/**
* @notice Indicates whether the contract implements the specified interface
* @param interfaceId Interface identifier
* @return bool True if the contract implements the interface
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
}
Compiler settingsShow
{
"viaIR": true,
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.