¡El código fuente de este contrato está verificado!
Metadatos del Contrato
Compilador
0.8.9+commit.e5eed63a
Idioma
Solidity
Código Fuente del Contrato
Archivo 1 de 20: Address.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory 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._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory 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._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory 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._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Código Fuente del Contrato
Archivo 2 de 20: BatchOffsets.sol
//SPDX-License-Identifier: MITpragmasolidity >=0.8.0;/// @title Batch Offsets/// @author Adam Fuller (@azf20)/// Randomly shuffles IDs in batches, given an overall token limit/// Requirements: batchSize() divides perfectly into limit(), tokenIds start at 0contractBatchOffsets{
errorBatchNotRevealed();
eventBatchRevealed(uint256 batch, uint256 batchSize, uint256 within, uint256 overall);
// counter of revealed batchesuint256public revealedBatches;
// tracking the number of tokens in a batchuint256internal _batchSize;
functionbatchSize() publicviewvirtualreturns (uint256) {
return _batchSize;
}
// limit function, to be overriden by the importing contractfunctionlimit() publicviewvirtualreturns (uint256) {
return0;
}
// structure for an individual batch offsetstructBatchOffset {
uint256 seed; // the random number used to generate the offsetsuint256 within; // the offset of tokens within the batchuint256 overall; // the offset of the batch overall, relative to other batches
}
// batches start at 1mapping(uint256=> BatchOffset) public offsets;
mapping(uint256=>bool) private takenOffsets;
// Storing the offsets which are taken in a packed array of booleansmapping(uint256=>uint256) public takenBitMap;
/// @notice Internal function to set an index as taken/// @param index the indexfunction_setTaken(uint256 index) private{
uint256 takenWordIndex = index /256;
uint256 takenBitIndex = index %256;
takenBitMap[takenWordIndex] = takenBitMap[takenWordIndex] | (1<< takenBitIndex);
}
// set the batch offset for a batch, given a random numberfunction_setBatchOffset(uint256 _batch, uint256 random) internal{
// get an offset for within this batch
BatchOffset memory newBatchOffset;
newBatchOffset.seed = random;
newBatchOffset.within = random % batchSize();
// get an initial overall offset, out of the remaining slotsuint256 range = ((limit() / batchSize()) - revealedBatches);
random >>=16;
uint256 overall = random % range;
// create an array to populate with the remaining available offsetsuint256[] memory offsetOptions =newuint256[](range);
uint256 counter;
uint256 word;
// fetch the first word from the packed booleans (makes it closer to O(1))uint256 takenWord = takenBitMap[word];
// check which offsets are already taken from the full rangefor(uint256 j=0; j<(limit() / batchSize()); j++) {
// if the offset is beyond the range of the current word, fetch the next wordif ((j /256) > word) {
takenWord = takenBitMap[j /256];
}
// check if a given offset is taken. If it is not, add it to the array of optionsuint256 takenBitIndex = j %256;
uint256 mask = (1<< takenBitIndex);
if(takenWord & mask != mask) {
offsetOptions[counter] = j;
counter +=1;
}
}
// the offset uses the initial offset to pick from the remaining available offsets
newBatchOffset.overall = offsetOptions[overall];
// set the selected offset as taken, and save the batch offset and increase the revealedBatches counter
_setTaken(newBatchOffset.overall);
offsets[_batch] = newBatchOffset;
revealedBatches +=1;
emit BatchRevealed(_batch, batchSize(), newBatchOffset.within, newBatchOffset.overall);
}
// helper to work out which batch an ID is fromfunctionidToBatch(uint256 id) publicviewreturns (uint256) {
return ((id) / batchSize()) +1;
}
// get the shuffled ID, based on its batch's offsetsfunctiongetShuffledId(uint256 id) publicvirtualviewreturns (uint256) {
uint256 _batch = idToBatch(id);
if(offsets[_batch].seed ==0) revert BatchNotRevealed();
BatchOffset memory _offset = offsets[_batch];
uint256 within = (((id) % batchSize()) + _offset.within) % batchSize();
return (within * (limit() / batchSize())) + _offset.overall
;
}
}
Código Fuente del Contrato
Archivo 3 de 20: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Código Fuente del Contrato
Archivo 4 de 20: ECDSA.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)pragmasolidity ^0.8.0;import"../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/libraryECDSA{
enumRecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function_throwError(RecoverError error) privatepure{
if (error == RecoverError.NoError) {
return; // no error: do nothing
} elseif (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} elseif (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} elseif (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} elseif (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytesmemory signature) internalpurereturns (address, RecoverError) {
// Check the signature length// - case 65: r,s,v signature (standard)// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._if (signature.length==65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
s :=mload(add(signature, 0x40))
v :=byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} elseif (signature.length==64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly.assembly {
r :=mload(add(signature, 0x20))
vs :=mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address, RecoverError) {
bytes32 s = vs &bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v =uint8((uint256(vs) >>255) +27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/functionrecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most// signatures from current libraries generate a unique signature with an s-value in the lower half order.//// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept// these malleable signatures as well.if (uint256(s) >0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v !=27&& v !=28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
if (signer ==address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/functionrecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytes32 hash) internalpurereturns (bytes32) {
// 32 is the length in bytes of hash,// enforced by the type signature abovereturnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytesmemory s) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/functiontoTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
Código Fuente del Contrato
Archivo 5 de 20: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Código Fuente del Contrato
Archivo 6 de 20: ERC2981Base.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import'@openzeppelin/contracts/utils/introspection/ERC165.sol';
import'./IERC2981Royalties.sol';
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155abstractcontractERC2981BaseisERC165, IERC2981Royalties{
structRoyaltyInfo {
address recipient;
uint24 amount;
}
/// @inheritdoc ERC165functionsupportsInterface(bytes4 interfaceId)
publicviewvirtualoverridereturns (bool)
{
return
interfaceId ==type(IERC2981Royalties).interfaceId||super.supportsInterface(interfaceId);
}
}
Código Fuente del Contrato
Archivo 7 de 20: ERC2981ContractWideRoyalties.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import'@openzeppelin/contracts/utils/introspection/ERC165.sol';
import'./ERC2981Base.sol';
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155/// @dev This implementation has the same royalties for each and every tokensabstractcontractERC2981ContractWideRoyaltiesisERC2981Base{
RoyaltyInfo private _royalties;
/// @dev Sets token royalties/// @param recipient recipient of the royalties/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)function_setRoyalties(address recipient, uint256 value) internal{
require(value <=10000, 'ERC2981Royalties: Too high');
_royalties = RoyaltyInfo(recipient, uint24(value));
}
/// @inheritdoc IERC2981RoyaltiesfunctionroyaltyInfo(uint256, uint256 value)
externalviewoverridereturns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (value * royalties.amount) /10000;
}
}
Código Fuente del Contrato
Archivo 8 de 20: ERC721A.sol
// SPDX-License-Identifier: MIT// Creator: Chiru Labspragmasolidity ^0.8.4;import'@openzeppelin/contracts/token/ERC721/IERC721.sol';
import'@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import'@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import'@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import'@openzeppelin/contracts/utils/Address.sol';
import'@openzeppelin/contracts/utils/Context.sol';
import'@openzeppelin/contracts/utils/Strings.sol';
import'@openzeppelin/contracts/utils/introspection/ERC165.sol';
errorApprovalCallerNotOwnerNorApproved();
errorApprovalQueryForNonexistentToken();
errorApproveToCaller();
errorApprovalToCurrentOwner();
errorBalanceQueryForZeroAddress();
errorMintedQueryForZeroAddress();
errorBurnedQueryForZeroAddress();
errorAuxQueryForZeroAddress();
errorMintToZeroAddress();
errorMintZeroQuantity();
errorOwnerIndexOutOfBounds();
errorOwnerQueryForNonexistentToken();
errorTokenIndexOutOfBounds();
errorTransferCallerNotOwnerNorApproved();
errorTransferFromIncorrectOwner();
errorTransferToNonERC721ReceiverImplementer();
errorTransferToZeroAddress();
errorURIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/contractERC721AisContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Compiler will pack this into a single 256bit word.structTokenOwnership {
// The address of the owner.address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.uint64 startTimestamp;
// Whether the token has been burned.bool burned;
}
// Compiler will pack this into a single 256bit word.structAddressData {
// Realistically, 2**64-1 is more than enough.uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address// (e.g. number of whitelist mint slots used).// If there are multiple variables, please pack them into a uint64.uint64 aux;
}
// The tokenId of the next token to be minted.uint256internal _currentIndex;
// The number of tokens burned.uint256internal _burnCounter;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to ownership details// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.mapping(uint256=> TokenOwnership) internal _ownerships;
// Mapping owner address to address datamapping(address=> AddressData) private _addressData;
// Mapping from token ID to approved addressmapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/function_startTokenId() internalviewvirtualreturns (uint256) {
return0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/functiontotalSupply() publicviewreturns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented// more than _currentIndex - _startTokenId() timesunchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/function_totalMinted() internalviewreturns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,// and it is initialized to _startTokenId()unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewoverridereturns (uint256) {
if (owner ==address(0)) revert BalanceQueryForZeroAddress();
returnuint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/function_numberMinted(address owner) internalviewreturns (uint256) {
if (owner ==address(0)) revert MintedQueryForZeroAddress();
returnuint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/function_numberBurned(address owner) internalviewreturns (uint256) {
if (owner ==address(0)) revert BurnedQueryForZeroAddress();
returnuint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/function_getAux(address owner) internalviewreturns (uint64) {
if (owner ==address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/function_setAux(address owner, uint64 aux) internal{
if (owner ==address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/functionownershipOf(uint256 tokenId) internalviewreturns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr !=address(0)) {
return ownership;
}
// Invariant:// There will always be an ownership that has an address and is not burned// before an ownership that does not have an address and is not burned.// Hence, curr will not underflow.while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr !=address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewoverridereturns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length!=0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return'';
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicoverride{
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner &&!isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewoverridereturns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicoverride{
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) publicvirtualoverride{
_transfer(from, to, tokenId);
if (to.isContract() &&!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/function_exists(uint256 tokenId) internalviewreturns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&!_ownerships[tokenId].burned;
}
function_safeMint(address to, uint256 quantity) internal{
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internal{
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/function_mint(address to,
uint256 quantity,
bytesmemory _data,
bool safe
) internal{
uint256 startTokenId = _currentIndex;
if (to ==address(0)) revert MintToZeroAddress();
if (quantity ==0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1unchecked {
_addressData[to].balance+=uint64(quantity);
_addressData[to].numberMinted +=uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp =uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protectionif (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom,
address to,
uint256 tokenId
) private{
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr !=from) revert TransferFromIncorrectOwner();
if (to ==address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for// ownership above and the recipient's balance can't realistically overflow.// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.unchecked {
_addressData[from].balance-=1;
_addressData[to].balance+=1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp =uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.uint256 nextTokenId = tokenId +1;
if (_ownerships[nextTokenId].addr ==address(0)) {
// This will suffice for checking _exists(nextTokenId),// as a burned slot cannot contain the zero address.if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for// ownership above and the recipient's balance can't realistically overflow.// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.unchecked {
_addressData[prevOwnership.addr].balance-=1;
_addressData[prevOwnership.addr].numberBurned +=1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp =uint64(block.timestamp);
_ownerships[tokenId].burned =true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.uint256 nextTokenId = tokenId +1;
if (_ownerships[nextTokenId].addr ==address(0)) {
// This will suffice for checking _exists(nextTokenId),// as a burned slot cannot contain the zero address.if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/function_approve(address to,
uint256 tokenId,
address owner
) private{
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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_checkContractOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/function_beforeTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/function_afterTokenTransfers(addressfrom,
address to,
uint256 startTokenId,
uint256 quantity
) internalvirtual{}
}
Código Fuente del Contrato
Archivo 9 de 20: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Código Fuente del Contrato
Archivo 10 de 20: IERC2981Royalties.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/// @title IERC2981Royalties/// @dev Interface for the ERC2981 - Token Royalty standardinterfaceIERC2981Royalties{
/// @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 pricefunctionroyaltyInfo(uint256 _tokenId, uint256 _value)
externalviewreturns (address _receiver, uint256 _royaltyAmount);
}
Código Fuente del Contrato
Archivo 11 de 20: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (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.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (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.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
}
Código Fuente del Contrato
Archivo 12 de 20: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/interfaceIERC721EnumerableisIERC721{
/**
* @dev Returns the total amount of tokens stored by the contract.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) externalviewreturns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
Código Fuente del Contrato
Archivo 15 de 20: MPL.sol
//SPDX-License-Identifier: MITpragmasolidity >=0.8.0;import"@openzeppelin/contracts/utils/Strings.sol";
import"@rari-capital/solmate/src/utils/ReentrancyGuard.sol";
import"erc721a/contracts/ERC721A.sol";
import"./SignedAllowance.sol";
import"./MultisigOwnable.sol";
import"./BatchOffsets.sol";
import'./ERC2981ContractWideRoyalties.sol';
/*
'##::::'##:'########::'##:::::::
###::'###: ##.... ##: ##:::::::
####'####: ##:::: ##: ##:::::::
## ### ##: ########:: ##:::::::
##. #: ##: ##.....::: ##:::::::
##:.:: ##: ##:::::::: ##:::::::
##:::: ##: ##:::::::: ########:
..:::::..::..:::::::::........::
*//// @title Martian Premier LeaguecontractMPLisERC721A, BatchOffsets, SignedAllowance, ReentrancyGuard, MultisigOwnable, ERC2981ContractWideRoyalties{
usingStringsforuint256;
// Custom errorserrorOverMintLimit();
errorAllMinted();
errorInsufficientValue();
errorInvalidRecipient();
errorTokenDoesNotExist();
errorPublicSaleNotStarted();
errorMarsListInactive();
errorAlreadyClaimed();
errorSenderNotTxOrigin();
errorBatchNotMinted();
errorNonSequentialBatch();
errorLimitBatchMismatch();
errorOnlyOneCallPerBlockForNonEOA();
errorContractIsFrozen();
errorNotUsingBatches();
// events to help with indexingeventLimitUpdated(uint256 newLimit);
eventBaseURIUpdated(string newBaseURI);
eventSuffixUpdated(string newSuffix);
eventPreRevealURIUpdated(string newPreRevealURI);
eventMaxQuantityUpdated(uint256 newMaxQuantity);
eventPriceUpdated(uint256 newPrice);
eventFundsWithdrawn(uint256 amount);
eventPublicSaleUpdated(bool newValue);
eventMarsListUpdated(bool newValue);
eventBatchSizeUpdated(uint256 newBatchSize);
eventFrozen();
eventFancyMathUpdated();
eventRoyaltiesUpdated(uint256 value);
/*///////////////////////////////////////////////////////////////
Settings
//////////////////////////////////////////////////////////////*/// tracking internal variablesuint256private _limit;
uint256private _revealedBatch;
// max quantity that can be minted per mint()uint256public maxQuantity;
// price per characteruint256public price;
// tokens reserved for the MPL teamuint256public ownerLimit;
uint256public ownerCount;
// sale state variablesboolpublic publicSale;
boolpublic marsList;
// metadata configurationstringpublic baseURI;
stringpublic preRevealURI;
stringprivate _suffix =".json";
boolpublic frozen;
boolpublic useFancyMath =true;
// minimum indexuint256public minimumIndex;
// tracking last calls from smart contracts minting, to prevent multi-mintingmapping(address=>uint256) public lastCallFrom;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/structInitialConfiguration {
address owner;
uint256 limit;
uint256 maxQuantity;
uint256 ownerLimit;
uint256 price;
string baseURI;
string preRevealURI;
uint256 revealBatchSize;
uint256 royaltyValue;
}
/// @param config initial configuration for the MPLconstructor(InitialConfiguration memory config) ERC721A("MPL", "MPL") {
setBatchSize(config.revealBatchSize);
setLimit(config.limit);
setMaxQuantity(config.maxQuantity);
ownerLimit = config.ownerLimit;
setPrice(config.price);
setBaseURI(config.baseURI);
setPreRevealURI(config.preRevealURI);
setRoyalties(config.royaltyValue);
transferOwnership(config.owner);
transferRealOwnership(config.owner);
}
/*///////////////////////////////////////////////////////////////
View functions
//////////////////////////////////////////////////////////////*//// @notice returns the maximum number of tokens available to mint/// @return limit the limitfunctionlimit() publicviewoverridereturns (uint256) {
return _limit;
}
/// @notice get the shuffled final character ID for a given token (once revealed)/// @param id tokenId/// @return the shuffled character IDfunctiongetShuffledId(uint256 id) publicviewoverridereturns (uint256) {
if(!useFancyMath) revert NotUsingBatches();
if(ownerOf(id) ==address(0)) revert TokenDoesNotExist();
return BatchOffsets.getShuffledId(id);
}
/// @notice Returns the URI for a given token's metadata/// @param id the token ID of interest/// @return the URI for this tokenfunctiontokenURI(uint256 id) publicviewoverridereturns (stringmemory) {
if(ownerOf(id) ==address(0)) revert TokenDoesNotExist();
if(!useFancyMath) {
returnstring(abi.encodePacked(baseURI,id.toString(),_suffix));
}
if(idToBatch(id) > _revealedBatch) return preRevealURI;
uint256 offsetId = getShuffledId(id);
returnstring(abi.encodePacked(baseURI,offsetId.toString(),_suffix));
}
/// @notice Helper to know allowancesSigner address/// @return the allowance signer addressfunctionallowancesSigner() publicviewoverridereturns (address) {
return owner();
}
structConfiguration {
uint256 limit;
uint256 totalSupply;
uint256 maxQuantity;
uint256 price;
string baseURI;
bool marsList;
bool publicSale;
}
/// @notice helper to fetch a lot of useful data in a single call/// @return the overall configurationfunctionconfiguration() publicviewreturns (Configuration memory) {
Configuration memory config;
config.limit = limit();
config.totalSupply = totalSupply();
config.maxQuantity = maxQuantity;
config.price = price;
config.baseURI = baseURI;
config.marsList = marsList;
config.publicSale = publicSale;
return config;
}
/// @inheritdoc ERC165functionsupportsInterface(bytes4 interfaceId)
publicviewvirtualoverride(ERC721A, ERC2981Base)
returns (bool)
{
returnsuper.supportsInterface(interfaceId);
}
/*///////////////////////////////////////////////////////////////
Updating settings
//////////////////////////////////////////////////////////////*//// @notice modifier to check if the contract metadata has been frozenmodifiernotFrozen() {
if(frozen) revert ContractIsFrozen();
_;
}
/// @notice owner only function to freeze the metadatafunctionsetFrozen() publiconlyRealOwnernotFrozen{
emit Frozen();
frozen =true;
}
/// @notice owner only function to toggle if we are using offsets for token IDsfunctionsetUseFancyMath() publiconlyRealOwnernotFrozen{
emit FancyMathUpdated();
useFancyMath =!useFancyMath;
}
/// @notice owner only function to update the metadata suffix/// @param newSuffix new suffixfunctionsetSuffix(stringmemory newSuffix) publiconlyRealOwnernotFrozen{
emit SuffixUpdated(newSuffix);
_suffix = newSuffix;
}
/// @notice owner only function to update the baseURI/// @param newBaseURI the new BaseURIfunctionsetBaseURI(stringmemory newBaseURI) publiconlyRealOwnernotFrozen{
emit BaseURIUpdated(newBaseURI);
baseURI = newBaseURI;
}
/// @notice owner only function to update the preRevealURI/// @param newPreRevealURI the new preRevealURIfunctionsetPreRevealURI(stringmemory newPreRevealURI) publiconlyRealOwner{
emit PreRevealURIUpdated(newPreRevealURI);
preRevealURI = newPreRevealURI;
}
/// @notice owner only function to update the limit (not available once hit)/// batch reveal must divide cleanly into it/// @param newLimit the new LimitfunctionsetLimit(uint256 newLimit) publiconlyRealOwner{
if(totalSupply() == limit() && totalSupply() >0) revert AllMinted();
if(newLimit % batchSize() !=0) revert LimitBatchMismatch();
emit LimitUpdated(newLimit);
_limit = newLimit;
}
/// @notice owner only function to update the batch size for token reveals/// batch reveal must divide cleanly into the limit/// @param newBatchSize the new batch sizefunctionsetBatchSize(uint256 newBatchSize) publiconlyRealOwner{
if(!useFancyMath) revert NotUsingBatches();
if(totalSupply() == limit() && totalSupply() >0) revert AllMinted();
if(limit() % newBatchSize !=0) revert LimitBatchMismatch();
emit BatchSizeUpdated(newBatchSize);
_batchSize = newBatchSize;
}
/// @notice owner only function to update the max quantity per mint/// @param newMaxQuantity the new max quantityfunctionsetMaxQuantity(uint256 newMaxQuantity) publiconlyRealOwner{
emit MaxQuantityUpdated(newMaxQuantity);
maxQuantity = newMaxQuantity;
}
/// @notice owner only function to update the price per mint/// @param newPrice the new pricefunctionsetPrice(uint256 newPrice) publiconlyRealOwner{
emit PriceUpdated(newPrice);
price = newPrice;
}
/// @notice owner only function to activate or deactivate the public salefunctionsetPublicSale() publiconlyRealOwner{
emit PublicSaleUpdated(!publicSale);
publicSale =!publicSale;
}
/// @notice owner only function to activate or deactivate the Mars listfunctionsetMarsList() publiconlyRealOwner{
emit MarsListUpdated(!marsList);
marsList =!marsList;
}
/// @notice owner only function to set the minimum Mars List index supported/// @param newMinimumIndex the newMinimumIndexfunctionsetMinimumIndex(uint256 newMinimumIndex) publiconlyRealOwner{
minimumIndex = newMinimumIndex;
}
/// @notice Allows to set the royalties on the contract/// @param value royalties value (between 0 and 10000)functionsetRoyalties(uint256 value) publiconlyRealOwner{
emit RoyaltiesUpdated(value);
_setRoyalties(realOwner, value);
}
/*///////////////////////////////////////////////////////////////
Updating Batches
//////////////////////////////////////////////////////////////*//// @notice simple predictable generator of randomness based on on-chain data, given a seedfunction_getPredictableRandom(uint256 _seed) internalviewreturns (uint256){
returnuint256(keccak256(abi.encodePacked( blockhash(block.number-1), _seed, msg.sender, address(this) )));
}
/// @notice set the random offsets for a batch of batchSize() tokens/// @param _batch the batch to revealfunctionsetBatchOffset(uint256 _batch) publiconlyRealOwner{
if(!useFancyMath) revert NotUsingBatches();
if(totalSupply() < batchSize() * _batch && totalSupply() < limit()) revert BatchNotMinted();
if(_batch != (_revealedBatch +1)) revert NonSequentialBatch();
_revealedBatch = _batch;
_setBatchOffset(_batch, _getPredictableRandom(_batch));
}
/*///////////////////////////////////////////////////////////////
Withdrawing proceeds
//////////////////////////////////////////////////////////////*//// @notice only owner function to withdraw fundsfunctionwithdrawFunds() publiconlyRealOwner{
uint amount =address(this).balance;
(bool success,) =msg.sender.call{value: amount}("");
require(success, "Failed");
emit FundsWithdrawn(amount);
}
/*///////////////////////////////////////////////////////////////
MINT LOGIC
//////////////////////////////////////////////////////////////*//// @notice internal only function to batch mint tokens/// @param to address to receive the tokens/// @param quantity number of tokens to mintfunction_batchMint(address to, uint256 quantity) internalvirtual{
if(quantity > (limit() - totalSupply()) || (quantity > maxQuantity &&msg.sender!= realOwner) || quantity ==0) revert OverMintLimit();
_safeMint(to, quantity);
}
/// @notice public mint function, for public sale/// @param quantity number of tokens to mintfunctionmint(uint256 quantity) publicpayablenonReentrant{
if(!publicSale) revert PublicSaleNotStarted();
if(msg.value< (price * quantity)) revert InsufficientValue();
// hat tip to @dieverdump https://twitter.com/dievardump/status/1486111678550974464if (msg.sender!=tx.origin) {
if (lastCallFrom[tx.origin] ==block.number) {
revert OnlyOneCallPerBlockForNonEOA();
}
lastCallFrom[tx.origin] =block.number;
}
_batchMint(msg.sender, quantity);
}
/// @notice function to batch mint tokens with an owner signature/// @param quantity number of tokens to mint/// @param index the index of the Mars List spot/// @param signature owner signed messagefunctionmintWithSignature(uint256 quantity, uint256 index, bytesmemory signature) publicpayable{
if(!marsList || index < minimumIndex) revert MarsListInactive();
if(msg.value< (price * quantity)) revert InsufficientValue();
_useAllowance(index, signature);
_batchMint(msg.sender, quantity);
}
/// @notice only owner function to mint based on the ownerLimit/// @param quantity number of tokens to mintfunctionownerMint(uint256 quantity) publiconlyRealOwner{
if(ownerCount + quantity > ownerLimit) revert OverMintLimit();
ownerCount = ownerCount + quantity;
_batchMint(msg.sender, quantity);
}
}
Código Fuente del Contrato
Archivo 16 de 20: MultisigOwnable.sol
//SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"@openzeppelin/contracts/access/Ownable.sol";
/*
Source: https://github.com/0xngmi/tubbies/blob/master/contracts/MultisigOwnable.sol
Opensea only allows EOAs to make changes to collections,
which makes it impossible to use multisigs to secure these NFT contracts
since when you want to make changes you need to transfer ownership to an EOA, who can rug.
This contract establishes a second owner that can change the EOA owner,
this way a multisig can give ownership to an EOA and later claim it back.
*/abstractcontractMultisigOwnableisOwnable{
addresspublic realOwner;
eventRealOwnershipTransferred(address oldRealOwner, address newRealOwner);
constructor() {
realOwner =msg.sender;
}
modifieronlyRealOwner() {
require(realOwner ==msg.sender, "MultisigOwnable: caller is not the real owner");
_;
}
functiontransferRealOwnership(address newRealOwner) publiconlyRealOwner{
emit RealOwnershipTransferred(realOwner, newRealOwner);
realOwner = newRealOwner;
}
functiontransferOwnership(address newOwner) publicoverrideonlyRealOwner{
_transferOwnership(newOwner);
}
}
Código Fuente del Contrato
Archivo 17 de 20: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
//SPDX-License-Identifier: MITpragmasolidity ^0.8.9;import'@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
/// @title SignedAllowance with claimedBitMap/// @author Simon Fremaux (@dievardump) / Adam Fuller (@azf20)/// Original: https://github.com/dievardump/signed-minting/blob/main/contracts/SignedAllowance.solcontractSignedAllowance{
usingECDSAforbytes32;
// event to track claimseventClaimed(uint256 index, address account);
// This is a packed array of booleans to track claimsmapping(uint256=>uint256) public claimedBitMap;
/// @notice Helper to check if an index has been claimed/// @param index the indexfunctionisClaimed(uint256 index) publicviewreturns (bool) {
uint256 claimedWordIndex = index /256;
uint256 claimedBitIndex = index %256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1<< claimedBitIndex);
return claimedWord & mask == mask;
}
/// @notice Internal function to set an index as claimed/// @param index the indexfunction_setClaimed(uint256 index) private{
uint256 claimedWordIndex = index /256;
uint256 claimedBitIndex = index %256;
claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1<< claimedBitIndex);
}
// address used to sign the allowancesaddressprivate _allowancesSigner;
/// @notice Helper to know allowancesSigner address/// @return the allowance signer addressfunctionallowancesSigner() publicviewvirtualreturns (address) {
return _allowancesSigner;
}
/// @notice Helper that creates the message that signer needs to sign to allow a mint/// this is usually also used when creating the allowances, to ensure "message"/// is the same/// @param account the account to allow/// @param index the index/// @return the message to signfunctioncreateMessage(address account, uint256 index)
publicviewreturns (bytes32)
{
returnkeccak256(abi.encode(account, index, address(this)));
}
/// @notice Helper that creates a list of messages that signer needs to sign to allow mintings/// @param accounts the accounts to allow/// @param indexes the corresponding indexes/// @return messages the messages to signfunctioncreateMessages(address[] memory accounts, uint256[] memory indexes)
externalviewreturns (bytes32[] memory messages)
{
require(accounts.length== indexes.length, '!LENGTH_MISMATCH!');
messages =newbytes32[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
messages[i] = createMessage(accounts[i], indexes[i]);
}
}
/// @notice This function verifies that the current request is valid/// @dev It ensures that _allowancesSigner signed a message containing (account, index, address(this))/// and that this message was not already used/// @param account the account the allowance is associated to/// @param index the index associated to this allowance/// @param signature the signature by the allowance signer wallet/// @return the message to mark as usedfunctionvalidateSignature(address account,
uint256 index,
bytesmemory signature
) publicviewreturns (bytes32) {
return
_validateSignature(account, index, signature, allowancesSigner());
}
/// @dev It ensures that signer signed a message containing (account, index, address(this))/// and that this message was not already used/// @param account the account the allowance is associated to/// @param index the index associated to this allowance/// @param signature the signature by the allowance signer wallet/// @param signer the signer/// @return the message to mark as usedfunction_validateSignature(address account,
uint256 index,
bytesmemory signature,
address signer
) internalviewreturns (bytes32) {
bytes32 message = createMessage(account, index)
.toEthSignedMessageHash();
// verifies that the sha3(account, index, address(this)) has been signed by signerrequire(message.recover(signature) == signer, '!INVALID_SIGNATURE!');
// verifies that the allowances was not already usedrequire(isClaimed(index) ==false, '!ALREADY_USED!');
return message;
}
/// @notice internal function that verifies an allowance and marks it as used/// this function throws if signature is wrong or this index for this user has already been used/// @param index the index/// @param signature the signature by the allowance walletfunction_useAllowance(uint256 index,
bytesmemory signature
) internal{
validateSignature(msg.sender, index, signature);
_setClaimed(index);
}
/// @notice Allows to change the allowance signer. This can be used to revoke any signed allowance not already used/// @param newSigner the new signer addressfunction_setAllowancesSigner(address newSigner) internal{
_allowancesSigner = newSigner;
}
}
Código Fuente del Contrato
Archivo 20 de 20: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
}