Verified contractExactGPL-3.0
PrideModule
Address0x0475b2f06a04d1a361b06558d853c84aa043dcd8
- Balance
0 ETH
- Transactions
98
- Compiler
solc 0.8.12
- Same code
Only this contract
Details
- Compiler
- solc 0.8.12+commit.f00d7308
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- GPL-3.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 14,889,221
- Creation transaction
- 0x4783db87c4…729f643109
34 files
- contracts/PrideModule.solmain12.13 KB
- @0xdievardump/niftyforge/contracts/INiftyForge721.sol7.51 KB
- @0xdievardump/niftyforge/contracts/Modules/INFModule.sol792 B
- @0xdievardump/niftyforge/contracts/Modules/INFModuleTokenURI.sol208 B
- @0xdievardump/niftyforge/contracts/Modules/INFModuleWithRoyalties.sol654 B
- @0xdievardump/niftyforge/contracts/Modules/NFBaseModule.sol1.67 KB
- @0xdievardump/niftyforge/contracts/NFT/ERC721/IERC721WithMutableURI.sol273 B
- @0xdievardump/niftyforge/contracts/NFT/ERC721/IERC721WithRoyalties.sol489 B
- @0xdievardump/niftyforge/contracts/NFT/IERC721Full.sol5.67 KB
- @0xdievardump/niftyforge/contracts/NFT/Royalties/ERC2981/IERC2981Royalties.sol747 B
- @0xdievardump/niftyforge/contracts/NFT/Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol417 B
- @0xdievardump/niftyforge/contracts/NFT/Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol618 B
- @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol4.77 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol864 B
- @openzeppelin/contracts/access/Ownable.sol2.46 KB
- @openzeppelin/contracts/security/Pausable.sol2.23 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.66 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC721/ERC721.sol13.62 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.74 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol964 B
- @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol761 B
- @openzeppelin/contracts/utils/Address.sol7.91 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.03 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- @openzeppelin/contracts/utils/structs/EnumerableSet.sol12.18 KB
- contracts/NiftyPrideAuctionHouse.sol10.5 KB
- contracts/Renderers/IRenderer.sol228 B
- contracts/interfaces/IAuctionHouse.sol1.74 KB
- contracts/interfaces/IBokkyPooBahsDateTimeContract.sol376 B
- contracts/interfaces/IWETH.sol244 B
- contracts/utils/Base64.sol3.45 KB
contracts/PrideModule.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {Strings} from '@openzeppelin/contracts/utils/Strings.sol';
import {INFModule, NFBaseModule, ERC165, IERC165} from '@0xdievardump/niftyforge/contracts/Modules/NFBaseModule.sol';
import {INFModuleTokenURI} from '@0xdievardump/niftyforge/contracts/Modules/INFModuleTokenURI.sol';
import {INFModuleWithRoyalties} from '@0xdievardump/niftyforge/contracts/Modules/INFModuleWithRoyalties.sol';
import {INiftyForge721} from '@0xdievardump/niftyforge/contracts/INiftyForge721.sol';
import {IBokkyPooBahsDateTimeContract} from './interfaces/IBokkyPooBahsDateTimeContract.sol';
import {NiftyPrideAuctionHouse} from './NiftyPrideAuctionHouse.sol';
import {IRenderer} from './Renderers/IRenderer.sol';
import {Base64} from './utils/Base64.sol';
contract PrideModule is
NFBaseModule,
INFModuleTokenURI,
INFModuleWithRoyalties,
NiftyPrideAuctionHouse
{
using EnumerableSet for EnumerableSet.AddressSet;
using Strings for uint256;
error InvalidParameter();
error RendererExists();
error UnknownRenderer();
error TooLate();
error InvalidDate();
error NotAuthorized();
struct Renderer {
address creator; // the renderer creator
uint32 royalties; // the renderer royalties
uint32 remainingUse; // how many times this renderer can be used
}
struct TokenMeta {
address renderer; // the renderer for this token;
uint96 creation;
bytes32 seed; // the seed for this token
}
mapping(address => Renderer) public renderers;
mapping(uint256 => TokenMeta) public tokensMeta;
EnumerableSet.AddressSet internal _availableRenderers;
EnumerableSet.AddressSet internal _beneficiaries;
uint256 beneficiaryIndex;
// The ERC721 token contract
address public nftContract;
constructor(address weth_) NFBaseModule('') NiftyPrideAuctionHouse(weth_) {}
////////////////////////////////////////////////////
///// Module //
////////////////////////////////////////////////////
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (nftContract == address(0)) {
nftContract = msg.sender;
return true;
}
// only allows attachment if nftContract if not set
return false;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(INFModuleTokenURI).interfaceId ||
interfaceId == type(INFModuleWithRoyalties).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(address, uint256 tokenId)
public
view
override
returns (address, uint256)
{
TokenMeta memory tokenMeta = tokensMeta[tokenId];
Renderer memory renderer = renderers[tokenMeta.renderer];
return (renderer.creator, uint256(renderer.royalties));
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
TokenMeta memory tokenMeta = tokensMeta[tokenId];
(string memory imageURI, string memory animationURI) = IRenderer(
tokenMeta.renderer
).render(tokenMeta.seed);
return
Base64.toB64JSON(
abi.encodePacked(
'{"name":"Pride | ',
_getDate(tokenMeta.creation),
'","description":"',
IRenderer(tokenMeta.renderer).description(),
'","image":"',
imageURI,
'"',
(
bytes(animationURI).length > 0
? abi.encodePacked(
',"animation_url":"',
animationURI,
'"'
)
: bytes('')
),
'}'
)
);
}
////////////////////////////////////////////////////
///// Getters //
////////////////////////////////////////////////////
function getAvailableRenderers()
external
view
returns (Renderer[] memory availableRenderers)
{
uint256 length = _availableRenderers.length();
availableRenderers = new Renderer[](length);
for (uint256 i; i < length; i++) {
availableRenderers[i] = renderers[_availableRenderers.at(i)];
}
}
////////////////////////////////////////////////////
///// Setters //
////////////////////////////////////////////////////
/// @notice allows a renderer creator to change where the renderer points (for Royalties purpose mainly)
/// @param renderer the renderer to edit
/// @param creator the new creator address
function setRendererCreator(address renderer, address creator) external {
if (msg.sender != renderers[renderer].creator) {
revert NotAuthorized();
}
renderers[renderer].creator = creator;
}
////////////////////////////////////////////////////
///// Misc //
////////////////////////////////////////////////////
function onERC721Received(
address operator,
address,
uint256,
bytes memory
) public view returns (bytes4) {
// if not our nftContract and not a mint
if (msg.sender != nftContract || operator != address(this)) {
revert NotAuthorized();
}
return this.onERC721Received.selector;
}
////////////////////////////////////////////////////
///// Owner //
////////////////////////////////////////////////////
/// @notice allows owner to start the first auction which is a bit special.
function startFirst() external onlyOwner {
uint256 tokenId = _mintNext();
if (tokenId != 1) revert TooLate();
// forcing the first auction timestamp at June 1st 3PM UTC because I started this project late late on
// June 1st 2022 and I am not sure I can deploy before June 2nd
uint256 startTime = 1654095600;
uint256 endTime = startTime + duration;
tokensMeta[tokenId].creation = uint96(startTime);
auction = Auction({
tokenId: tokenId,
amount: 0,
startTime: startTime,
endTime: endTime,
bidder: payable(0),
settled: false
});
emit AuctionCreated(tokenId, startTime, endTime);
_unpause();
}
/// @notice allows owner to add a new renderer contract
function addRenderer(
address renderer,
address creator,
uint32 royalties,
uint32 times
) public onlyOwner {
if (times == 0) revert InvalidParameter();
if (creator == address(0)) revert InvalidParameter();
if (renderers[renderer].creator != address(0)) revert RendererExists();
renderers[renderer] = Renderer(creator, royalties, times);
_availableRenderers.add(renderer);
}
/// @notice allows owner to remove a contract from the available renderers
function removeAvailableRenderer(address renderer) external onlyOwner {
if (!_availableRenderers.remove(renderer)) revert UnknownRenderer();
}
/// @notice adds `beneficiary` to the list of beneficiaries
/// @param beneficiary the new beneficiary
function addBeneficiary(address beneficiary) public onlyOwner {
if (beneficiary == address(0)) revert InvalidParameter();
if (!_beneficiaries.add(beneficiary)) revert InvalidParameter();
}
/// @notice removes `beneficiary` from the list of beneficiaries
/// @param beneficiary the beneficiary to remove
function removeBeneficiary(address beneficiary) public onlyOwner {
if (!_beneficiaries.remove(beneficiary)) revert InvalidParameter();
}
////////////////////////////////////////////////////
///// Internals //
////////////////////////////////////////////////////
function _createAuction() internal override {
(uint256 year, uint256 month, ) = _getYearMonthDay(block.timestamp);
// only June 2022 for this contract.
if (year != 2022 || month != 6) {
revert InvalidDate();
}
super._createAuction();
}
/// @dev internal function to allow transfer to revenue recipient(s)
function _transferToRecipients(uint256 tokenId, uint256 amount)
internal
virtual
override
{
uint256 creatorShare = (amount * 10) / 100;
// transfer 10% to the creator of the Renderer linked the the NFT
_safeTransferETHWithFallback(
renderers[tokensMeta[tokenId].renderer].creator,
creatorShare
);
// transfer what's left to the next "beneficiary" in the list of all beneficiaries
_safeTransferETHWithFallback(_nextBeneficiary(), amount - creatorShare);
}
function _mintNext() internal override returns (uint256) {
uint256 tokenId = INiftyForge721(nftContract).mint(address(this));
bytes32 seed = keccak256(
abi.encodePacked(
msg.sender,
block.timestamp,
block.difficulty,
tokenId
)
);
address renderer = _availableRenderers.at(
uint256(seed) % _availableRenderers.length()
);
// decrement the remaining use for this renderer
if (--renderers[renderer].remainingUse == 0) {
// and remove this renderer from the list of available renderers if 0
_availableRenderers.remove(renderer);
}
tokensMeta[tokenId] = TokenMeta({
renderer: renderer,
creation: uint96(block.timestamp),
seed: seed
});
return tokenId;
}
function _getRegistry() internal view override returns (address) {
return nftContract;
}
function _getDate(uint256 timestamp) internal view returns (string memory) {
(uint256 year, uint256 month, uint256 day) = _getYearMonthDay(
timestamp
);
return
string(
abi.encodePacked(
year.toString(),
'/',
month.toString(),
'/',
day.toString()
)
);
}
function _getYearMonthDay(uint256 timestamp)
internal
view
returns (
uint256 year,
uint256 month,
uint256 day
)
{
address bokky;
if (block.chainid == 1) {
bokky = address(0x23d23d8F243e57d0b924bff3A3191078Af325101);
} else if (block.chainid == 4) {
bokky = address(0x047C6386C30E785F7a8fd536945410802a605395);
}
if (address(0) != bokky) {
(year, month, day, , , ) = IBokkyPooBahsDateTimeContract(bokky)
.timestampToDateTime(timestamp);
} else {
// force 2022-06 for chainid not 1 or 4
year = 2022;
month = 6;
}
}
function _nextBeneficiary() internal returns (address) {
uint256 length = _beneficiaries.length();
uint256 beneficiaryIndex_ = beneficiaryIndex;
address beneficiary = _beneficiaries.at(beneficiaryIndex_ % length);
beneficiaryIndex = (beneficiaryIndex_ + 1) % length;
return beneficiary;
}
}
@0xdievardump/niftyforge/contracts/INiftyForge721.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './NFT/IERC721Full.sol';
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
/// @notice Interface to interact with a NiftyFroge721 on a network
interface INiftyForge721 is IERC721Full {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice this is the constructor of the contract, called at the time of creation
/// Although it uses what are called upgradeable contracts, this is only to
/// be able to make deployment cheap using a Proxy but NiftyForge contracts
/// ARE NOT UPGRADEABLE => the proxy used is not an upgradeable proxy, the implementation is immutable
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param baseURI_ the contract baseURI (if there is) - can be empty ""
/// @param owner_ Address to whom transfer ownership
/// @param modulesInit_ modules to add / enable directly at creation
/// @param contractRoyaltiesRecipient the recipient, if the contract has "contract wide royalties"
/// @param contractRoyaltiesValue the value, modules to add / enable directly at creation
function initialize(
string memory name_,
string memory symbol_,
string memory contractURI_,
string memory baseURI_,
address owner_,
ModuleInit[] memory modulesInit_,
address contractRoyaltiesRecipient,
uint256 contractRoyaltiesValue
) external;
/// @notice getter for the version of the implementation
/// @return the current implementation version following the scheme 0x[erc][type][version]
/// erc: 00 => ERC721 | 01 => ERC1155
/// type: 00 => full | 01 => slim
/// version: 00, 01, 02, 03...
function version() external view returns (bytes3);
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Allows to set a maximum number of mint possible
function setMaxSupply(uint256 maxSupply_) external;
/// @notice Mint next token to `to`
/// @param to address of recipient
/// @return tokenId the tokenId
function mint(address to) external returns (uint256 tokenId);
/// @notice Mint next token to `to` and then transfers to `transferTo`
/// @param to address of first recipient
/// @param transferTo address to transfer token to
/// @return tokenId the tokenId
function mint(address to, address transferTo)
external
returns (uint256 tokenId);
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return startId the first id
/// @return endId the last id
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256 startId, uint256 endId);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external;
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice allows to force the collection to start ids at 0
function startAtZero() external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
@0xdievardump/niftyforge/contracts/Modules/INFModule.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface INFModule is IERC165 {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
@0xdievardump/niftyforge/contracts/Modules/INFModuleTokenURI.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface INFModuleTokenURI {
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
@0xdievardump/niftyforge/contracts/Modules/INFModuleWithRoyalties.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface INFModuleWithRoyalties {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
@0xdievardump/niftyforge/contracts/Modules/NFBaseModule.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './INFModule.sol';
/// @title NFBaseModule
/// @author Simon Fremaux (@dievardump)
contract NFBaseModule is INFModule, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet internal _attached;
event NewContractURI(string contractURI);
string private _contractURI;
modifier onlyAttached(address registry) {
require(_attached.contains(registry), '!NOT_ATTACHED!');
_;
}
constructor(string memory contractURI_) {
_setContractURI(contractURI_);
}
/// @inheritdoc INFModule
function contractURI()
external
view
virtual
override
returns (string memory)
{
return _contractURI;
}
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (_attached.add(msg.sender)) {
return true;
}
revert('!ALREADY_ATTACHED!');
}
/// @notice this contract doesn't really care if it's enabled or not
/// since trying to mint on a contract where it's not enabled will fail
/// @inheritdoc INFModule
function onEnable() external virtual override returns (bool) {
return true;
}
/// @inheritdoc INFModule
function onDisable() external virtual override {}
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
}
@0xdievardump/niftyforge/contracts/NFT/ERC721/IERC721WithMutableURI.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @dev This is the interface for NFT extension mutableURI
/// @author Simon Fremaux (@dievardump)
interface IERC721WithMutableURI {
function mutableURI(uint256 tokenId) external view returns (string memory);
}
@0xdievardump/niftyforge/contracts/NFT/ERC721/IERC721WithRoyalties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '../Royalties/ERC2981/IERC2981Royalties.sol';
import '../Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol';
import '../Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol';
/// @dev This is a contract used for royalties on various platforms
/// @author Simon Fremaux (@dievardump)
interface IERC721WithRoyalties is
IERC2981Royalties,
IRaribleSecondarySales,
IFoundationSecondarySales
{
}
@0xdievardump/niftyforge/contracts/NFT/IERC721Full.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol';
import './ERC721/IERC721WithRoyalties.sol';
import './ERC721/IERC721WithMutableURI.sol';
/// @title ERC721Full
/// @dev This contains all the different overrides needed on
/// ERC721 / URIStorage / Royalties
/// This contract does not use ERC721enumerable because Enumerable adds quite some
/// gas to minting costs and I am trying to make this cheap for creators.
/// Also, since all NiftyForge contracts will be fully indexed in TheGraph it will easily
/// Be possible to get tokenIds of an owner off-chain, before passing them to a contract
/// which can verify ownership at the processing time
/// @author Simon Fremaux (@dievardump)
interface IERC721Full is
IERC721Upgradeable,
IERC721WithRoyalties,
IERC721WithMutableURI
{
function baseURI() external view returns (string memory);
function contractURI() external view returns (string memory);
/// @notice This is a generic function that allows this contract's owner to withdraw
/// any balance / ERC20 / ERC721 / ERC1155 it can have
/// this contract has no payable nor receive function so it should not get any nativ token
/// but this could save some ERC20, 721 or 1155
/// @param token the token to withdraw from. address(0) means native chain token
/// @param amount the amount to withdraw if native token, erc20 or erc1155 - must be 0 for ERC721
/// @param tokenId the tokenId to withdraw for ERC1155 and ERC721
function withdraw(
address token,
uint256 amount,
uint256 tokenId
) external;
/// @notice Helper to know if an address can do the action an Editor can
/// @param account the address to check
function canEdit(address account) external view returns (bool);
/// @notice Helper to know if an address can do the action a Minter can
/// @param account the address to check
function canMint(address account) external view returns (bool);
/// @notice Helper to know if an address is editor
/// @param account the address to check
function isEditor(address account) external view returns (bool);
/// @notice Helper to know if an address is minter
/// @param account the address to check
function isMinter(address account) external view returns (bool);
/// @notice Allows to get approved using a permit and transfer in the same call
/// @dev this supposes that the permit is for msg.sender
/// @param from current owner
/// @param to recipient
/// @param tokenId the token id
/// @param _data optional data to add
/// @param deadline the deadline for the permit to be used
/// @param signature of permit
function safeTransferFromWithPermit(
address from,
address to,
uint256 tokenId,
bytes memory _data,
uint256 deadline,
bytes memory signature
) external;
/// @notice Set the base token URI
/// @dev only an editor can do that (account or module)
/// @param baseURI_ the new base token uri used in tokenURI()
function setBaseURI(string memory baseURI_) external;
/// @notice Set the base mutable meta URI for tokens
/// @param baseMutableURI_ the new base for mutable meta uri used in mutableURI()
function setBaseMutableURI(string memory baseMutableURI_) external;
/// @notice Set the mutable URI for a token
/// @dev Mutable URI work like tokenURI
/// -> if there is a baseMutableURI and a mutableURI, concat baseMutableURI + mutableURI
/// -> else if there is only mutableURI, return mutableURI
//. -> else if there is only baseMutableURI, concat baseMutableURI + tokenId
/// @dev only an editor (account or module) can call this
/// @param tokenId the token to set the mutable URI for
/// @param mutableURI_ the mutable URI
function setMutableURI(uint256 tokenId, string memory mutableURI_) external;
/// @notice Helper for the owner to add new editors
/// @dev needs to be owner
/// @param users list of new editors
function addEditors(address[] memory users) external;
/// @notice Helper for the owner to remove editors
/// @dev needs to be owner
/// @param users list of removed editors
function removeEditors(address[] memory users) external;
/// @notice Helper for an editor to add new minter
/// @dev needs to be owner
/// @param users list of new minters
function addMinters(address[] memory users) external;
/// @notice Helper for an editor to remove minters
/// @dev needs to be owner
/// @param users list of removed minters
function removeMinters(address[] memory users) external;
/// @notice Allows to change the default royalties recipient
/// @dev an editor can call this
/// @param recipient new default royalties recipient
function setDefaultRoyaltiesRecipient(address recipient) external;
/// @notice Allows a royalty recipient of a token to change their recipient address
/// @dev only the current token royalty recipient can change the address
/// @param tokenId the token to change the recipient for
/// @param recipient new default royalties recipient
function setTokenRoyaltiesRecipient(uint256 tokenId, address recipient)
external;
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_) external;
}
@0xdievardump/niftyforge/contracts/NFT/Royalties/ERC2981/IERC2981Royalties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
@0xdievardump/niftyforge/contracts/NFT/Royalties/FoundationSecondarySales/IFoundationSecondarySales.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IFoundationSecondarySales {
/// @notice returns a list of royalties recipients and the amount
/// @param tokenId the token Id to check for
/// @return all the recipients and their basis points, for tokenId
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
}
@0xdievardump/niftyforge/contracts/NFT/Royalties/RaribleSecondarySales/IRaribleSecondarySales.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IRaribleSecondarySales {
/// @notice returns a list of royalties recipients
/// @param tokenId the token Id to check for
/// @return all the recipients for tokenId
function getFeeRecipients(uint256 tokenId)
external
view
returns (address payable[] memory);
/// @notice returns a list of royalties amounts
/// @param tokenId the token Id to check for
/// @return all the amounts for tokenId
function getFeeBps(uint256 tokenId)
external
view
returns (uint256[] memory);
}
@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {
/**
* @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/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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/security/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @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);
}
@openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
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) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
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 overriden 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 owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
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: transfer caller is not owner nor 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: transfer caller is not owner nor 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 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 _owners[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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, 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);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {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 a {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 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 {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 `IERC721.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/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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 functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// 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
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 v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
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] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
@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/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
contracts/NiftyPrideAuctionHouse.sol
// SPDX-License-Identifier: GPL-3.0
/// @title The NiftyPride Auction House
/************************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░████░░████░░██░░████░░░░████░░ *
* ░░█░░█░░█░░█░░██░░█░░░█░░░█░░░░░ *
* ░░████░░███░░░██░░█░░░░█░░███░░░ *
* ░░█░░░░░█░█░░░██░░█░░░█░░░█░░░░░ *
* ░░█░░░░░█░░█░░██░░████░░░░████░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
***********************************/
// LICENSE
// NiftyPrideAuctionHouse.sol is a modified version of Noun's NounsAuctionHouse.sol:
// https://github.com/nounsDAO/nouns-monorepo/blob/17e61ecaf6f1c66ca8035bf4e0c3c8dae58ca937/packages/nouns-contracts/contracts/NounsAuctionHouse.sol
//
// and is published under the same GPL-3.0 license
pragma solidity ^0.8.6;
import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol';
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import {IAuctionHouse} from './interfaces/IAuctionHouse.sol';
import {IWETH} from './interfaces/IWETH.sol';
contract NiftyPrideAuctionHouse is
IAuctionHouse,
Pausable,
ReentrancyGuard,
Ownable
{
error WrongAuction();
error AuctionExpired();
error ReservePriceNotMet();
error BidTooLow();
error AuctionNotStarted();
error AuctionAlreadySettled();
error AuctionNotEnded();
error RegistryNotSet();
/// @notice The address of the WETH contract
address public weth;
/// @notice The minimum amount of time left in an auction after a new bid is created
uint256 public timeBuffer = 10 minutes;
/// @notice The minimum price accepted in an auction
uint256 public reservePrice = 0.01 ether;
/// @notice The minimum percentage difference between the last bid amount and the current bid
uint8 public minBidIncrementPercentage = 5;
/// @notice The duration of a single auction
uint256 public duration = 24 hours;
/// @notice The active auction
IAuctionHouse.Auction public auction;
constructor(address weth_) {
_pause();
if (block.chainid == 1) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
} else if (block.chainid == 4) {
weth = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
} else {
weth = weth_;
}
}
////////////////////////////////////////////////////
///// Public //
////////////////////////////////////////////////////
/**
* @notice Settle the current auction, mint a new token, and put it up for auction.
*/
function settleCurrentAndCreateNewAuction()
external
override
nonReentrant
whenNotPaused
{
_settleAuction();
_createAuction();
}
/**
* @notice Settle the current auction.
* @dev This function can only be called when the contract is paused.
*/
function settleAuction() external override whenPaused nonReentrant {
_settleAuction();
}
/**
* @notice Create a bid for a token, with a given amount.
* @dev This contract only accepts payment in ETH.
*/
function createBid(uint256 tokenId) external payable override nonReentrant {
IAuctionHouse.Auction memory _auction = auction;
if (_auction.tokenId != tokenId) revert WrongAuction();
if (block.timestamp >= _auction.endTime) revert AuctionExpired();
if (msg.value < reservePrice) revert ReservePriceNotMet();
if (
msg.value <
_auction.amount +
((_auction.amount * minBidIncrementPercentage) / 100)
) {
revert BidTooLow();
}
address payable lastBidder = _auction.bidder;
// Refund the last bidder, if applicable
if (lastBidder != address(0)) {
_safeTransferETHWithFallback(lastBidder, _auction.amount);
}
auction.amount = msg.value;
auction.bidder = payable(msg.sender);
// Extend the auction if the bid was received within `timeBuffer` of the auction end time
bool extended = _auction.endTime - block.timestamp < timeBuffer;
if (extended) {
auction.endTime = _auction.endTime = block.timestamp + timeBuffer;
}
emit AuctionBid(_auction.tokenId, msg.sender, msg.value, extended);
if (extended) {
emit AuctionExtended(_auction.tokenId, _auction.endTime);
}
}
////////////////////////////////////////////////////
///// Contract owner //
////////////////////////////////////////////////////
/**
* @notice Pause the auction house.
* @dev This function can only be called by the owner when the
* contract is unpaused. While no new auctions can be started when paused,
* anyone can settle an ongoing auction.
*/
function pause() external override onlyOwner {
_pause();
}
/**
* @notice Unpause the auction house.
* @dev This function can only be called by the owner when the
* contract is paused. If required, this function will start a new auction.
*/
function unpause() external override onlyOwner {
_unpause();
if (auction.startTime == 0 || auction.settled) {
_createAuction();
}
}
/**
* @notice Set the auction time buffer.
* @dev Only callable by the owner.
*/
function setTimeBuffer(uint256 _timeBuffer) external override onlyOwner {
timeBuffer = _timeBuffer;
emit AuctionTimeBufferUpdated(_timeBuffer);
}
/**
* @notice Set the auction reserve price.
* @dev Only callable by the owner.
*/
function setReservePrice(uint256 _reservePrice)
external
override
onlyOwner
{
reservePrice = _reservePrice;
emit AuctionReservePriceUpdated(_reservePrice);
}
/**
* @notice Set the auction minimum bid increment percentage.
* @dev Only callable by the owner.
*/
function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage)
external
override
onlyOwner
{
minBidIncrementPercentage = _minBidIncrementPercentage;
emit AuctionMinBidIncrementPercentageUpdated(
_minBidIncrementPercentage
);
}
////////////////////////////////////////////////////
///// Internals //
////////////////////////////////////////////////////
/**
* @notice Create an auction.
* @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event.
* If the mint reverts, the minter was updated without pausing this contract first. To remedy this,
* catch the revert and pause this contract.
*/
function _createAuction() internal virtual {
uint256 tokenId = _mintNext();
if (tokenId > 0) {
uint256 startTime = block.timestamp;
uint256 endTime = startTime + duration;
auction = Auction({
tokenId: tokenId,
amount: 0,
startTime: startTime,
endTime: endTime,
bidder: payable(0),
settled: false
});
emit AuctionCreated(tokenId, startTime, endTime);
} else {
_pause();
}
}
/**
* @notice Settle an auction, finalizing the bid and paying out to the owner.
* @dev If there are no bids, the token is sent to the current contract owner (and after to its creator).
*/
function _settleAuction() internal {
IAuctionHouse.Auction memory _auction = auction;
if (_auction.startTime == 0) revert AuctionNotStarted();
if (_auction.settled) revert AuctionAlreadySettled();
if (block.timestamp < _auction.endTime) revert AuctionNotEnded();
auction.settled = true;
ERC721(_getRegistry()).transferFrom(
address(this),
(
_auction.bidder == address(0)
? owner() // if no bidder, send to owner() so it can go back to creator
: _auction.bidder
),
_auction.tokenId
);
if (_auction.amount > 0) {
_transferToRecipients(_auction.tokenId, _auction.amount);
}
emit AuctionSettled(_auction.tokenId, _auction.bidder, _auction.amount);
}
/**
* @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH.
*/
function _safeTransferETHWithFallback(address to, uint256 amount) internal {
if (!_safeTransferETH(to, amount)) {
IWETH(weth).deposit{value: amount}();
IERC20(weth).transfer(to, amount);
}
}
/**
* @notice Transfer ETH and return the success status.
* @dev This function only forwards 30,000 gas to the callee.
*/
function _safeTransferETH(address to, uint256 value)
internal
returns (bool)
{
(bool success, ) = to.call{value: value, gas: 30_000}(new bytes(0));
return success;
}
/// @dev internal function to allow transfer to revenue recipient(s), default to owner()
function _transferToRecipients(uint256, uint256 amount) internal virtual {
_safeTransferETHWithFallback(owner(), amount);
}
/// @dev internal function to mint next token, must be overrode
function _mintNext() internal virtual returns (uint256) {
return 0;
}
/// @dev internal function to get nft contract holder, must be overrode
function _getRegistry() internal virtual returns (address) {
return address(0);
}
}
contracts/Renderers/IRenderer.sol
pragma solidity ^0.8.0;
interface IRenderer {
function description() external view returns (string memory);
function render(bytes32 seed)
external
view
returns (string memory, string memory);
}
contracts/interfaces/IAuctionHouse.sol
// SPDX-License-Identifier: GPL-3.0
/// @title Interface for Auction Houses
/// modified from INounAuctionHouse.sol
pragma solidity ^0.8.6;
interface IAuctionHouse {
struct Auction {
// ID for the token (ERC721 token ID)
uint256 tokenId;
// The current highest bid amount
uint256 amount;
// The time that the auction started
uint256 startTime;
// The time that the auction is scheduled to end
uint256 endTime;
// The address of the current highest bid
address payable bidder;
// Whether or not the auction has been settled
bool settled;
}
event AuctionCreated(
uint256 indexed tokenId,
uint256 startTime,
uint256 endTime
);
event AuctionBid(
uint256 indexed tokenId,
address sender,
uint256 value,
bool extended
);
event AuctionExtended(uint256 indexed tokenId, uint256 endTime);
event AuctionSettled(
uint256 indexed tokenId,
address winner,
uint256 amount
);
event AuctionTimeBufferUpdated(uint256 timeBuffer);
event AuctionReservePriceUpdated(uint256 reservePrice);
event AuctionMinBidIncrementPercentageUpdated(
uint256 minBidIncrementPercentage
);
function settleAuction() external;
function settleCurrentAndCreateNewAuction() external;
function createBid(uint256 tokenId) external payable;
function pause() external;
function unpause() external;
function setTimeBuffer(uint256 timeBuffer) external;
function setReservePrice(uint256 reservePrice) external;
function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage)
external;
}
contracts/interfaces/IBokkyPooBahsDateTimeContract.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;
interface IBokkyPooBahsDateTimeContract {
function timestampToDateTime(uint256 timestamp)
external
pure
returns (
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
);
}
contracts/interfaces/IWETH.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.6;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
contracts/utils/Base64.sol
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
/// modified to add some utility functions
library Base64 {
string internal constant TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
function toB64JSON(bytes memory toEncode)
internal
pure
returns (string memory)
{
return
string(
abi.encodePacked(
'data:application/json;base64,',
encode(toEncode)
)
);
}
function toB64JSON(string memory toEncode)
internal
pure
returns (string memory)
{
return toB64JSON(bytes(toEncode));
}
function toB64SVG(bytes memory toEncode)
internal
pure
returns (string memory)
{
return
string(
abi.encodePacked('data:image/svg+xml;base64,', encode(toEncode))
);
}
function toB64SVG(string memory toEncode)
internal
pure
returns (string memory)
{
return toB64SVG(bytes(toEncode));
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.