// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;/// @notice Library to encode strings in Base64./// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)/// @author Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos - <brecht@loopring.org>.libraryBase64{
/// @dev Encodes `data` using the base64 encoding described in RFC 4648./// See: https://datatracker.ietf.org/doc/html/rfc4648/// @param fileSafe Whether to replace '+' with '-' and '/' with '_'./// @param noPadding Whether to strip away the padding.functionencode(bytesmemory data, bool fileSafe, bool noPadding)
internalpurereturns (stringmemory result)
{
/// @solidity memory-safe-assemblyassembly {
let dataLength :=mload(data)
if dataLength {
// Multiply by 4/3 rounded up.// The `shl(2, ...)` is equivalent to multiplying by 4.let encodedLength :=shl(2, div(add(dataLength, 2), 3))
// Set `result` to point to the start of the free memory.
result :=mload(0x40)
// Store the table into the scratch space.// Offsetted by -1 byte so that the `mload` will load the character.// We will rewrite the free memory pointer at `0x40` later with// the allocated size.// The magic constant 0x0230 will translate "-_" + "+/".mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, sub("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0230)))
// Skip the first slot, which stores the length.let ptr :=add(result, 0x20)
let end :=add(ptr, encodedLength)
// Run over the input, 3 bytes at a time.for {} 1 {} {
data :=add(data, 3) // Advance 3 bytes.let input :=mload(data)
// Write 4 bytes. Optimized for fewer stack operations.mstore8(0, mload(and(shr(18, input), 0x3F)))
mstore8(1, mload(and(shr(12, input), 0x3F)))
mstore8(2, mload(and(shr(6, input), 0x3F)))
mstore8(3, mload(and(input, 0x3F)))
mstore(ptr, mload(0x00))
ptr :=add(ptr, 4) // Advance 4 bytes.ifiszero(lt(ptr, end)) { break }
}
// Allocate the memory for the string.// Add 31 and mask with `not(31)` to round the// free memory pointer up the next multiple of 32.mstore(0x40, and(add(end, 31), not(31)))
// Equivalent to `o = [0, 2, 1][dataLength % 3]`.let o :=div(2, mod(dataLength, 3))
// Offset `ptr` and pad with '='. We can simply write over the end.mstore(sub(ptr, o), shl(240, 0x3d3d))
// Set `o` to zero if there is padding.
o :=mul(iszero(iszero(noPadding)), o)
// Zeroize the slot after the string.mstore(sub(ptr, o), 0)
// Write the length of the string.mstore(result, sub(encodedLength, o))
}
}
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648./// Equivalent to `encode(data, false, false)`.functionencode(bytesmemory data) internalpurereturns (stringmemory result) {
result = encode(data, false, false);
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648./// Equivalent to `encode(data, fileSafe, false)`.functionencode(bytesmemory data, bool fileSafe)
internalpurereturns (stringmemory result)
{
result = encode(data, fileSafe, false);
}
/// @dev Decodes base64 encoded `data`.////// Supports:/// - RFC 4648 (both standard and file-safe mode)./// - RFC 3501 (63: ',').////// Does not support:/// - Line breaks.////// Note: For performance reasons,/// this function will NOT revert on invalid `data` inputs./// Outputs for invalid inputs will simply be undefined behaviour./// It is the user's responsibility to ensure that the `data`/// is a valid base64 encoded string.functiondecode(stringmemory data) internalpurereturns (bytesmemory result) {
/// @solidity memory-safe-assemblyassembly {
let dataLength :=mload(data)
if dataLength {
let decodedLength :=mul(shr(2, dataLength), 3)
for {} 1 {} {
// If padded.ifiszero(and(dataLength, 3)) {
let t :=xor(mload(add(data, dataLength)), 0x3d3d)
// forgefmt: disable-next-item
decodedLength :=sub(
decodedLength,
add(iszero(byte(30, t)), iszero(byte(31, t)))
)
break
}
// If non-padded.
decodedLength :=add(decodedLength, sub(and(dataLength, 3), 1))
break
}
result :=mload(0x40)
// Write the length of the bytes.mstore(result, decodedLength)
// Skip the first slot, which stores the length.let ptr :=add(result, 0x20)
let end :=add(ptr, decodedLength)
// Load the table into the scratch space.// Constants are optimized for smaller bytecode with zero gas overhead.// `m` also doubles as the mask of the upper 6 bits.let m :=0xfc000000fc00686c7074787c8084888c9094989ca0a4a8acb0b4b8bcc0c4c8ccmstore(0x5b, m)
mstore(0x3b, 0x04080c1014181c2024282c3034383c4044484c5054585c6064)
mstore(0x1a, 0xf8fcf800fcd0d4d8dce0e4e8ecf0f4)
for {} 1 {} {
// Read 4 bytes.
data :=add(data, 4)
let input :=mload(data)
// Write 3 bytes.// forgefmt: disable-next-itemmstore(ptr, or(
and(m, mload(byte(28, input))),
shr(6, or(
and(m, mload(byte(29, input))),
shr(6, or(
and(m, mload(byte(30, input))),
shr(6, mload(byte(31, input)))
))
))
))
ptr :=add(ptr, 3)
ifiszero(lt(ptr, end)) { break }
}
// Allocate the memory for the string.// Add 31 and mask with `not(31)` to round the// free memory pointer up the next multiple of 32.mstore(0x40, and(add(end, 31), not(31)))
// Zeroize the slot after the bytes.mstore(end, 0)
// Restore the zero slot.mstore(0x60, 0)
}
}
}
}
Contract Source Code
File 3 of 24: Clifford.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"@openzeppelin/contracts/access/Ownable.sol";
import"@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol";
import"@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import"@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import"ERC721A/ERC721A.sol";
import"./Metadata.sol";
import"solady/utils/LibBitmap.sol";
interfaceICypher{
functionownerOf(uint) externalviewreturns (address);
}
/// @notice Main Contract for the Machine For Dying NFT collection./// @author Zac Williams (https://twitter.com/ZacW369)/// @author Anomalous Materials (https://twitter.com/AnomalousMatter)contractCliffordisERC721A, Ownable, VRFConsumerBaseV2{
addressprivateconstant vrfCoordinator =0x271682DEB8C4E0901D1a1550aD2e64D568E69909;
VRFCoordinatorV2Interface constant COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
LinkTokenInterface constant LINKTOKEN = LinkTokenInterface(0x514910771AF9Ca656af840dff83E8264EcF986CA);
// CUSTOM ERRORSerrorInvalidTokenId(uint tokenId);
errorSeedNotSet(uint genId);
errorTransferFailed();
errorNotOwnerOfCypher(uint tokenId);
errorCypherAlreadyClaimed(uint tokenId);
errorCypherClaimNotActive();
errorCannotBidZero();
errorIncorrectBidIncrement(uint amount);
errorAuctionNotActive();
errorBidTooSmall(uint amount);
errorAuctionAlreadyStarted();
errorCypherClaimNotStarted();
errorCypherClaimNotEnded();
errorAuctionNotOver();
errorNftsNotAllMinted();
errorTransferNotSuccessful(address to);
errorNoBidToClaim(address to);
errorTooManyRequested();
// EVENTS// emit genId and seed when random number is generatedeventRandomNumberGenerated(uint256 genId, uint256 seed);
// emit genId when reveal is calledeventRandomnessRequested(uint256 genId);
// emit bidder's address and amount bideventUserPlacesBid(address user, uint amount);
// MAPPINGS// requestId => genIdmapping(uint256=>uint256) private requestIdToGenId;
// genId => seedmapping(uint256=>uint256) private genSeed;
// genId => tokenIdmapping(uint256=>uint256) private genIdToTokenId;
// bidder => total amount biddedmapping(address=>uint) private allBids;
// CONSTANTSuint256publicconstant MAX_SUPPLY =6_000;
// The gas lane to use, which specifies the maximum gas price to bump to.bytes32privateconstant keyHash =0xff8dedfbfa60af186cf3c830acbc32c05aae823045ae5ea7da1e45fbfaba4f92;
uint32privateconstant callbackGasLimit =100_000;
uint16privateconstant requestConfirmations =3;
// Number of random values to requestuint32privateconstant numWords =1;
// Subscription Id set during deploymentuint64publicconstant s_subscriptionId =747;
// Auction Settingsuintprivateconstant BID_INCREMENT =0.01ether;
uintprivateconstant AUCTION_LENGTH =1weeks;
// Time after auction ends that users can claim their nfts and refunds// Also the time cypher holders have to claim their NFTuintprivateconstant CLAIM_PERIOD =1weeks;
uintprivateconstant BID_EXTENSION_LENGTH =15minutes;
uintprivateconstant BID_INCREASE_PERCENT =10;
ICypher internalconstant CYPHER_CONTRACT = ICypher(0xdDA32aabBBB6c44eFC567baC5F7C35f185338456);
// current genId for mintinguintprivate currentGen;
uintprivate numOfCyphersClaimed;
// Cypher claims equivalent to mapping(uint => bool) private cypherClaims;
LibBitmap.Bitmap private cypherClaims;
// Auction Infouintprivate startedAt;
uintprivate endAt;
uintprivate sumOfAllBids;
address[] private allBidders;
Metadata privateimmutable _metadata;
constructor(Metadata metadata) ERC721A("AMachineForDying", "AMFD") VRFConsumerBaseV2(vrfCoordinator) {
_metadata = metadata;
}
/**
* @dev Reveals all minted tokens that have not been revealed yet.
*/functionreveal() externalonlyOwner{
// Assumes the subscription is funded sufficiently.uint gen = currentGen;
genIdToTokenId[gen] = totalSupply();
currentGen++;
// Will revert if subscription is not set and funded.uint256 s_requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
requestIdToGenId[s_requestId] = gen;
emit RandomnessRequested(gen);
}
/**
* @dev Callback function used by VRF Coordinator.
* @param requestId The request Id used to get the random number.
* @param randomWords The random words generated by the VRF Coordinator.
*/functionfulfillRandomWords(uint256 requestId, /* requestId */uint256[] memory randomWords
) internaloverride{
uint256 randomness = randomWords[0];
uint256 genId = requestIdToGenId[requestId];
delete requestIdToGenId[genId];
genSeed[genId] = randomness;
emit RandomNumberGenerated(genId, randomness);
}
// Step 1 - Cypher Claim/**
* @dev Start the cypher claim period.
*/functionstartCypherClaimPeriod() externalonlyOwner{
// Auction settings
startedAt =block.timestamp+ CLAIM_PERIOD;
endAt =block.timestamp+ CLAIM_PERIOD + AUCTION_LENGTH;
}
/**
* @dev Validate that the cypher can be claimed and that the sender owns the cypher.
* @param tokenId The tokenId to validate.
*/function_validateCypherClaim(uint tokenId) internal{
// Check sender owns the cypher they are claiming forif (msg.sender!= CYPHER_CONTRACT.ownerOf(tokenId)) revert NotOwnerOfCypher(tokenId);
// check the cypher has not already been claimedif (LibBitmap.get(cypherClaims, tokenId)) revert CypherAlreadyClaimed(tokenId);
// set claimed for this cypher to be true
LibBitmap.set(cypherClaims, tokenId);
}
/**
* @dev Claim a free NFT for each cypher you own.
* @param tokenIds The tokenIds to claim for.
*/functionclaimCyphers(uint[] memory tokenIds) external{
// will revert if the claim period hasn't started or if the auction has startedif (block.timestamp>= startedAt) revert CypherClaimNotActive();
uint numOfCyphers = tokenIds.length;
numOfCyphersClaimed += numOfCyphers;
for (uint i =0; i < numOfCyphers;) {
_validateCypherClaim(tokenIds[i]);
unchecked {
++i;
}
}
_mint(msg.sender, numOfCyphers);
}
// Step 2 - Auction/**
* @dev User places a bid in the auction in the form of ETH.
*/functionplaceBid() externalpayable{
// Check the auction has started and hasn't endedif (block.timestamp>= endAt ||block.timestamp< startedAt) revert AuctionNotActive();
uint bidAmount =msg.value;
// msg.value cannot be zeroif (bidAmount ==0) revert CannotBidZero();
// Check the bid increment is correctif (bidAmount % BID_INCREMENT !=0) revert IncorrectBidIncrement(bidAmount);
uint totalBidsFromBidder = bidAmount + allBids[msg.sender];
// Check the bid is large enough to recieve at least 1 NFT at the current priceif (totalBidsFromBidder < getMinimumBid()) revert BidTooSmall(bidAmount);
// reset the timer to 15mins if less than 15mins is remainingif (block.timestamp+ BID_EXTENSION_LENGTH > endAt) {
endAt =block.timestamp+ BID_EXTENSION_LENGTH;
}
// keeptrack of all bidders for distributing NFT's and refunds// if the 2 values are equal then their original bid must be zeroif (bidAmount == totalBidsFromBidder) {
allBidders.push(msg.sender);
}
sumOfAllBids += bidAmount;
allBids[msg.sender] = totalBidsFromBidder;
emit UserPlacesBid(msg.sender, totalBidsFromBidder);
}
/**
* @dev When the auction ends, bidders can claim their NFT's and any remaining ETH.
*/functionclaimAfterAuction() external{
// Check the auction has ended and it is within the claim period (1 week)if (block.timestamp< endAt + BID_EXTENSION_LENGTH ||block.timestamp> endAt + CLAIM_PERIOD) revert AuctionNotOver();
// Check the sender has placed a bid and has not already claimedif (allBids[msg.sender] ==0) revert NoBidToClaim(msg.sender);
uint pricePerUnit = getCurrentPricePerUnit();
uint amount = allBids[msg.sender];
uint quantityToMint = amount / pricePerUnit;
allBids[msg.sender] =0;
if (quantityToMint >0) {
_mint(msg.sender, quantityToMint);
}
uint remainder = amount % pricePerUnit;
(bool success, ) = (msg.sender).call{value: remainder}("");
if (!success) revert TransferNotSuccessful(msg.sender);
}
// Step 3 - Withdraw Remaining NFTsfunctionwithdrawRemainingNFTs(uint amount) externalonlyOwner{
// Check the auction has started, ended and the claim period has passedif (startedAt ==0||block.timestamp< endAt + CLAIM_PERIOD) revert AuctionNotOver();
if (totalSupply() + amount > MAX_SUPPLY) revert TooManyRequested();
// After all nfts have been minted, this will revert// In the rare case that there are no NFTs left after the auction, this will revert
_mint(owner(), amount);
}
// Step 4 - Withdraw/**
* @dev Withdraw the ETH from the contract, but only after all other steps have been completed.
*/functionwithdraw() externalonlyOwner{
if (totalSupply() != MAX_SUPPLY) revert NftsNotAllMinted();
(bool success, ) =msg.sender.call{value: address(this).balance}("");
if (!success) revert TransferFailed();
}
// Getters/ View Functions/**
* @dev Get the seed for a given tokenId.
* @param tokenId The tokenId to get the seed for.
* @return The seed(random number) for the given tokenId.
*/functiongetSeed(uint256 tokenId) publicviewreturns (uint256) {
if (tokenId >= totalSupply()) revert InvalidTokenId(tokenId);
for (uint i =0; i < currentGen;) {
if (tokenId < genIdToTokenId[i]) {
uint seed = genSeed[i];
returnuint256(keccak256(abi.encodePacked(seed, tokenId)));
}
unchecked {
++i;
}
}
return0;
}
/**
* @dev Get the metadata for a given tokenId.
* @param tokenId The tokenId to get the metadata for.
* @return The metadata for the given tokenId.
*/functiontokenURI(uint256 tokenId) publicviewoverridereturns (stringmemory) {
uint seed = getSeed(tokenId);
if (seed ==0) {
return"ipfs://QmTJf1jnE2E8iMtVdVvdcCUwC1D8kJ4Qktise1XM1CfvyS";
}
return _metadata.buildMetadata(tokenId, seed);
}
/**
* @dev Get the current price per unit.
* @return The current price per unit.
*/functiongetCurrentPricePerUnit() publicviewreturns (uint) {
return sumOfAllBids / (MAX_SUPPLY - numOfCyphersClaimed);
}
/**
* @dev Get the minimum bid.
* @return The minimum bid.
*/functiongetMinimumBid() publicviewreturns (uint) {
uint minimum = getCurrentPricePerUnit() + getCurrentPricePerUnit() / BID_INCREASE_PERCENT;
if (minimum <= BID_INCREMENT) {
return BID_INCREMENT;
} else {
return minimum - minimum % BID_INCREMENT + BID_INCREMENT;
}
}
/**
* @dev Get all bidders.
* @return An array of all bidders.
*/functiongetAllBidders() externalviewreturns (address[] memory) {
return allBidders;
}
/**
* @dev Get the total amount of bids for a given bidder, assuming they have not claimed.
* @param bidder The bidder to get the total amount of bids for.
* @return The total amount of bids for the given bidder.
*/functiongetUserBid(address bidder) externalviewreturns (uint) {
return allBids[bidder];
}
/**
* @dev Get when the auction started
* @return The timestamp when the auction started.
*/functiongetStartTimestamp() externalviewreturns(uint) {
return startedAt;
}
/**
* @dev Get when the auction is currently scheduled to end. This may be extended if a bid is placed in the last 15mins.
* @return The timestamp when the auction ends.
*/functiongetEndTimestamp() externalviewreturns(uint) {
return endAt;
}
/**
* @dev check if an individual cypher claim has been claimed
* @param tokenId The tokenId to check if it has been claimed.
* @return true if the given tokenId has been claimed.
*/functiongetIfCypherClaimed(uint tokenId) externalviewreturns(bool) {
return LibBitmap.get(cypherClaims, tokenId);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 6 of 24: ERC721A.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.2.3// Creator: Chiru Labspragmasolidity ^0.8.4;import'./IERC721A.sol';
/**
* @dev Interface of ERC721 token receiver.
*/interfaceERC721A__IERC721Receiver{
functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
/**
* @title ERC721A
*
* @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
* Non-Fungible Token Standard, including the Metadata extension.
* Optimized for lower gas during batch mints.
*
* Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
* starting from `_startTokenId()`.
*
* Assumptions:
*
* - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
* - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
*/contractERC721AisIERC721A{
// Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).structTokenApprovalRef {
address value;
}
// =============================================================// CONSTANTS// =============================================================// Mask of an entry in packed address data.uint256privateconstant _BITMASK_ADDRESS_DATA_ENTRY = (1<<64) -1;
// The bit position of `numberMinted` in packed address data.uint256privateconstant _BITPOS_NUMBER_MINTED =64;
// The bit position of `numberBurned` in packed address data.uint256privateconstant _BITPOS_NUMBER_BURNED =128;
// The bit position of `aux` in packed address data.uint256privateconstant _BITPOS_AUX =192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.uint256privateconstant _BITMASK_AUX_COMPLEMENT = (1<<192) -1;
// The bit position of `startTimestamp` in packed ownership.uint256privateconstant _BITPOS_START_TIMESTAMP =160;
// The bit mask of the `burned` bit in packed ownership.uint256privateconstant _BITMASK_BURNED =1<<224;
// The bit position of the `nextInitialized` bit in packed ownership.uint256privateconstant _BITPOS_NEXT_INITIALIZED =225;
// The bit mask of the `nextInitialized` bit in packed ownership.uint256privateconstant _BITMASK_NEXT_INITIALIZED =1<<225;
// The bit position of `extraData` in packed ownership.uint256privateconstant _BITPOS_EXTRA_DATA =232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.uint256privateconstant _BITMASK_EXTRA_DATA_COMPLEMENT = (1<<232) -1;
// The mask of the lower 160 bits for addresses.uint256privateconstant _BITMASK_ADDRESS = (1<<160) -1;
// The maximum `quantity` that can be minted with {_mintERC2309}.// This limit is to prevent overflows on the address data entries.// For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}// is required to cause an overflow, which is unrealistic.uint256privateconstant _MAX_MINT_ERC2309_QUANTITY_LIMIT =5000;
// The `Transfer` event signature is given by:// `keccak256(bytes("Transfer(address,address,uint256)"))`.bytes32privateconstant _TRANSFER_EVENT_SIGNATURE =0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
// =============================================================// STORAGE// =============================================================// The next token ID to be minted.uint256private _currentIndex;
// The number of tokens burned.uint256private _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 {_packedOwnershipOf} implementation for details.//// Bits Layout:// - [0..159] `addr`// - [160..223] `startTimestamp`// - [224] `burned`// - [225] `nextInitialized`// - [232..255] `extraData`mapping(uint256=>uint256) private _packedOwnerships;
// Mapping owner address to address data.//// Bits Layout:// - [0..63] `balance`// - [64..127] `numberMinted`// - [128..191] `numberBurned`// - [192..255] `aux`mapping(address=>uint256) private _packedAddressData;
// Mapping from token ID to approved address.mapping(uint256=> TokenApprovalRef) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
// =============================================================// CONSTRUCTOR// =============================================================constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
// =============================================================// TOKEN COUNTING OPERATIONS// =============================================================/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/function_startTokenId() internalviewvirtualreturns (uint256) {
return0;
}
/**
* @dev Returns the next token ID to be minted.
*/function_nextTokenId() internalviewvirtualreturns (uint256) {
return _currentIndex;
}
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see {_totalMinted}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented// more than `_currentIndex - _startTokenId()` times.unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/function_totalMinted() internalviewvirtualreturns (uint256) {
// Counter underflow is impossible as `_currentIndex` does not decrement,// and it is initialized to `_startTokenId()`.unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/function_totalBurned() internalviewvirtualreturns (uint256) {
return _burnCounter;
}
// =============================================================// ADDRESS DATA OPERATIONS// =============================================================/**
* @dev Returns the number of tokens in `owner`'s account.
*/functionbalanceOf(address owner) publicviewvirtualoverridereturns (uint256) {
if (owner ==address(0)) revert BalanceQueryForZeroAddress();
return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/function_numberMinted(address owner) internalviewreturns (uint256) {
return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/function_numberBurned(address owner) internalviewreturns (uint256) {
return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
*/function_getAux(address owner) internalviewreturns (uint64) {
returnuint64(_packedAddressData[owner] >> _BITPOS_AUX);
}
/**
* Sets the auxiliary 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) internalvirtual{
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.assembly {
auxCasted := aux
}
packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
_packedAddressData[owner] = packed;
}
// =============================================================// IERC165// =============================================================/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
// The interface IDs are constants representing the first 4 bytes// of the XOR of all function selectors in the interface.// See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)// (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)return
interfaceId ==0x01ffc9a7||// ERC165 interface ID for ERC165.
interfaceId ==0x80ac58cd||// ERC165 interface ID for ERC721.
interfaceId ==0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}
// =============================================================// IERC721Metadata// =============================================================/**
* @dev Returns the token collection name.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the token collection symbol.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length!=0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}
/**
* @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, it can be overridden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return'';
}
// =============================================================// OWNERSHIPS OPERATIONS// =============================================================/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
returnaddress(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @dev Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around over time.
*/function_ownershipOf(uint256 tokenId) internalviewvirtualreturns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Returns the unpacked `TokenOwnership` struct at `index`.
*/function_ownershipAt(uint256 index) internalviewvirtualreturns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/function_initializeOwnershipAt(uint256 index) internalvirtual{
if (_packedOwnerships[index] ==0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Returns the packed ownership data of `tokenId`.
*/function_packedOwnershipOf(uint256 tokenId) privateviewreturns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
// If not burned.if (packed & _BITMASK_BURNED ==0) {
// If the data at the starting slot does not exist, start the scan.if (packed ==0) {
if (tokenId >= _currentIndex) revert OwnerQueryForNonexistentToken();
// Invariant:// There will always be an initialized ownership slot// (i.e. `ownership.addr != address(0) && ownership.burned == false`)// before an unintialized ownership slot// (i.e. `ownership.addr == address(0) && ownership.burned == false`)// Hence, `tokenId` will not underflow.//// We can directly compare the packed value.// If the address is zero, packed will be zero.for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed ==0) continue;
return packed;
}
}
// Otherwise, the data exists and is not burned. We can skip the scan.// This is possible because we have already achieved the target condition.// This saves 2143 gas on transfers of initialized tokens.return packed;
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev Returns the unpacked `TokenOwnership` struct from `packed`.
*/function_unpackedOwnership(uint256 packed) privatepurereturns (TokenOwnership memory ownership) {
ownership.addr =address(uint160(packed));
ownership.startTimestamp =uint64(packed >> _BITPOS_START_TIMESTAMP);
ownership.burned = packed & _BITMASK_BURNED !=0;
ownership.extraData =uint24(packed >> _BITPOS_EXTRA_DATA);
}
/**
* @dev Packs ownership data into a single uint256.
*/function_packOwnershipData(address owner, uint256 flags) privateviewreturns (uint256 result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner :=and(owner, _BITMASK_ADDRESS)
// `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
result :=or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
/**
* @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
*/function_nextInitializedFlag(uint256 quantity) privatepurereturns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.assembly {
// `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
result :=shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
// =============================================================// APPROVAL OPERATIONS// =============================================================/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
*/functionapprove(address to, uint256 tokenId) publicpayablevirtualoverride{
_approve(to, tokenId, true);
}
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId].value;
}
/**
* @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) publicvirtualoverride{
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @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. See {_mint}.
*/function_exists(uint256 tokenId) internalviewvirtualreturns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex &&// If within bounds,
_packedOwnerships[tokenId] & _BITMASK_BURNED ==0; // and not burned.
}
/**
* @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
*/function_isSenderApprovedOrOwner(address approvedAddress,
address owner,
address msgSender
) privatepurereturns (bool result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner :=and(owner, _BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
msgSender :=and(msgSender, _BITMASK_ADDRESS)
// `msgSender == owner || msgSender == approvedAddress`.
result :=or(eq(msgSender, owner), eq(msgSender, approvedAddress))
}
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/function_getApprovedSlotAndAddress(uint256 tokenId)
privateviewreturns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress :=sload(approvedAddressSlot)
}
}
// =============================================================// TRANSFER OPERATIONS// =============================================================/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) publicpayablevirtualoverride{
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) !=from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to ==address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.sstore(approvedAddressSlot, 0)
}
}
// 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 {
// We can directly increment and decrement the balances.--_packedAddressData[from]; // Updates: `balance -= 1`.++_packedAddressData[to]; // Updates: `balance += 1`.// Updates:// - `address` to the next owner.// - `startTimestamp` to the timestamp of transfering.// - `burned` to `false`.// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED ==0) {
uint256 nextTokenId = tokenId +1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).if (_packedOwnerships[nextTokenId] ==0) {
// If the next slot is within bounds.if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicpayablevirtualoverride{
safeTransferFrom(from, to, tokenId, '');
}
/**
* @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,
bytesmemory _data
) publicpayablevirtualoverride{
transferFrom(from, to, tokenId);
if (to.code.length!=0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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{}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* `from` - Previous owner of the given token ID.
* `to` - Target address that will receive the token.
* `tokenId` - Token ID to be transferred.
* `_data` - Optional data to send along with the call.
*
* Returns whether the call correctly returned the expected magic value.
*/function_checkContractOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory _data
) privatereturns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
// =============================================================// MINT OPERATIONS// =============================================================/**
* @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 for each mint.
*/function_mint(address to, uint256 quantity) internalvirtual{
uint256 startTokenId = _currentIndex;
if (quantity ==0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.// `balance` and `numberMinted` have a maximum limit of 2**64.// `tokenId` has a maximum limit of 2**256.unchecked {
// Updates:// - `balance += quantity`.// - `numberMinted += quantity`.//// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1<< _BITPOS_NUMBER_MINTED) |1);
// Updates:// - `address` to the owner.// - `startTimestamp` to the timestamp of minting.// - `burned` to `false`.// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 toMasked;
uint256 end = startTokenId + quantity;
// Use assembly to loop and emit the `Transfer` event for gas savings.// The duplicated `log4` removes an extra check and reduces stack juggling.// The assembly, together with the surrounding Solidity code, have been// delicately arranged to nudge the compiler into producing optimized opcodes.assembly {
// Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
toMasked :=and(to, _BITMASK_ADDRESS)
// Emit the `Transfer` event.log4(
0, // Start of data (0, since no data).0, // End of data (0, since no data).
_TRANSFER_EVENT_SIGNATURE, // Signature.0, // `address(0)`.
toMasked, // `to`.
startTokenId // `tokenId`.
)
// The `iszero(eq(,))` check ensures that large values of `quantity`// that overflows uint256 will make the loop run out of gas.// The compiler will optimize the `iszero` away for performance.for {
let tokenId :=add(startTokenId, 1)
} iszero(eq(tokenId, end)) {
tokenId :=add(tokenId, 1)
} {
// Emit the `Transfer` event. Similar to above.log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
}
}
if (toMasked ==0) revert MintToZeroAddress();
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* This function is intended for efficient minting only during contract creation.
*
* It emits only one {ConsecutiveTransfer} as defined in
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
* instead of a sequence of {Transfer} event(s).
*
* Calling this function outside of contract creation WILL make your contract
* non-compliant with the ERC721 standard.
* For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
* {ConsecutiveTransfer} event is only permissible during contract creation.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {ConsecutiveTransfer} event.
*/function_mintERC2309(address to, uint256 quantity) internalvirtual{
uint256 startTokenId = _currentIndex;
if (to ==address(0)) revert MintToZeroAddress();
if (quantity ==0) revert MintZeroQuantity();
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are unrealistic due to the above check for `quantity` to be below the limit.unchecked {
// Updates:// - `balance += quantity`.// - `numberMinted += quantity`.//// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1<< _BITPOS_NUMBER_MINTED) |1);
// Updates:// - `address` to the owner.// - `startTimestamp` to the timestamp of minting.// - `burned` to `false`.// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity -1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, 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.
*
* See {_mint}.
*
* Emits a {Transfer} event for each mint.
*/function_safeMint(address to,
uint256 quantity,
bytesmemory _data
) internalvirtual{
_mint(to, quantity);
unchecked {
if (to.code.length!=0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.if (_currentIndex != end) revert();
}
}
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/function_safeMint(address to, uint256 quantity) internalvirtual{
_safeMint(to, quantity, '');
}
// =============================================================// APPROVAL OPERATIONS// =============================================================/**
* @dev Equivalent to `_approve(to, tokenId, false)`.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_approve(to, tokenId, false);
}
/**
* @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:
*
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/function_approve(address to,
uint256 tokenId,
bool approvalCheck
) internalvirtual{
address owner = ownerOf(tokenId);
if (approvalCheck)
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId].value= to;
emit Approval(owner, to, tokenId);
}
// =============================================================// BURN OPERATIONS// =============================================================/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/function_burn(uint256 tokenId) internalvirtual{
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId, bool approvalCheck) internalvirtual{
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
addressfrom=address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.sstore(approvedAddressSlot, 0)
}
}
// 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 {
// Updates:// - `balance -= 1`.// - `numberBurned += 1`.//// We can directly decrement the balance, and increment the number burned.// This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
_packedAddressData[from] += (1<< _BITPOS_NUMBER_BURNED) -1;
// Updates:// - `address` to the last owner.// - `startTimestamp` to the timestamp of burning.// - `burned` to `true`.// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED ==0) {
uint256 nextTokenId = tokenId +1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).if (_packedOwnerships[nextTokenId] ==0) {
// If the next slot is within bounds.if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.unchecked {
_burnCounter++;
}
}
// =============================================================// EXTRA DATA OPERATIONS// =============================================================/**
* @dev Directly sets the extra data for the ownership data `index`.
*/function_setExtraDataAt(uint256 index, uint24 extraData) internalvirtual{
uint256 packed = _packedOwnerships[index];
if (packed ==0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
/**
* @dev Called during each token transfer to set the 24bit `extraData` field.
* Intended to be overridden by the cosumer contract.
*
* `previousExtraData` - the value of `extraData` before transfer.
*
* 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_extraData(addressfrom,
address to,
uint24 previousExtraData
) internalviewvirtualreturns (uint24) {}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/function_nextExtraData(addressfrom,
address to,
uint256 prevOwnershipPacked
) privateviewreturns (uint256) {
uint24 extraData =uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
returnuint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
}
// =============================================================// OTHER OPERATIONS// =============================================================/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/function_msgSenderERC721A() internalviewvirtualreturns (address) {
returnmsg.sender;
}
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/function_toString(uint256 value) internalpurevirtualreturns (stringmemory str) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.// We will need 1 word for the trailing zeros padding, 1 word for the length,// and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.let m :=add(mload(0x40), 0xa0)
// Update the free memory pointer to allocate.mstore(0x40, m)
// Assign the `str` to the end.
str :=sub(m, 0x20)
// Zeroize the slot after the string.mstore(str, 0)
// Cache the end of the memory to calculate the length later.let end := str
// We write the string from rightmost digit to leftmost digit.// The following is essentially a do-while loop that also handles the zero case.// prettier-ignorefor { let temp := value } 1 {} {
str :=sub(str, 1)
// Write the character to the pointer.// The ASCII index of the '0' character is 48.mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp :=div(temp, 10)
// prettier-ignoreifiszero(temp) { break }
}
let length :=sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str :=sub(str, 0x20)
// Store the length.mstore(str, length)
}
}
}
Contract Source Code
File 7 of 24: Environment.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"./GridHelper.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
libraryEnvironment{
uintinternalconstant TOTAL_BASIC_COLOURS =5;
uintinternalconstant TOTAL_EMBELLISHED_COLOURS =6;
uintinternalconstant TOTAL_DEGRADED_COLOURS =8; // includes grey// LW, RW, FLOORstringinternalconstant EXECUTIVE_COLOUR_PERCENTAGES ="040020025000070000";
stringinternalconstant LAB_COLOUR_PERCENTAGES ="040020025000070000";
stringinternalconstant FACTORY_COLOUR_PERCENTAGES ="040020025000070000";
// Darker Gray, Orange, Dark Gray, Red, Light Gray, Orange, Lightest Gray, Redstringinternalconstant EXECUTIVE_DEGRADED_HSL ="120001015120001035120001061120002088019068078019032045019058048002047049";
stringinternalconstant LAB_DEGRADED_HSL ="120001015120001035120001061120002088156015049050047054276021058155037049";
stringinternalconstant FACTORY_DEGRADED_HSL ="120001015120001035120001061120002088021042074203032059319029046243031039";
// EXECUTIVE// Combined without shadesstringinternalconstant EXECUTIVE_COLOURS_BASIC ="000000069240003029000000069240003029000000069000000069240003013000000069354100060240003013000000069240003013240003029047100050240003013240003029240003013240003029121082050240003013240003029240003013240003029221082050240003013354100060000100004000100004022100050041100050047100050021081004021081004030100013022100045221081088194090077200075078195086089200084076";
stringinternalconstant EXECUTIVE_COLOURS_EMBELLISHED ="121082050093090004099074009095085054099075072093090004221082050194089004199074009195085054199075080194089004339082050314089004317074009313085054318075084314089004357061040040091044040091062040091044040091062040091044137093049197100052287100053347100053047100052287100053259100052184100052083100052050100050000100050083100052093063053082084048066100048053100050036100050066100048060087053061100042070100040101055042165100025070100040";
// Combined with shadesstringinternalconstant EXECUTIVE_COLOURS_BASIC_SHADE ="000000050240003029000000050240003029000000050000000050240003029000000050000086027240003029000000050240003029240003013047100032240003029240003013240003029240003013104079046240003029240003013240003029240003013204079046240003029000086027000061010000100007013091043041100045047100032022080008022081012030100015022100040204079087196071077180054080195093089195095092";
stringinternalconstant EXECUTIVE_COLOURS_EMBELLISHED_SHADE ="104079046096071004080054015095093054095096068096071004204079046196071004180054015195093054195096068196071004322079046316071004299054015313093054313096068316071004357078056040091062040091044040091062040091044040091062168100054257100053317100053017100052047100056317100053284100052212092052155100052068100052032100050155100052093063057093068048075100048058100050047100050075100048060100062061100044065100041081077041137055037065100041";
// LAB// Combined without shadesstringinternalconstant LAB_COLOURS_BASIC ="185053039180055056185053039180095040181066049231095074252070052231095074210049067030100050168056095228081062168056095051093072182081087240060097253081078240060097224062081245080083352033081165032066027028078027033080037031079143014078000000100143014078237045053183099034207099060207099060040090096239066051176077048221081088194090077200075078195086089200084076";
stringinternalconstant LAB_COLOURS_EMBELLISHED ="158100077228081062168056095051093072182081087168056095238100086253081078240060097224062081245080083253081078190054036252070052231095074210049067030100050252070052144090033040091044040091062040091044040091062040091044287100053047100052137093049347100053197100052287100053000100050050100050083100052184100052259100052083100052036100050053100050066100048082084048093063053082084048165100025101055042070100040061100042060087053070100040";
// Combined with shadesstringinternalconstant LAB_COLOURS_BASIC_SHADE ="181085042184045075181085042180059062181062052251085079251073027251085079211053076030100050182081087229047032182081087051090084180064063242083093252047060242083093224058089244079072004029080164031070021030079022034081023028075143014068183100080143014068237045048183099028239066051207099060041090092238072019176077048204079087196071077180054080195093089195095092";
stringinternalconstant LAB_COLOURS_EMBELLISHED_SHADE ="169048056229047032182081087051090084180064063182081087241047074252047060242083093224058089244079072252047060184021040251073027251085079211053076030100050251073027147089054040091062040091044040091062040091044040091062317100053047100056168100054017100052257100053317100053032100050068100052155100052212092052284100052155100052047100050058100050075100048093068048093063057093068048137055037081077041065100041061100044060100062065100041";
// FACTORY// Combined without shadesstringinternalconstant FACTORY_COLOURS_BASIC ="232053033232052058232054032232051037232058059196085079193083063193048054193064047193089055231032035196085079231032035300085082000000085249069060196085079231032035300085082000000085266083081162085079197031035266083081000000085033098060196085068231032035196085068000000085300085082196085079231032035033100052000000085221081088194090077200075078195086089200084076";
stringinternalconstant FACTORY_COLOURS_EMBELLISHED ="160073059280078043280077074340097062160071039280078043280094041340086057280084075340084055340087027340086057162085079266083081266083081197031035000000085266083081220067026040091044040091072040091044040091072040091044197100052287100053137093049347100053047100052287100053083100052050100050000100050259100052184100052050100050082084048066100048036100050053100050093063053082084048101055042070100040165100025060087053061100042070100040";
// Combined with shadesstringinternalconstant FACTORY_COLOURS_BASIC_SHADE ="232066056233054034232066067232071029232091066196084068193045040193073053193067051193070044229034024193083063229034024033098060000000052243039046193083063229034024033098060000000052359097059159084063195034025266086072000000052033098044193083052229034024193083052000000052321076067193083063229034024033098060000000052204079087196071077180054080195093089195095092";
stringinternalconstant FACTORY_COLOURS_EMBELLISHED_SHADE ="243039046300085082193083063229034024000000052300085082249069060033098060196085079231032035000000085033098060159084063359097059266086072195034025000000052359097059220096052040091072040091044040091072040091044220087032257100053317100053168100054017100052047100056317100053155100052068100052032100050284100052212092052068100052093068048075100048047100050058100050093063057093068048081077041065100041137055037060100062061100044065100041";
stringinternalconstant DEGRADED_COLOUR_PERCENTAGES ="064115153191217237251256";
stringinternalconstant BASIC_COLOUR_PERCENTAGES ="064115153191217237251256";
stringinternalconstant EMBELLISHED_COLOUR_PERCENTAGES ="064115153191217237251256";
functionincreaseValueByPercentage(uint baseLightness, uint percentage) internalpurereturns(uint) {
uint value = baseLightness + (baseLightness * percentage /100);
if (value >100) {
value =100;
}
return value;
}
functiondecreaseValueByPercentage(uint baseLightness, uint percentage) internalpurereturns (uint) {
return baseLightness - (baseLightness * percentage /100);
}
functiongetColours(stringmemory machine, uint baseValue) externalpurereturns (uint[] memory) {
uint[] memory colourArray =newuint[](36); // 6 colours, 3*2 values eachuint colourIndex = getColourIndex(baseValue);
if (colourIndex <8) { // degraded
colourArray = getDegradedShell(colourArray, machine, baseValue);
} else { // basic or embellished
colourArray = getBasicEmbelishedShell(colourArray, machine, baseValue);
}
return colourArray;
}
functiongetColourIndex(uint baseValue) internalpurereturns(uint) {
uint[] memory colourProbabilitiesArray = GridHelper.createEqualProbabilityArray(24);
uint index =100;
for (uint i =0; i < colourProbabilitiesArray.length; ++i) {
if (baseValue < colourProbabilitiesArray[i]) {
index = i;
break;
}
}
if (index ==100) {
index =23;
}
return index;
}
functionselectBasicEmbellishedPalette(stringmemory machine, uint baseValue) internalpurereturns (string[] memory) {
string[] memory basicPalette =newstring[](2);
uint index = getColourIndex(baseValue);
uint state =2;
if (index <16) {
state =1;
}
index = index %8;
uint size;
if (state ==1) {
size = TOTAL_BASIC_COLOURS *9;
} else {
size = TOTAL_EMBELLISHED_COLOURS *9;
}
// could be simplified by storing every colour in a single string but this is more readable and easier to changeif (keccak256(bytes(machine)) ==keccak256(bytes("Altar"))) { // executiveif (state ==1) {
basicPalette[0] =string(GridHelper.slice(bytes(EXECUTIVE_COLOURS_BASIC), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(EXECUTIVE_COLOURS_BASIC_SHADE), index * size, size));
} else {
basicPalette[0] =string(GridHelper.slice(bytes(EXECUTIVE_COLOURS_EMBELLISHED), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(EXECUTIVE_COLOURS_EMBELLISHED_SHADE), index * size, size));
}
} elseif (keccak256(bytes(machine)) ==keccak256(bytes("Apparatus")) ||keccak256(bytes(machine)) ==keccak256(bytes("Cells"))) { // labif (state ==1) {
basicPalette[0] =string(GridHelper.slice(bytes(LAB_COLOURS_BASIC), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(LAB_COLOURS_BASIC_SHADE), index * size, size));
} else {
basicPalette[0] =string(GridHelper.slice(bytes(LAB_COLOURS_EMBELLISHED), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(LAB_COLOURS_EMBELLISHED_SHADE), index * size, size));
}
} else { // factoryif (state ==1) {
basicPalette[0] =string(GridHelper.slice(bytes(FACTORY_COLOURS_BASIC), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(FACTORY_COLOURS_BASIC_SHADE), index * size, size));
} else {
basicPalette[0] =string(GridHelper.slice(bytes(FACTORY_COLOURS_EMBELLISHED), index * size, size));
basicPalette[1] =string(GridHelper.slice(bytes(FACTORY_COLOURS_EMBELLISHED_SHADE), index * size, size));
}
}
return basicPalette;
}
functiongetDegradedShell(uint[] memory colourArray, stringmemory machine, uint baseValue) internalpurereturns (uint[] memory) {
stringmemory degradedHsl;
stringmemory degradedPercentages;
if (keccak256(bytes(machine)) ==keccak256(bytes("Altar"))) { // executive
degradedHsl = EXECUTIVE_DEGRADED_HSL;
degradedPercentages = EXECUTIVE_COLOUR_PERCENTAGES;
} elseif (keccak256(bytes(machine)) ==keccak256(bytes("Apparatus")) ||keccak256(bytes(machine)) ==keccak256(bytes("Cells"))) { // lab
degradedHsl = LAB_DEGRADED_HSL;
degradedPercentages = LAB_COLOUR_PERCENTAGES;
} else { // factory
degradedHsl = FACTORY_DEGRADED_HSL;
degradedPercentages = FACTORY_COLOUR_PERCENTAGES;
}
uint index = getColourIndex(baseValue);
uint[] memory singleColour =newuint[](3); // h, s, lfor (uint i =0; i <3; ++i) {
singleColour[i] = GridHelper.stringToUint(string(GridHelper.slice(bytes(degradedHsl), (index)*9+3*i, 3))); // 9 = h,s,l to 3 significant digits
}
uint[] memory colourPercentages = GridHelper.setUintArrayFromString(degradedPercentages, 6, 3);
for (uint i =0; i <12; ++i) { // 12 = 6 colours, 2 values each
colourArray[i*3] = singleColour[0];
colourArray[i*3+1] = singleColour[1];
colourArray[i*3+2] = increaseValueByPercentage(singleColour[2], colourPercentages[i%6]);
}
return colourArray;
}
functiongetBasicEmbelishedShell(uint[] memory colourArray, stringmemory machine, uint baseValue) internalpurereturns (uint[] memory) {
uint index = getColourIndex(baseValue);
uint state =2;
if (index <16) {
state =1;
}
uint numColours;
if (state ==1) {
numColours = TOTAL_BASIC_COLOURS;
} else {
numColours = TOTAL_EMBELLISHED_COLOURS;
}
string[] memory colourAvailableStrings = selectBasicEmbellishedPalette(machine, baseValue);
uint[] memory coloursAvailable = GridHelper.setUintArrayFromString(colourAvailableStrings[0], numColours*3, 3);
uint[] memory coloursAvailableShade = GridHelper.setUintArrayFromString(colourAvailableStrings[1], numColours*3, 3);
for (uint i =0; i <6; ++i) {
for (uint j =0; j <3; ++j) { // j = h, s, l// Duplicate colours for linear gradient
colourArray[2*i*3+j] = coloursAvailable[3*(i % numColours) + j];
colourArray[(2*i+1)*3+j] = coloursAvailableShade[3*(i % numColours) + j];
}
}
return colourArray;
}
}
Contract Source Code
File 8 of 24: GlobalNumbers.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"./GridHelper.sol";
import"./Noise.sol";
libraryGlobalNumbers{
uintinternalconstant FLIPPER_WRAPPER_NUMBER =13010;
uintinternalconstant CHAR_MASK_GROUP_NUMBER =14006;
uintinternalconstant GROUP_CLOSE_NUMBER =13000;
// Small Asset numbers// 00000 - None// 06022 - Rat// 06021 - Skull// 06028 - Dead Plant// 06014 - Dog Bowl// 06027 - Bottle// 06026 - Can// 06006 - Bong// 06004 - Martini// 06011 - Books// 06000 - Lavalamp// 06025 - Pineapple// 06029 - Watermelon// 06020 - Lizardstringinternalconstant SMALL_ASSET_NUMBERS ="0000006022060210602806014060270602606006060040601106000060250602906020";
// Large Asset numbers// 00000 - None// 02002 - Pit// 06013 - Toilet// 02001 - Pit with Grate// 02009 - Spikes B// 02008 - Spikes A// 02004 - Ladder// 02003 - Stairs// 06008 - Fridge// 06019 - Stool// 06009 - Circular Rug// 06023 - Desk Chair// 06024 - Cactus (Large)// 06030 - Gramaphone// 06018 - Cello// 06017 - Harpstringinternalconstant LARGE_ASSET_NUMBERS ="00000020020601302001020090200802004020030600806019060090602306024060300601806017";
// Out Wall numbers// 06005 - Peephole A// 06007 - Peephole B// 06016 - Megaphone// 06010 - CCTVstringinternalconstant OUT_WALL_NUMBERS ="0000006005060070601606010";
// Flat Wall numbers// 02000 - Crack// 02011 - Numbers// 02007 - Recess C// 02006 - Recess B// 02005 - Recess A// 02010 - Wall Rugstringinternalconstant FLAT_WALL_NUMBERS ="00000020000201102007020060200502010";
// Expansion Props - 9 values// None// Crack// Recess A// Recess B// Recess C// Pit// Grate// Stairs// Ladderstringinternalconstant EXPANSION_PROPS_NUMBERS ="000000200002005020060200702002020010200302004";
// Character Lever - 8 values// LEVER D// LEVER C// LEVER B// LEVER A// DETAILED LEVER D// DETAILED LEVER C// DETAILED LEVER B// DETAILED LEVER Astringinternalconstant CHARACTER_LEVER_NUMBERS ="0300003001030020300303016030170301803019";
// Character - 7 values// 00000 - None// 14002 - COLLAPSED// 14005 - HUNCHED// 14003 - SLOUCHED// 14001 - STANDING// 14000 - SITTING// 14004 - MEDITATINGstringinternalconstant CHARACTER_NUMBERS ="00000140021400514003140011400014004";
/**
* @dev Returns the small asset number based on the digits
* @param rand The digits to use
* @return The small asset number
*/functiongetSmallAssetNumber(uint rand, int baseline) externalpurereturns (uint) {
uint smallAssetDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 20)] + baseline);
return GridHelper.getSingleObject(SMALL_ASSET_NUMBERS, smallAssetDigits, 14, 5);
}
/**
* @dev Returns the large asset number based on the digits
* @param rand The digits to use
* @return The large asset number
*/functiongetLargeAssetNumber(uint rand, int baseline) externalpurereturns (uint) {
uint largeAssetDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 21)] + baseline);
return GridHelper.getSingleObject(LARGE_ASSET_NUMBERS, largeAssetDigits, 16, 5);
}
/**
* @dev Returns the out wall number based on the digits
* @param rand The digits to use
* @return The out wall number
*/functiongetOutWallNumber(uint rand, int baseline) externalpurereturns (uint) {
uint outWallDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 22)] + baseline);
return GridHelper.getSingleObject(OUT_WALL_NUMBERS, outWallDigits, 5, 5);
}
/**
* @dev Returns the flat wall number based on the digits
* @param rand The digits to use
* @return The flat wall number
*/functiongetFlatWallNumber(uint rand, int baseline) externalpurereturns (uint) {
uint flatWallDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 23)] + baseline);
return GridHelper.getSingleObject(FLAT_WALL_NUMBERS, flatWallDigits, 7, 5);
}
/**
* @dev Returns the character lever number based on the digits and state
* @param rand The digits to use
* @return The character lever number
*/functiongetCharacterLeverNumber(uint rand, int baseline) internalpurereturns (uint) {
uint characterLeverDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 30)] + baseline);
return GridHelper.getSingleObject(CHARACTER_LEVER_NUMBERS, characterLeverDigits, 8, 5);
}
/**
* @dev Returns the character number based on the digits and state
* @param rand The digits to use
* @return The character number
*/functiongetCharacterNumber(uint rand, int baseline) internalpurereturns (uint) {
uint characterDigits = GridHelper.constrainToHex(Noise.getNoiseArrayTwo()[GridHelper.getRandByte(rand, 31)] + baseline);
return GridHelper.getSingleObject(CHARACTER_NUMBERS, characterDigits, 7, 5);
}
/**
* @dev Returns the character number and lever number based on the digits and state
* @param rand The digits to use
* @param flip Whether to flip the character
* @return The character number and lever numbers
*/functiongetCharacterNumberAndLeverNumber(uint rand, bool flip, int baseline) externalpurereturns (uint[5] memory) {
uint characterNumber = getCharacterNumber(rand, baseline);
uint characterLeverNumber = getCharacterLeverNumber(rand, baseline);
uint armMask =0;
if (characterNumber ==14001|| characterNumber ==14003|| characterNumber ==14005) {
armMask = CHAR_MASK_GROUP_NUMBER;
}
uint flipOpen =0;
uint flipClose =0;
if (flip) {
flipOpen = FLIPPER_WRAPPER_NUMBER;
flipClose = GROUP_CLOSE_NUMBER;
}
return [flipOpen, characterLeverNumber, armMask, characterNumber, flipClose];
}
/**
* @dev Returns the expansion prop number based on the digits
* @param rand The digits to use
* @param baseline The baseline to use
* @param offsetNumbers The offset numbers to use
* @param numOptions The number of options
* @return The expansion prop number
*/functiongetSingleOffset(uint rand, int baseline, stringmemory offsetNumbers, uint numOptions) externalpurereturns (stringmemory) {
uint offsetDigits1 = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 20)] + baseline);
uint offsetDigits2 = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 21)] + baseline);
uint offsetDigits3 = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 22)] + baseline);
uint finalOffsetDigits = (offsetDigits1 + offsetDigits2 + offsetDigits3) /3;
returnstring(GridHelper.slice(bytes(offsetNumbers), (finalOffsetDigits % numOptions)*8, 8));
}
}
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"@openzeppelin/contracts/utils/Strings.sol";
libraryGridHelper{
uint256publicconstant MAX_GRID_INDEX =8;
/**
* @dev slice array of bytes
* @param data The array of bytes to slice
* @param start The start index
* @param len The length of the slice
* @return The sliced array of bytes
*/functionslice(bytesmemory data, uint256 start, uint256 len) internalpurereturns (bytesmemory) {
bytesmemory b =newbytes(len);
for (uint256 i =0; i < len; i++) {
b[i] = data[i + start];
}
return b;
}
/**
* @dev combine two arrays of strings
* @param a The first array
* @param b The second array
* @return The combined array
*/functioncombineStringArrays(string[] memory a, string[] memory b) publicpurereturns (string[] memory) {
string[] memory c =newstring[](a.length+ b.length);
for (uint256 i =0; i < a.length; i++) {
c[i] = a[i];
}
for (uint256 i =0; i < b.length; i++) {
c[i + a.length] = b[i];
}
return c;
}
/**
* @dev combine two arrays of uints
* @param a The first array
* @param b The second array
* @return The combined array
*/functioncombineUintArrays(uint256[] memory a, uint256[] memory b) publicpurereturns (uint256[] memory) {
uint256[] memory c =newuint256[](a.length+ b.length);
for (uint256 i =0; i < a.length; i++) {
c[i] = a[i];
}
for (uint256 i =0; i < b.length; i++) {
c[i + a.length] = b[i];
}
return c;
}
/**
* @dev wrap a string in a transform group
* @param x The x position
* @param y The y position
* @param data The data to wrap
* @return The wrapped string
*/functiongroupTransform(stringmemory x, stringmemory y, stringmemory data) internalpurereturns (stringmemory) {
returnstring.concat("<g transform='translate(", x, ",", y, ")'>", data, "</g>");
}
/**
* @dev convert a uint to bytes
* @param x The uint to convert
* @return b The bytes
*/functionuintToBytes(uint256 x) internalpurereturns (bytesmemory b) {
b =newbytes(32);
assembly {
mstore(add(b, 32), x)
} // first 32 bytes = length of the bytes value
}
/**
* @dev convert bytes with length equal to bytes32 to uint
* @param value The bytes to convert
* @return The uint
*/functionbytesToUint(bytesmemory value) internalpurereturns(uint) {
uint256 num =uint256(bytes32(value));
return num;
}
/**
* @dev convert bytes with length less than bytes32 to uint
* @param a The bytes to convert
* @return The uint
*/functionbyteSliceToUint (bytesmemory a) internalpurereturns(uint) {
bytes32 padding =bytes32(0);
bytesmemory formattedSlice = slice(bytes.concat(padding, a), 1, 32);
return bytesToUint(formattedSlice);
}
/**
* @dev get a byte from a random number at a given position
* @param rand The random number
* @param slicePosition The position of the byte to slice
* @return The random byte
*/functiongetRandByte(uint rand, uint slicePosition) internalpurereturns(uint) {
bytesmemory bytesRand = uintToBytes(rand);
bytesmemory part = slice(bytesRand, slicePosition, 1);
return byteSliceToUint(part);
}
/**
* @dev convert a string to a uint
* @param s The string to convert
* @return The uint
*/functionstringToUint(stringmemory s) internalpurereturns (uint) {
bytesmemory b =bytes(s);
uint result =0;
for (uint256 i =0; i < b.length; i++) {
uint256 c =uint256(uint8(b[i]));
if (c >=48&& c <=57) {
result = result *10+ (c -48);
}
}
return result;
}
/**
* @dev repeat an object a given number of times with given offsets
* @param object The object to repeat
* @param times The number of times to repeat
* @param offsetBytes The offsets to use
* @return The repeated object
*/functionrepeatGivenObject(stringmemory object, uint times, bytesmemory offsetBytes) internalpurereturns (stringmemory) {
// uint sliceSize = offsetBytes.length / (times * 2); // /2 for x and yrequire(offsetBytes.length% (times *2) ==0, "offsetBytes length must be divisible by times * 2");
stringmemory output ="";
for (uint256 i =0; i < times; i++) {
stringmemory xOffset =string(slice(offsetBytes, 2*i * offsetBytes.length/ (times *2), offsetBytes.length/ (times *2)));
stringmemory yOffset =string(slice(offsetBytes, (2*i +1) * offsetBytes.length/ (times *2), offsetBytes.length/ (times *2)));
output =string.concat(
output,
groupTransform(xOffset, yOffset, object)
);
}
return output;
}
/**
* @dev convert a single string to an array of uints
* @param values The string to convert
* @param numOfValues The number of values in the string
* @param lengthOfValue The length of each value in the string
* @return The array of uints
*/functionsetUintArrayFromString(stringmemory values, uint numOfValues, uint lengthOfValue) internalpurereturns (uint[] memory) {
uint[] memory output =newuint[](numOfValues);
for (uint256 i =0; i < numOfValues; i++) {
output[i] = stringToUint(string(slice(bytes(values), i*lengthOfValue, lengthOfValue)));
}
return output;
}
/**
* @dev get the sum of an array of uints
* @param arr The array to sum
* @return The sum
*/functiongetSumOfUintArray(uint[] memory arr) internalpurereturns (uint) {
uint sum =0;
for (uint i =0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
/**
* @dev constrain a value to the range 0-255, must be between -255 and 510
* @param value The value to constrain
* @return The constrained value
*/functionconstrainToHex(int value) internalpurereturns (uint) {
require(value >=-255&& value <=510, "Value out of bounds.");
if (value <0) { // if negative, make positivereturnuint(0- value);
}
elseif (value >255) { // if greater than 255, count back from 255returnuint(255- (value -255));
} else {
returnuint(value);
}
}
/**
* @dev create an array of equal probabilities for a given number of values
* @param numOfValues The number of values
* @return The array of probabilities
*/functioncreateEqualProbabilityArray(uint numOfValues) internalpurereturns (uint[] memory) {
uint oneLess = numOfValues -1;
uint[] memory probabilities =newuint[](oneLess);
for (uint256 i =0; i < oneLess; ++i) {
probabilities[i] =256* (i +1) / numOfValues;
}
return probabilities;
}
/**
* @dev get a single object from a string of object numbers
* @param objectNumbers The string of objects
* @param channelValue The hex value of the channel
* @param numOfValues The number of values in the string
* @param valueLength The length of each value in the string
* @return The object
*/functiongetSingleObject(stringmemory objectNumbers, uint channelValue, uint numOfValues, uint valueLength) internalpurereturns (uint) {
// create probability array assuming all objects have equal probabilityuint[] memory probabilities = createEqualProbabilityArray(numOfValues);
uint[] memory objectNumbersArray = setUintArrayFromString(objectNumbers, numOfValues, valueLength);
uint oneLess = numOfValues -1;
for (uint256 i =0; i < oneLess; ++i) {
if (channelValue < probabilities[i]) {
return objectNumbersArray[i];
}
}
return objectNumbersArray[oneLess];
}
}
Contract Source Code
File 11 of 24: IERC721A.sol
// SPDX-License-Identifier: MIT// ERC721A Contracts v4.2.3// Creator: Chiru Labspragmasolidity ^0.8.4;/**
* @dev Interface of ERC721A.
*/interfaceIERC721A{
/**
* The caller must own the token or be an approved operator.
*/errorApprovalCallerNotOwnerNorApproved();
/**
* The token does not exist.
*/errorApprovalQueryForNonexistentToken();
/**
* Cannot query the balance for the zero address.
*/errorBalanceQueryForZeroAddress();
/**
* Cannot mint to the zero address.
*/errorMintToZeroAddress();
/**
* The quantity of tokens minted must be more than zero.
*/errorMintZeroQuantity();
/**
* The token does not exist.
*/errorOwnerQueryForNonexistentToken();
/**
* The caller must own the token or be an approved operator.
*/errorTransferCallerNotOwnerNorApproved();
/**
* The token must be owned by `from`.
*/errorTransferFromIncorrectOwner();
/**
* Cannot safely transfer to a contract that does not implement the
* ERC721Receiver interface.
*/errorTransferToNonERC721ReceiverImplementer();
/**
* Cannot transfer to the zero address.
*/errorTransferToZeroAddress();
/**
* The token does not exist.
*/errorURIQueryForNonexistentToken();
/**
* The `quantity` minted with ERC2309 exceeds the safety limit.
*/errorMintERC2309QuantityExceedsLimit();
/**
* The `extraData` cannot be set on an unintialized ownership slot.
*/errorOwnershipNotInitializedForExtraData();
// =============================================================// STRUCTS// =============================================================structTokenOwnership {
// The address of the owner.address addr;
// Stores the start time of ownership with minimal overhead for tokenomics.uint64 startTimestamp;
// Whether the token has been burned.bool burned;
// Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.uint24 extraData;
}
// =============================================================// TOKEN COUNTERS// =============================================================/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see {_totalMinted}.
*/functiontotalSupply() externalviewreturns (uint256);
// =============================================================// IERC165// =============================================================/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
// =============================================================// IERC721// =============================================================/**
* @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,
bytescalldata data
) externalpayable;
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) externalpayable;
/**
* @dev Transfers `tokenId` 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
) externalpayable;
/**
* @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) externalpayable;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom}
* for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
// =============================================================// IERC721Metadata// =============================================================/**
* @dev Returns the token collection name.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the token collection symbol.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/functiontokenURI(uint256 tokenId) externalviewreturns (stringmemory);
// =============================================================// IERC2309// =============================================================/**
* @dev Emitted when tokens in `fromTokenId` to `toTokenId`
* (inclusive) is transferred from `from` to `to`, as defined in the
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
*
* See {_mintERC2309} for more details.
*/eventConsecutiveTransfer(uint256indexed fromTokenId, uint256 toTokenId, addressindexedfrom, addressindexed to);
}
Contract Source Code
File 12 of 24: LibBit.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;/// @notice Library for bit twiddling and boolean operations./// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)/// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html)libraryLibBit{
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*//* BIT TWIDDLING OPERATIONS *//*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*//// @dev Find last set./// Returns the index of the most significant bit of `x`,/// counting from the least significant bit position./// If `x` is zero, returns 256./// Equivalent to `log2(x)`, but without reverting for the zero case.functionfls(uint256 x) internalpurereturns (uint256 r) {
/// @solidity memory-safe-assemblyassembly {
r :=shl(8, iszero(x))
r :=or(r, shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
r :=or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r :=or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.
x :=shr(r, x)
x :=or(x, shr(1, x))
x :=or(x, shr(2, x))
x :=or(x, shr(4, x))
x :=or(x, shr(8, x))
x :=or(x, shr(16, x))
// forgefmt: disable-next-item
r :=or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f))
}
}
/// @dev Count leading zeros./// Returns the number of zeros preceding the most significant one bit./// If `x` is zero, returns 256.functionclz(uint256 x) internalpurereturns (uint256 r) {
/// @solidity memory-safe-assemblyassembly {
let t :=add(iszero(x), 255)
r :=shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r :=or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r :=or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.
x :=shr(r, x)
x :=or(x, shr(1, x))
x :=or(x, shr(2, x))
x :=or(x, shr(4, x))
x :=or(x, shr(8, x))
x :=or(x, shr(16, x))
// forgefmt: disable-next-item
r :=sub(t, or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f)))
}
}
/// @dev Find first set./// Returns the index of the least significant bit of `x`,/// counting from the least significant bit position./// If `x` is zero, returns 256./// Equivalent to `ctz` (count trailing zeros), which gives/// the number of zeros following the least significant one bit.functionffs(uint256 x) internalpurereturns (uint256 r) {
/// @solidity memory-safe-assemblyassembly {
r :=shl(8, iszero(x))
// Isolate the least significant bit.
x :=and(x, add(not(x), 1))
r :=or(r, shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
r :=or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r :=or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.// forgefmt: disable-next-item
r :=or(r, byte(shr(251, mul(shr(r, x), shl(224, 0x077cb531))),
0x00011c021d0e18031e16140f191104081f1b0d17151310071a0c12060b050a09))
}
}
/// @dev Returns the number of set bits in `x`.functionpopCount(uint256 x) internalpurereturns (uint256 c) {
/// @solidity memory-safe-assemblyassembly {
let max :=not(0)
let isMax :=eq(x, max)
x :=sub(x, and(shr(1, x), div(max, 3)))
x :=add(and(x, div(max, 5)), and(shr(2, x), div(max, 5)))
x :=and(add(x, shr(4, x)), div(max, 17))
c :=or(shl(8, isMax), shr(248, mul(x, div(max, 255))))
}
}
/// @dev Returns whether `x` is a power of 2.functionisPo2(uint256 x) internalpurereturns (bool result) {
/// @solidity memory-safe-assemblyassembly {
// Equivalent to `x && !(x & (x - 1))`.
result :=iszero(add(and(x, sub(x, 1)), iszero(x)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*//* BOOLEAN OPERATIONS *//*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*//// @dev Returns `x & y`.functionand(bool x, bool y) internalpurereturns (bool z) {
/// @solidity memory-safe-assemblyassembly {
z :=and(x, y)
}
}
/// @dev Returns `x | y`.functionor(bool x, bool y) internalpurereturns (bool z) {
/// @solidity memory-safe-assemblyassembly {
z :=or(x, y)
}
}
/// @dev Returns a non-zero number if `b` is true, else 0./// If `b` is from plain Solidity, the non-zero number will be 1.functiontoUint(bool b) internalpurereturns (uint256 z) {
/// @solidity memory-safe-assemblyassembly {
z := b
}
}
}
Contract Source Code
File 13 of 24: LibBitmap.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;import"./LibBit.sol";
/// @notice Library for storage of packed unsigned booleans./// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBitmap.sol)/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibBitmap.sol)/// @author Modified from Solidity-Bits (https://github.com/estarriolvetch/solidity-bits/blob/main/contracts/BitMaps.sol)libraryLibBitmap{
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*//* CONSTANTS *//*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*//// @dev The constant returned when a bitmap scan does not find a result.uint256internalconstant NOT_FOUND =type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*//* STRUCTS *//*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*//// @dev A bitmap in storage.structBitmap {
mapping(uint256=>uint256) map;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*//* OPERATIONS *//*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*//// @dev Returns the boolean value of the bit at `index` in `bitmap`.functionget(Bitmap storage bitmap, uint256 index) internalviewreturns (bool isSet) {
// It is better to set `isSet` to either 0 or 1, than zero vs non-zero.// Both cost the same amount of gas, but the former allows the returned value// to be reused without cleaning the upper bits.uint256 b = (bitmap.map[index >>8] >> (index &0xff)) &1;
/// @solidity memory-safe-assemblyassembly {
isSet := b
}
}
/// @dev Updates the bit at `index` in `bitmap` to true.functionset(Bitmap storage bitmap, uint256 index) internal{
bitmap.map[index >>8] |= (1<< (index &0xff));
}
/// @dev Updates the bit at `index` in `bitmap` to false.functionunset(Bitmap storage bitmap, uint256 index) internal{
bitmap.map[index >>8] &=~(1<< (index &0xff));
}
/// @dev Flips the bit at `index` in `bitmap`./// Returns the boolean result of the flipped bit.functiontoggle(Bitmap storage bitmap, uint256 index) internalreturns (bool newIsSet) {
/// @solidity memory-safe-assemblyassembly {
mstore(0x00, shr(8, index))
mstore(0x20, bitmap.slot)
let storageSlot :=keccak256(0x00, 0x40)
let shift :=and(index, 0xff)
let storageValue :=sload(storageSlot)
let mask :=shl(shift, 1)
storageValue :=xor(storageValue, mask)
// It makes sense to return the `newIsSet`,// as it allow us to skip an additional warm `sload`,// and it costs minimal gas (about 15),// which may be optimized away if the returned value is unused.
newIsSet :=iszero(iszero(and(storageValue, mask)))
sstore(storageSlot, storageValue)
}
}
/// @dev Updates the bit at `index` in `bitmap` to `shouldSet`.functionsetTo(Bitmap storage bitmap, uint256 index, bool shouldSet) internal{
/// @solidity memory-safe-assemblyassembly {
mstore(0x20, bitmap.slot)
mstore(0x00, shr(8, index))
let storageSlot :=keccak256(0x00, 0x40)
let storageValue :=sload(storageSlot)
let shift :=and(index, 0xff)
sstore(
storageSlot,
// Unsets the bit at `shift` via `and`, then sets its new value via `or`.or(and(storageValue, not(shl(shift, 1))), shl(shift, iszero(iszero(shouldSet))))
)
}
}
/// @dev Consecutively sets `amount` of bits starting from the bit at `start`.functionsetBatch(Bitmap storage bitmap, uint256 start, uint256 amount) internal{
/// @solidity memory-safe-assemblyassembly {
let max :=not(0)
let shift :=and(start, 0xff)
mstore(0x20, bitmap.slot)
mstore(0x00, shr(8, start))
ifiszero(lt(add(shift, amount), 257)) {
let storageSlot :=keccak256(0x00, 0x40)
sstore(storageSlot, or(sload(storageSlot), shl(shift, max)))
let bucket :=add(mload(0x00), 1)
let bucketEnd :=add(mload(0x00), shr(8, add(amount, shift)))
amount :=and(add(amount, shift), 0xff)
shift :=0for {} iszero(eq(bucket, bucketEnd)) { bucket :=add(bucket, 1) } {
mstore(0x00, bucket)
sstore(keccak256(0x00, 0x40), max)
}
mstore(0x00, bucket)
}
let storageSlot :=keccak256(0x00, 0x40)
sstore(storageSlot, or(sload(storageSlot), shl(shift, shr(sub(256, amount), max))))
}
}
/// @dev Consecutively unsets `amount` of bits starting from the bit at `start`.functionunsetBatch(Bitmap storage bitmap, uint256 start, uint256 amount) internal{
/// @solidity memory-safe-assemblyassembly {
let shift :=and(start, 0xff)
mstore(0x20, bitmap.slot)
mstore(0x00, shr(8, start))
ifiszero(lt(add(shift, amount), 257)) {
let storageSlot :=keccak256(0x00, 0x40)
sstore(storageSlot, and(sload(storageSlot), not(shl(shift, not(0)))))
let bucket :=add(mload(0x00), 1)
let bucketEnd :=add(mload(0x00), shr(8, add(amount, shift)))
amount :=and(add(amount, shift), 0xff)
shift :=0for {} iszero(eq(bucket, bucketEnd)) { bucket :=add(bucket, 1) } {
mstore(0x00, bucket)
sstore(keccak256(0x00, 0x40), 0)
}
mstore(0x00, bucket)
}
let storageSlot :=keccak256(0x00, 0x40)
sstore(
storageSlot, and(sload(storageSlot), not(shl(shift, shr(sub(256, amount), not(0)))))
)
}
}
/// @dev Returns number of set bits within a range by/// scanning `amount` of bits starting from the bit at `start`.functionpopCount(Bitmap storage bitmap, uint256 start, uint256 amount)
internalviewreturns (uint256 count)
{
unchecked {
uint256 bucket = start >>8;
uint256 shift = start &0xff;
if (!(amount + shift <257)) {
count = LibBit.popCount(bitmap.map[bucket] >> shift);
uint256 bucketEnd = bucket + ((amount + shift) >>8);
amount = (amount + shift) &0xff;
shift =0;
for (++bucket; bucket != bucketEnd; ++bucket) {
count += LibBit.popCount(bitmap.map[bucket]);
}
}
count += LibBit.popCount((bitmap.map[bucket] >> shift) << (256- amount));
}
}
/// @dev Returns the index of the most significant set bit before the bit at `before`./// If no set bit is found, returns `NOT_FOUND`.functionfindLastSet(Bitmap storage bitmap, uint256 before)
internalviewreturns (uint256 setBitIndex)
{
uint256 bucket;
uint256 bucketBits;
/// @solidity memory-safe-assemblyassembly {
setBitIndex :=not(0)
bucket :=shr(8, before)
mstore(0x00, bucket)
mstore(0x20, bitmap.slot)
let offset :=and(0xff, not(before)) // `256 - (255 & before) - 1`.
bucketBits :=shr(offset, shl(offset, sload(keccak256(0x00, 0x40))))
ifiszero(bucketBits) {
for {} bucket {} {
bucket :=add(bucket, setBitIndex) // `sub(bucket, 1)`.mstore(0x00, bucket)
bucketBits :=sload(keccak256(0x00, 0x40))
if bucketBits { break }
}
}
}
if (bucketBits !=0) {
setBitIndex = (bucket <<8) | LibBit.fls(bucketBits);
/// @solidity memory-safe-assemblyassembly {
setBitIndex :=or(setBitIndex, sub(0, gt(setBitIndex, before)))
}
}
}
}
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"@openzeppelin/contracts/utils/Strings.sol";
import"./GridHelper.sol";
import"./GlobalNumbers.sol";
import"./AssetRetriever.sol";
interfaceIMachine{
functiongetMachine(uint rand, int baseline) externalviewreturns (stringmemory);
functiongetAllNumbersUsed(uint rand, int baseline) externalpurereturns (uint[] memory, string[] memory);
functiongetGlobalAssetNumber(uint rand, uint version, int baseline) externalpurereturns (uint);
}
contractMachine{
AssetRetriever internalimmutable _assetRetriever;
string[] public allMachines = ["Altar", "Apparatus", "Cells", "Tubes", "Beast", "Conveyor"];
mapping(string=>address) public machineToWorkstation;
constructor(address[6] memory workstations, AssetRetriever assetRetriever) {
_assetRetriever = assetRetriever;
for (uint i =0; i < allMachines.length; ++i) {
machineToWorkstation[allMachines[i]] = workstations[i];
}
}
/**
* @dev Returns the machine based on the random number
* @param rand The digits to use
* @return The machine
*/functionselectMachine(uint rand) externalviewreturns (stringmemory) {
return allMachines[rand % allMachines.length];
// return allMachines[5];
}
/**
* @dev Get a machine based on the random number
* @param machine The machine to get
* @param rand The digits to use
* @param baseline The baseline rarity
*/functionmachineToGetter(stringmemory machine, uint rand, int baseline) externalviewreturns (stringmemory) {
return IMachine(machineToWorkstation[machine]).getMachine(rand, baseline);
}
/**
* @dev Get the global asset name based on the random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The global asset name
*/functiongetSmallAssetName(uint rand, int baseline) externalpurereturns (stringmemory) {
uint assetNumber = GlobalNumbers.getSmallAssetNumber(rand, baseline);
if (assetNumber ==6000) {
return"Lava Lamp";
} elseif (assetNumber ==6004) {
return"Martini";
} elseif (assetNumber ==6006) {
return"Bong";
} elseif (assetNumber ==6011) {
return"Books";
} elseif (assetNumber ==6014) {
return"Dog Bowl";
} elseif (assetNumber ==6020) {
return"Lizard";
} elseif (assetNumber ==6021) {
return"Skull";
} elseif (assetNumber ==6022) {
return"Dead Rat";
} elseif (assetNumber ==6025) {
return"Pineapple";
} elseif (assetNumber ==6026) {
return"Can";
} elseif (assetNumber ==6027) {
return"Cracked Bottle";
} elseif (assetNumber ==6028) {
return"Dead Plant";
} elseif (assetNumber ==6029) {
return"Watermelon";
} else {
return"None";
}
}
/**
* @dev Get the expansion prop name based on the random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The expansion prop name
*/functiongetLargeAssetName(uint rand, int baseline) externalpurereturns (stringmemory) {
uint propNumber = GlobalNumbers.getLargeAssetNumber(rand, baseline);
if (propNumber ==2001) {
return"Grate";
} elseif (propNumber ==2002) {
return"Pit";
} elseif (propNumber ==2003) {
return"Stairs";
} elseif (propNumber ==2004) {
return"Ladder";
} elseif (propNumber ==2008) {
return"Spikes A";
} elseif (propNumber ==2009) {
return"Spikes B";
} elseif (propNumber ==6008) {
return"Fridge";
} elseif (propNumber ==6009) {
return"Rug Circle";
} elseif (propNumber ==6013) {
return"Toilet";
} elseif (propNumber ==6017) {
return"Harp";
} elseif (propNumber ==6018) {
return"Cello";
} elseif (propNumber ==6019) {
return"Stool";
} elseif (propNumber ==6023) {
return"Deck Chair";
} elseif (propNumber ==6024) {
return"Cactus Chunk";
} elseif (propNumber ==6030) {
return"Gramophone";
} else {
return"None";
}
}
/**
* @dev Get the wall prop name based on the random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The wall out name
*/functiongetWallOutName(uint rand, int baseline) externalpurereturns (stringmemory) {
uint wallOutNumber = GlobalNumbers.getOutWallNumber(rand, baseline);
if (wallOutNumber ==6005) {
return"Peephole A";
} elseif (wallOutNumber ==6007) {
return"Peephole B";
} elseif (wallOutNumber ==6010) {
return"CCTV";
} elseif (wallOutNumber ==6016) {
return"Megaphone";
} else {
return"None";
}
}
/**
* @dev Get the wall flat name based on the random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The wall flat name
*/functiongetWallFlatName(uint rand, int baseline) externalpurereturns (stringmemory) {
uint wallFlatNumber = GlobalNumbers.getFlatWallNumber(rand, baseline);
if (wallFlatNumber ==2000) {
return"Crack";
} elseif (wallFlatNumber ==2005) {
return"Recess A";
} elseif (wallFlatNumber ==2006) {
return"Recess B";
} elseif (wallFlatNumber ==2007) {
return"Recess C";
} elseif (wallFlatNumber ==2010) {
return"Wall Rug";
} elseif (wallFlatNumber ==2011) {
return"Numbers";
} else {
return"None";
}
}
/**
* @dev Get the character name based on the random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The character name
*/functiongetCharacterName(uint rand, int baseline) externalpurereturns (stringmemory) {
uint characterNumber = GlobalNumbers.getCharacterNumber(rand, baseline);
if (characterNumber ==14000) {
return"Sitting";
} elseif (characterNumber ==14001) {
return"Standing";
} elseif (characterNumber ==14002) {
return"Collapsed";
} elseif (characterNumber ==14003) {
return"Slouched";
} elseif (characterNumber ==14004) {
return"Meditating";
} elseif (characterNumber ==14005) {
return"Hunched";
} else {
return"None";
}
}
}
Contract Source Code
File 16 of 24: Math.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
enumRounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.return a ==0 ? 0 : (a -1) / b +1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x,
uint256 y,
uint256 denominator
) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2^256 + prod0.uint256 prod0; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod0 :=mul(x, y)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.require(denominator > prod1);
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.// See https://cs.stackexchange.com/q/138556/92363.// Does not overflow because the denominator cannot be zero at this stage in the function.uint256 twos = denominator & (~denominator +1);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works// in modular arithmetic, doubling the correct bits in each step.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/functionmulDiv(uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internalpurereturns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up &&mulmod(x, y, denominator) >0) {
result +=1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/functionsqrt(uint256 a) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.//// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.//// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`//// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.uint256 result =1<< (log2(a) >>1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision// into the expected uint128 result.unchecked {
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/functionsqrt(uint256 a, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=128;
}
if (value >>64>0) {
value >>=64;
result +=64;
}
if (value >>32>0) {
value >>=32;
result +=32;
}
if (value >>16>0) {
value >>=16;
result +=16;
}
if (value >>8>0) {
value >>=8;
result +=8;
}
if (value >>4>0) {
value >>=4;
result +=4;
}
if (value >>2>0) {
value >>=2;
result +=2;
}
if (value >>1>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result =log2(value);
return result + (rounding == Rounding.Up &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >=10**64) {
value /=10**64;
result +=64;
}
if (value >=10**32) {
value /=10**32;
result +=32;
}
if (value >=10**16) {
value /=10**16;
result +=16;
}
if (value >=10**8) {
value /=10**8;
result +=8;
}
if (value >=10**4) {
value /=10**4;
result +=4;
}
if (value >=10**2) {
value /=10**2;
result +=2;
}
if (value >=10**1) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up &&10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/functionlog256(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=16;
}
if (value >>64>0) {
value >>=64;
result +=8;
}
if (value >>32>0) {
value >>=32;
result +=4;
}
if (value >>16>0) {
value >>=16;
result +=2;
}
if (value >>8>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog256(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up &&1<< (result *8) < value ? 1 : 0);
}
}
}
Contract Source Code
File 17 of 24: Metadata.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"solady/utils/Base64.sol";
import"./Machine.sol";
import"./GridHelper.sol";
import"./GlobalSVG.sol";
import"./Noise.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
contractMetadata{
Machine privateimmutable _machine;
// Clifford private _clifford;
GlobalSVG privateimmutable _globalSVG;
string[3] allStates = ["Degraded", "Basic", "Embellished"];
constructor(Machine machine, GlobalSVG globalSVG) {
_machine = machine;
_globalSVG = globalSVG;
}
/**
* @dev Returns the machine based on the random number
* @param rand The digits to use
* @return The machine
*/functiongetMachine(uint rand) publicviewreturns (stringmemory) {
return _machine.selectMachine(rand);
}
/**
* @dev build entire metadata for a given token
* @param tokenId The token to build metadata for
* @param rand The digits to use
* @return The metadata
*/functionbuildMetadata(uint256 tokenId, uint rand) publicviewreturns (stringmemory) {
int baseline = getBaselineRarity(rand);
uint state = getState(baseline);
stringmemory jsonInitial =string.concat(
'{"name": "A Machine For Dying # ',
Strings.toString(tokenId),
'", "description": "A Machine For Dying is centred around the concept of the Worker in a Box, a trapped individual, doomed to toil forever. The collection presents the stark contrast between autonomy and individuality versus the destruction and apathy that can come from being trapped and exploited by the corporate machine.", "attributes": [{"trait_type": "Machine", "value":"',
getMachine(rand),
'"}, {"trait_type": "State", "value":"',
allStates[state],
'"}, {"trait_type": "Small Asset:", "value":"',
_machine.getSmallAssetName(rand, baseline)
);
jsonInitial =string.concat(
jsonInitial,
'"}, {"trait_type": "Large Asset:", "value":"',
_machine.getLargeAssetName(rand, baseline),
'"}, {"trait_type": "Wall Out:", "value":"',
_machine.getWallOutName(rand, baseline),
'"}, {"trait_type": "Wall Flat:", "value":"',
_machine.getWallFlatName(rand, baseline)
);
jsonInitial =string.concat(
jsonInitial,
'"}, {"trait_type": "Colour:", "value":"',
getColourIndexTier(rand, baseline),
'"}, {"trait_type": "Pattern:", "value":"',
Patterns.getPatternName(rand, baseline),
'"}, {"trait_type": "Character:", "value":"',
_machine.getCharacterName(rand, baseline),
'"}],',
'"image": "data:image/svg+xml;base64,'
);
stringmemory jsonFinal = Base64.encode(
bytes(string.concat(
jsonInitial,
composeSVG(rand, baseline),
'", ',
'"animation_url": "data:image/svg+xml;base64,',
composeSVG(rand, baseline),
'"}'
))
);
stringmemory output =string.concat("data:application/json;base64,", jsonFinal);
return output;
}
/**
* @dev Inject data into the SVG for the sound script
* @param rand The digits to use
* @return The data info object string
*/functioncreateDataInfo(uint rand) internalviewreturns (stringmemory) {
int baseline = getBaselineRarity(rand);
uint state = getState(baseline);
stringmemory json =string.concat(
'data-info=\'{"RandomNumber":"',
Strings.toString(rand),
'","State":"',
allStates[state],
'","Machine":"',
getMachine(rand),
'","SmallAsset":"',
_machine.getSmallAssetName(rand, baseline)
);
json =string.concat(
json,
'","LargeAsset":"',
_machine.getLargeAssetName(rand, baseline),
'","WallOut":"',
_machine.getWallOutName(rand, baseline),
'","WallFlat":"',
_machine.getWallFlatName(rand, baseline)
);
json =string.concat(
json,
'","Colour":"',
getColourIndexTier(rand, baseline),
'","Pattern":"',
Patterns.getPatternName(rand, baseline),
'","Character":"',
_machine.getCharacterName(rand, baseline),
'"}\' >'
);
return json;
}
/**
* @dev Get the colour index based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The colour index as a string
*/functiongetBaseColourValue(uint rand, int baseline) internalpurereturns (uint) {
return GridHelper.constrainToHex(Noise.getNoiseArrayThree()[GridHelper.getRandByte(rand, 3)] + baseline);
}
/**
* @dev Get the colour index tier based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The colour index tier as a string
*/functiongetColourIndexTier(uint rand, int baseline) publicpurereturns(stringmemory) {
uint value = Environment.getColourIndex(getBaseColourValue(rand, baseline));
if (value <12) {
returnstring.concat("DEG", Strings.toString(11-value));
} else {
returnstring.concat("EMB", Strings.toString(value-12));
}
}
/**
* @dev Get the state based on the baseline rarity
* @param baseline The baseline rarity
* @return The state as an integer
*/functiongetState(int baseline) publicpurereturns (uint) {
// 0 = degraded, 1 = basic, 2 = embellishedif (baseline <85) {
return0;
} elseif (baseline <171) {
return1;
} else {
return2;
}
}
/**
* @dev Get the baseline rarity based on the random number
* @param rand The digits to use
* @return The baseline rarity as an integer
*/functiongetBaselineRarity(uint rand) publicpurereturns (int) {
int baselineDigits =int(GridHelper.constrainToHex(Noise.getNoiseArrayZero()[GridHelper.getRandByte(rand, 2)]));
return baselineDigits;
}
/**
* @dev Get the SVG for a given token base64 encoded
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The SVG as a string
*/functioncomposeSVG(uint rand, int baseline) publicviewreturns (stringmemory) {
// return all svg's concatenated together and base64 encodedreturn Base64.encode(bytes(composeOnlyImage(rand, baseline)));
}
/**
* @dev Get the SVG for a given token not base64 encoded
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The SVG as a string
*/functioncomposeOnlyImage(uint rand, int baseline) publicviewreturns (stringmemory) {
// determine if flipped// 0 if not flipped, 1 if flippeduint isFlipped = rand %2;
stringmemory flip ="";
if (isFlipped ==0) {
flip ="1";
} else {
flip ="-1";
}
stringmemory machine = getMachine(rand);
uint colourValue = getBaseColourValue(rand, baseline);
stringmemory dataInfo = createDataInfo(rand);
stringmemory opening = _globalSVG.getOpeningSVG(machine, colourValue, rand, baseline);
stringmemory objects = _machine.machineToGetter(machine, rand, baseline);
stringmemory closing = _globalSVG.getClosingSVG();
// return all svg's concatenated together and base64 encodedreturnstring.concat(opening, _globalSVG.getShell(flip, rand, baseline, dataInfo), objects, closing);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (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 Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 20 of 24: Patterns.sol
// SPDX-License-Identifier: MITpragmasolidity 0.8.16;import"./GridHelper.sol";
import"./Noise.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
libraryPatterns{
// 20 to 2 inclusive in 0.5 decrementsstringinternalconstant ANIMATED_TEXTURE_NUMBERS ="20.019.018.017.016.015.014.013.012.011.010.09.008.007.006.005.004.003.002.00";
// 4 to 1 inclusive in 0.1 decrimentsstringinternalconstant TEXTURE_SCALE_NUMBERS ="4.03.93.83.73.63.53.43.33.23.13.02.92.82.72.62.52.42.32.22.12.01.91.81.71.61.51.41.31.21.11.0";
// 15 to 0.3 inclusive in 0.3 decrimentsstringinternalconstant PATTERNS_SCALE_NUMBERS ="15.014.714.414.113.813.513.212.912.612.312.011.711.411.110.810.510.209.909.609.309.008.708.408.107.807.507.206.906.606.306.005.705.405.104.804.504.203.903.603.303.002.702.402.101.801.501.200.900.600.3";
stringinternalconstant ANIMATED_TEXTURE_NAMES ="TEXT12TEXT14TEXT09TEXT10TEXT13TEXT11";
stringinternalconstant TEXTURE_NAMES ="TEXT04TEXT01TEXT07TEXT05TEXT08TEXT02TEXT03TEXT06";
stringinternalconstant PATTERNS_NAMES ="GEOM03GEOM04PIXE02AZTC10GEOM02GEOM01LOGI01GEOM05PIXE02AZTC01AZTC05AZTC03AZTC09AZTC02AZTC08AZTC04AZTC06AZTC07";
/**
* @dev Get if the pattern is a texture or not based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return If the pattern is a texture or not
*/functiongetIsTexture(uint rand, int baseline) publicpurereturns (bool) {
uint textureDigits = GridHelper.constrainToHex(Noise.getNoiseArrayThree()[GridHelper.getRandByte(rand, 5)] + baseline);
return textureDigits <128;
}
/**
* @dev Get the pattern name based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The pattern name
*/functiongetPatternName(uint rand, int baseline) publicpurereturns (stringmemory) {
uint patternDigits = GridHelper.constrainToHex(Noise.getNoiseArrayThree()[GridHelper.getRandByte(rand, 5)] + baseline);
bool isTexture = getIsTexture(rand, baseline);
if (!isTexture) {
patternDigits -=128;
}
patternDigits *=2;
bool isAnimatedTexture = baseline <70;
uint nameLength;
uint nameCount;
stringmemory names;
if (isAnimatedTexture) {
nameLength =6;
nameCount =6;
names = ANIMATED_TEXTURE_NAMES;
} elseif (isTexture &&!isAnimatedTexture) {
nameLength =6;
nameCount =8;
names = TEXTURE_NAMES;
} else {
nameLength =6;
nameCount =18;
names = PATTERNS_NAMES;
}
uint[] memory nameProbabilitiesArray = GridHelper.createEqualProbabilityArray(nameCount);
uint oneLess = nameCount -1;
for (uint i =0; i < oneLess; ++i) {
if (patternDigits < nameProbabilitiesArray[i]) {
returnstring(GridHelper.slice(bytes(names), i * nameLength, nameLength));
}
}
returnstring(GridHelper.slice(bytes(names), oneLess * nameLength, nameLength));
}
/**
* @dev Get the surface quantity based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The surface quantity
*/functiongetSurfaceQuantity(uint rand, int baseline) publicpurereturns (bool[3] memory) {
uint surfaceDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 6)] + baseline);
if (baseline <70) {
surfaceDigits +=128; // animated textures should appear on 2+ surfaces
}
// LW, RW, FLOORuint[] memory surfaceProbabilitiesArray = GridHelper.createEqualProbabilityArray(4);
if (surfaceDigits < surfaceProbabilitiesArray[0]) {
return [true, false, false];
} elseif (surfaceDigits < surfaceProbabilitiesArray[1]) {
return [false, true, false];
} elseif (surfaceDigits < surfaceProbabilitiesArray[2]) {
return [true, true, false];
} else {
return [true, true, true];
}
}
/**
* @dev Get the pattern scale based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The pattern scale
*/functiongetScale(uint rand, int baseline) publicpurereturns (stringmemory) {
uint scaleDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 7)] + baseline);
bool isTexture = getIsTexture(rand, baseline);
bool isAnimatedTexture = baseline <70;
uint scaleLength;
uint scaleCount;
stringmemory scales;
if (isAnimatedTexture) {
scaleLength =4;
scaleCount =19;
scales = ANIMATED_TEXTURE_NUMBERS;
} elseif (isTexture &&!isAnimatedTexture) {
scaleLength =3;
scaleCount =31;
scales = TEXTURE_SCALE_NUMBERS;
} else {
scaleLength =4;
scaleCount =50;
scales = PATTERNS_SCALE_NUMBERS;
}
uint[] memory scaleProbabilitiesArray = GridHelper.createEqualProbabilityArray(scaleCount);
uint oneLess = scaleCount -1;
if (baseline >185) {
uint scaleValue = oneLess - (scaleDigits %5);
returnstring(GridHelper.slice(bytes(scales), scaleValue * scaleLength, scaleLength));
}
for (uint i =0; i < oneLess; ++i) {
if (scaleDigits < scaleProbabilitiesArray[i]) {
returnstring(GridHelper.slice(bytes(scales), i * scaleLength, scaleLength));
}
}
returnstring(GridHelper.slice(bytes(scales), oneLess * scaleLength, scaleLength));
}
/**
* @dev Get the pattern opacity based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @param surfaceNumber The surface number 0 is left wall, 1 is right wall, 2 is floor
* @return The pattern opacity as a string
*/functiongetOpacity(uint rand, int baseline, uint surfaceNumber) publicpurereturns (stringmemory) {
uint opacityDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 8)] + baseline);
bool[3] memory surfaceQuantity = getSurfaceQuantity(rand, baseline);
if (!surfaceQuantity[surfaceNumber]) {
return Strings.toString(0);
}
bool isTexture = getIsTexture(rand, baseline);
if (isTexture) {
// 100 -> 20return Strings.toString(100- (opacityDigits *80/255+20));
} else {
if (baseline >185) {
return Strings.toString(100);
} else {
// 25 -> 100return Strings.toString(opacityDigits *75/255+25);
}
}
}
/**
* @dev Get the pattern rotation based on the baseline rarity and random number
* @param rand The digits to use
* @param baseline The baseline rarity
* @return The pattern rotation in degrees from 0 to 45
*/// Only used for texturesfunctiongetRotate(uint rand, int baseline) publicpurereturns (uint) {
uint rotateDigits = GridHelper.constrainToHex(Noise.getNoiseArrayOne()[GridHelper.getRandByte(rand, 9)] + baseline);
// 0 -> 45return rotateDigits *45/255;
}
}
Contract Source Code
File 21 of 24: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)pragmasolidity ^0.8.0;import"./math/Math.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
uint256 length = Math.log10(value) +1;
stringmemory buffer =newstring(length);
uint256 ptr;
/// @solidity memory-safe-assemblyassembly {
ptr :=add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assemblyassembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, Math.log256(value) +1);
}
}
/**
* @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] = _SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.4;/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/abstractcontractVRFConsumerBaseV2{
errorOnlyCoordinatorCanFulfill(address have, address want);
addressprivateimmutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/functionfulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internalvirtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF// proof. rawFulfillRandomness then calls fulfillRandomness, after validating// the origin of the callfunctionrawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external{
if (msg.sender!= vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
Contract Source Code
File 24 of 24: VRFCoordinatorV2Interface.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;interfaceVRFCoordinatorV2Interface{
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/functiongetRequestConfig()
externalviewreturns (uint16,
uint32,
bytes32[] memory);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/functionrequestRandomWords(bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) externalreturns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/functioncreateSubscription() externalreturns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/functiongetSubscription(uint64 subId)
externalviewreturns (uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/functionrequestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/functionacceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/functionaddConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/functionremoveConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/functioncancelSubscription(uint64 subId, address to) external;
/*
* @notice Check to see if there exists a request commitment consumers
* for all consumers and keyhashes for a given sub.
* @param subId - ID of the subscription
* @return true if there exists at least one unfulfilled request for the subscription, false
* otherwise.
*/functionpendingRequestExists(uint64 subId) externalviewreturns (bool);
}