Contract Source Code:
// SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.10;
import "@divergencetech/ethier/contracts/erc721/ERC721Common.sol";
import "@divergencetech/ethier/contracts/sales/Seller.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import {Transforms} from "./Transforms.sol";
import {Base64} from "./base64.sol";
error Soulbound();
/// @title NFT NYC 2023
contract NYC2023 is ERC721Common, Seller {
using Strings for uint256;
struct Token {
string recipient;
string timestamp;
string writtenMsg;
}
Token[] private tokens;
// string public contractAddressString =
// Transforms.toAsciiString(address(this));
constructor(
string memory name,
string memory symbol,
uint256 alltotalSupply
) ERC721Common(name, symbol) Seller(alltotalSupply) {}
/**
@notice Internal override of Seller function for handling purchase (i.e.minting).
*/
function _handlePurchase(address to, uint256 num, bool) internal override {
for (uint256 i = 0; i < num; i++) {
_safeMint(to, totalSold() + i);
string memory resolved = string(
abi.encodePacked(
"0x",
Transforms.toAsciiString(to)
)
);
tokens.push(
Token({
recipient: resolved,
timestamp: block.timestamp.toString(),
writtenMsg: currentMessage
})
);
}
}
// /// @notice Prefix for tokenURI return values.
// string public baseTokenURI;
// /// @notice Set the baseTokenURI.
// function setBaseTokenURI(string memory baseTokenURI_) external onlyOwner {
// baseTokenURI = baseTokenURI_;
// }
/// @notice Returns the token's metadata URI.
function tokenURI(
uint256 tokenId
) public view override tokenExists(tokenId) returns (string memory) {
return constructTokenURI(tokenId);
// return string(abi.encodePacked(baseTokenURI, tokenId.toString()));
}
/// @notice Prefix for message return values
string public currentMessage;
/// @notice Set the message
function setMessage(string calldata _message) external onlyOwner {
require(bytes(_message).length <= 60);
// for(uint i = 0; i < tokens.length; ++i){
// tokens[i].writtenMsg = _message;
// }
currentMessage = _message;
}
/**
* @notice Generate SVG using tParams by index
*/
function generateSVG(uint256 id) private view returns (bytes memory) {
bytes memory message;
if (bytes(tokens[id].writtenMsg).length == 0) {
message = bytes.concat(
abi.encodePacked('<tspan text-anchor="middle" x="50%" y="565">', "</tspan>")
);
} else {
message = bytes.concat(
abi.encodePacked(
'<tspan text-anchor="middle" x="50%" y="565">"',
tokens[id].writtenMsg,
'"</tspan>'
)
);
}
return
bytes.concat(
abi.encodePacked(
'<svg id="_floor2" data-name="floor2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 800"><defs><style>.cls-1, .cls-2, .cls-3 {fill: #fff;} .cls-2 {stroke: #979797;stroke-width: .68px;}.cls-3, .cls-4, .cls-5 {fill-rule: evenodd;}.cls-4 {fill: #ffa51b;}</style></defs>',
'<g id="_floor" data-name="floor1"><rect class="cls-1" width="600" height="800"/><g>',
'<path id="Fill-1" class="cls-4" d="M124.45,139.25c-18.31-1.73-36.63,5.72-50.46,17.23-4.71,3.92-16.47,13.58-12,20.66,2.33,3.69,6.08,6.15,9.71,8.48,5.69,3.66,5.94,9.71,9.96,14.6,3.13,3.81,7.66,6.23,12.53,7.12-.46,.24-.91,.48-1.36,.73-11.46,6.37-11.62,15.16-10.24,20.67,.86,3.44,3.18,6.32,6.37,7.95,13.24,6.75,25.46-2.62,31-10.35,6.15-8.57,12.18-10.79,15.76-6.25,1.39,1.76,3.39,6.15,6.25,5.49,5.34-1.24,.57-9.45,4.6-11.15,2.73-1.14,3.6,2.19,4.84,3.77,1.65,2.11,3.98,3.86,6.74,4.18,3.85,.45,7.28-2.21,7.38-6.02,.05-1.88-.71-4.1-3.36-6.24-1.42-1.14-2.94-2.08-4.5-2.83,1.57-.25,2.89-.54,3.88-.89,11.26-3.91,10.6-20.86,10.6-20.86,.66-26.07-13.25-43.02-47.69-46.28"/>',
'<path id="Fill-3" class="cls-3" d="M126.99,202.04c-9.72,.55-21.69-5-22.4-14.55-.75-9.98,.3-22.27,7.29-28.68,9.94-9.13,34.44-12.38,47.03,1.3,12.58,13.69,8.61,29.33,2.92,33.89-7.16,5.74-20.33,7.22-34.83,8.04"/>',
'<path id="Fill-5" class="cls-4" d="M135.08,176.4c0,5.83-4.46,10.56-9.96,10.56s-9.96-4.73-9.96-10.56,4.46-10.56,9.96-10.56,9.96,4.73,9.96,10.56"/>',
'<path id="Fill-7" class="cls-4" d="M152.33,174.66c2.42-.28,4.73,.62,6.4,2.27,.72,.71,1.95,.15,1.83-.85v-.03c-.56-4.65-4.56-8.02-8.95-7.52-4.39,.5-7.51,4.69-6.96,9.34v.03c.12,1,1.45,1.27,1.98,.41,1.24-1.98,3.27-3.38,5.7-3.66"/></g>'
),
abi.encodePacked(
'<g><path class="cls-5" d="M239.73,165.65c-1.63-2.16-3.86-3.98-6.7-5.44-2.84-1.46-6.17-2.19-9.98-2.19s-7.16,.74-10.06,2.23c-2.9,1.49-5.15,3.33-6.75,5.52s-3.05,5.21-4.35,9.05c-1.3,3.84-1.95,8.47-1.95,13.88,0,5.9,.8,11.18,2.4,15.83,1.05,2.92,2.39,5.44,4.02,7.55,1.63,2.11,3.89,3.88,6.79,5.32,2.9,1.43,6.22,2.15,9.97,2.15s7.05-.7,9.89-2.11c2.84-1.41,5.06-3.19,6.66-5.36,4.3-5.74,6.46-13.5,6.46-23.3,0-5.47-.83-10.64-2.48-15.51-.99-2.92-2.3-5.47-3.93-7.63Zm-16.68,6.74c.78,0,1.5,.12,2.17,.33l-9.35,26.26c-.84-2.59-1.27-5.99-1.27-10.23,0-10.9,2.81-16.36,8.44-16.36Zm8.44,16.8c0,10.61-2.84,15.91-8.53,15.91-1.02,0-1.94-.19-2.77-.55l9.75-26.8c1.03,2.66,1.54,6.31,1.54,10.95v.49Z"/>'
'<path class="cls-5" d="M293.9,182.9c0-1.38-.99-3.04-2.98-4.99-1.99-1.95-3.67-2.92-5.05-2.92s-3.06,.97-5.05,2.92l-9.11,9.09-9.19-9.09c-1.99-1.95-3.66-2.92-5.01-2.92s-3.04,.97-5.05,2.92c-2.02,1.95-3.02,3.61-3.02,4.99s.99,3.04,2.98,4.99l9.19,9.09-9.19,9.09c-1.99,1.95-2.98,3.61-2.98,4.99s1.01,3.03,3.02,4.95c2.01,1.92,3.7,2.88,5.05,2.88s3.02-.97,5.01-2.92l9.19-9.01,9.11,9.01c1.99,1.95,3.67,2.92,5.05,2.92s3.06-.96,5.05-2.88c1.99-1.92,2.98-3.57,2.98-4.95s-.99-3.04-2.98-4.99l-9.19-9.09,9.19-9.09c1.99-1.95,2.98-3.61,2.98-4.99Z"/>',
'<path class="cls-5" d="M362.94,161.19c-.77-1.46-2.91-2.19-6.42-2.19s-5.73,.73-6.66,2.19c-3.14,3.9-9.41,11.93-18.79,24.11l-18.79-24.19-.5-.49c-.33-.38-1.03-.74-2.11-1.1-1.08-.35-2.36-.53-3.85-.53-3.48,0-5.63,.7-6.46,2.11-.44,.81-.7,1.53-.79,2.15-.08,.62-.12,1.56-.12,2.8v45.05c0,1.3,.04,2.27,.12,2.92,.08,.65,.34,1.35,.79,2.11,.83,1.46,2.92,2.19,6.29,2.19s5.63-.73,6.46-2.19c.44-.76,.7-1.45,.79-2.07,.08-.62,.12-1.56,.12-2.8v-27.36c.28,.33,2.04,2.69,5.3,7.1,3.26,4.41,5.44,7.29,6.54,8.65l.66,.89c.44,.54,1.17,1.09,2.19,1.66,1.02,.57,2.15,.85,3.39,.85s2.4-.31,3.48-.93c1.08-.62,1.75-1.11,2.03-1.46,.27-.35,.77-.99,1.49-1.91,.72-.92,2.4-3.21,5.05-6.86,2.65-3.65,4.66-6.32,6.04-8v27.2c0,1.89,.14,3.3,.41,4.22,.27,.7,.66,1.25,1.16,1.62,.5,.38,1.21,.7,2.15,.97,.94,.27,2.21,.41,3.81,.41s2.92-.16,3.97-.49c2.1-.65,3.15-2.84,3.15-6.58v-45.06c0-1.24-.04-2.19-.12-2.84-.08-.65-.34-1.38-.79-2.19Z"/>',
'<path class="cls-5" d="M409.99,199.3c1.68-1.6,2.53-4.06,2.53-7.39s-.94-6.4-2.81-9.21c-3.59-5.3-9.22-7.96-16.89-7.96-6.73,0-12.35,2.04-16.85,6.13-4.5,4.09-6.75,9.54-6.75,16.36,0,5.41,1.74,10.31,5.21,14.69,1.77,2.27,4.24,4.1,7.41,5.48,3.17,1.38,6.8,2.07,10.89,2.07,11.75,0,17.63-2.41,17.63-7.22,0-1.03-.36-2.27-1.08-3.73-1.27-2.44-2.79-3.65-4.55-3.65-.88,0-1.99,.3-3.31,.89l-.91,.32c-1.82,.65-4.33,.97-7.53,.97-1.82,0-3.64-.51-5.46-1.54-1.82-1.03-2.73-2.3-2.73-3.82h19.62c2.04,0,3.9-.8,5.59-2.39Zm-14.94-4.99h-10.43c0-1.62,.88-3.15,2.65-4.59,1.76-1.43,3.54-2.15,5.34-2.15s3.17,.38,4.14,1.14c.97,.76,1.45,1.76,1.45,3,0,1.73-1.05,2.6-3.14,2.6Z"/>',
'<path class="cls-5" d="M447.53,176.12c-1.05-.33-2.02-.55-2.9-.69-.88-.13-1.97-.2-3.27-.2s-2.8,.46-4.51,1.38c-1.71,.92-2.83,1.65-3.35,2.19-.53,.54-.92,1-1.2,1.38,0-.92-.3-1.81-.91-2.68-.83-1.24-2.9-1.87-6.21-1.87-3.53,0-5.68,.73-6.46,2.19-.39,.76-.62,1.45-.7,2.07-.08,.62-.12,1.56-.12,2.8v30.85c.11,1.57,.61,2.73,1.49,3.49,1.16,.92,3.06,1.38,5.71,1.38,3.48,0,5.63-.7,6.46-2.11,.44-.81,.7-1.53,.79-2.15,.08-.62,.12-1.56,.12-2.8v-17.05c0-1.46,.65-2.71,1.95-3.73,1.3-1.03,2.69-1.54,4.18-1.54s2.69,.22,3.6,.65,1.86,.65,2.86,.65c1.99,0,3.5-1.03,4.55-3.08,1.05-2.06,1.57-3.95,1.57-5.68s-.35-2.99-1.04-3.77c-.69-.78-1.56-1.34-2.61-1.66Z"/>',
'<path class="cls-5" d="M469.3,191.63c1.6-1.3,3.33-1.95,5.17-1.95s3.27,.46,4.26,1.38c1.93,1.19,3.42,1.79,4.47,1.79,1.82,0,3.73-1.49,5.71-4.46,1.16-1.73,1.74-3.29,1.74-4.67s-.72-2.61-2.15-3.69c-.55-.38-1.32-.89-2.32-1.54l-1.32-.81c-.94-.54-2.4-1.1-4.39-1.66-1.99-.57-4.03-.85-6.13-.85-5.19,0-10.07,1.79-14.65,5.36-2.26,1.73-4.11,4.02-5.55,6.86-1.44,2.84-2.15,6.01-2.15,9.5s.72,6.68,2.15,9.58c1.43,2.9,3.28,5.21,5.55,6.94,4.75,3.63,9.68,5.44,14.82,5.44,4.58,0,8.44-1.08,11.59-3.25,3.03-1.79,4.55-3.71,4.55-5.76,0-1.24-.64-2.65-1.9-4.22-2.37-2.87-4.39-4.3-6.04-4.3-.94,0-2.17,.5-3.68,1.5-1.52,1-3.15,1.5-4.88,1.5s-3.38-.64-4.92-1.91c-1.55-1.27-2.32-3.06-2.32-5.36s.8-4.1,2.4-5.4Z"/>',
'<path class="cls-5" d="M533.5,181.97c-3.67-4.11-8.26-6.17-13.78-6.17-3.7,0-6.93,1.65-9.68,4.95v-17.94c0-1.24-.04-2.18-.12-2.8-.08-.62-.35-1.34-.79-2.15-.72-1.46-2.81-2.19-6.29-2.19s-5.68,.73-6.46,2.19c-.39,.76-.62,1.45-.7,2.07-.08,.62-.12,1.56-.12,2.8v48.55c0,1.3,.04,2.25,.12,2.84,.08,.6,.32,1.3,.7,2.11,.77,1.46,2.9,2.19,6.37,2.19s5.66-.7,6.37-2.11c.44-.81,.7-1.53,.79-2.15,.08-.62,.12-1.55,.12-2.8v-15.75c.22-1.46,1.08-2.77,2.57-3.94,1.49-1.16,3.21-1.74,5.17-1.74s3.57,.62,4.84,1.87c1.27,1.25,1.9,2.98,1.9,5.2v14.21c0,1.3,.04,2.27,.12,2.92,.08,.65,.34,1.38,.79,2.19,.83,1.41,2.92,2.11,6.29,2.11s5.66-.7,6.37-2.11c.44-.81,.7-1.53,.79-2.15,.08-.62,.12-1.55,.12-2.8v-14.29c0-5.95-1.84-10.99-5.5-15.1Z"/>'
'</g><rect id="the" class="cls-2" x="50.34" y="378.34" width="499.32" height="340.32" rx="13.57" ry="13.57"/></g>'
),
abi.encodePacked(
'<rect id="the" stroke="#979797" stroke-width="0.678281069" fill="#FFFFFF" x="50.3391405" y="378.339141" width="499.321719" height="340.321719" rx="13.5656214"></rect>',
'<text id="address" font-family="Arial-BoldMT, Arial" font-size="18.9918699" font-weight="bold" fill="#000000"><tspan text-anchor="middle" x="50%" y="433">',
tokens[id].recipient,
'</tspan></text><text id="thank" font-family="ArialMT, Arial" font-size="18.9918699" font-weight="normal" fill="#000000">',
message,
'</text><text id="recipient" font-family="Arial-BoldMT, Arial" font-size="28" font-weight="bold" fill="#000000"><tspan x="242.148438" y="482">recipient</tspan></text>',
'<text id="mint-time" font-family="ArialMT, Arial" font-size="21" font-weight="normal" line-spacing="30" fill="#000000"><tspan text-anchor="middle" x="50%" y="647">',
tokens[id].timestamp,
'</tspan><tspan x="228.817383" y="677">mint timestamp</tspan></text></svg>'
)
);
}
/**
* @notice Generate SVG, b64 encode it, construct an ERC721 token URI.
*/
function constructTokenURI(
uint256 id
) private view returns (string memory) {
string memory pageSVG = Base64.encode(bytes(generateSVG(id)));
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"signed_to":"',
tokens[id].recipient,
'", "name":"',
"0xMerch NYC2023 ",
"#",
id.toString(),
'", "external_url":"',
"https://0xmerch.io/Home",
'", "timestamp":"',
tokens[id].timestamp,
'", "message":"',
tokens[id].writtenMsg,
'", "image": "',
"data:image/svg+xml;base64,",
pageSVG,
'"}'
)
)
)
)
);
}
// function contractURI() external pure returns (string memory) {
// return
// string(
// abi.encodePacked(
// "data:application/json;base64,",
// Base64.encode(
// bytes(
// abi.encodePacked(
// "{",
// '"name":"',
// "NYC 2023",
// '",'
// '"description":"',
// "0xMerch market can give you the best nft merch goods!",
// '",'
// '"image_data":"',
// // Yeah, looks like CORS may not be letting this resolve, fix l8r
// "",
// '",'
// '"external_link":"',
// "https://0xmerch.io/Home",
// '"}'
// )
// )
// )
// )
// );
// }
/**
@notice Returns total number of existing tokens.
@dev Using ERC721Enumerable is unnecessarily expensive wrt gas. However
Etherscan uses totalSupply() so we provide it here.
*/
function totalSupplied() external view returns (uint256) {
return totalSold();
}
/**
* @notice SOULBOUND: non transferable.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Common) {
require(
from == address(0) || to == address(0),
"SOULBOUND: Non-Transferable"
);
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @notice SOULBOUND: non approval.
*/
function setApprovalForAll(
address operator,
bool _approved
) public virtual override(ERC721) {
revert Soulbound();
}
/**
* @notice SOULBOUND: Block approvals.
*/
function approve(
address to,
uint256 tokenId
) public virtual override(ERC721) {
revert Soulbound();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
library Transforms {
/*///////////////////////////////////////////////////////////////
TYPE LOGIC
//////////////////////////////////////////////////////////////*/
function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = char(hi);
s[2 * i + 1] = char(lo);
}
return string(s);
}
function char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`.
// We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
// This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
// Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
// good first aproximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1;
uint256 x = a;
if (x >> 128 > 0) {
x >>= 128;
result <<= 64;
}
if (x >> 64 > 0) {
x >>= 64;
result <<= 32;
}
if (x >> 32 > 0) {
x >>= 32;
result <<= 16;
}
if (x >> 16 > 0) {
x >>= 16;
result <<= 8;
}
if (x >> 8 > 0) {
x >>= 8;
result <<= 4;
}
if (x >> 4 > 0) {
x >>= 4;
result <<= 2;
}
if (x >> 2 > 0) {
result <<= 1;
}
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
uint256 result = sqrt(a);
if (rounding == Rounding.Up && result * result < a) {
result += 1;
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @notice A Pausable contract that can only be toggled by the Owner.
contract OwnerPausable is Ownable, Pausable {
/// @notice Pauses the contract.
function pause() public onlyOwner {
Pausable._pause();
}
/// @notice Unpauses the contract.
function unpause() public onlyOwner {
Pausable._unpause();
}
}
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
/**
@notice Provides monotonic increasing and decreasing values, similar to
OpenZeppelin's Counter but (a) limited in direction, and (b) allowing for steps
> 1.
*/
library Monotonic {
/**
@notice Holds a value that can only increase.
@dev The internal value MUST NOT be accessed directly. Instead use current()
and add().
*/
struct Increaser {
uint256 value;
}
/// @notice Returns the current value of the Increaser.
function current(Increaser storage incr) internal view returns (uint256) {
return incr.value;
}
/// @notice Adds x to the Increaser's value.
function add(Increaser storage incr, uint256 x) internal {
incr.value += x;
}
/**
@notice Holds a value that can only decrease.
@dev The internal value MUST NOT be accessed directly. Instead use current()
and subtract().
*/
struct Decreaser {
uint256 value;
}
/// @notice Returns the current value of the Decreaser.
function current(Decreaser storage decr) internal view returns (uint256) {
return decr.value;
}
/// @notice Subtracts x from the Decreaser's value.
function subtract(Decreaser storage decr, uint256 x) internal {
decr.value -= x;
}
}
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
import "../utils/Monotonic.sol";
import "../utils/OwnerPausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/**
@notice An abstract contract providing the _purchase() function to:
- Enforce per-wallet / per-transaction limits
- Calculate required cost, forwarding to a beneficiary, and refunding extra
*/
abstract contract Seller is OwnerPausable, ReentrancyGuard {
using Address for address payable;
using Monotonic for Monotonic.Increaser;
using Strings for uint256;
uint256 public total;
constructor(uint256 total_) {
total = total_;
}
/**
@dev Called by both _purchase() and purchaseFreeOfCharge() after all limits
have been put in place; must perform all contract-specific sale logic, e.g.
ERC721 minting. When _handlePurchase() is called, the value returned by
Seller.totalSold() will be the pre-purchase amount.
@param to The recipient of the item(s).
@param n The number of items allowed to be purchased, which MAY be less than
to the number passed to _purchase() but SHALL be greater than zero.
@param freeOfCharge Indicates that the call originated from
purchaseFreeOfCharge() and not _purchase().
*/
function _handlePurchase(
address to,
uint256 n,
bool freeOfCharge
) internal virtual;
/**
@notice Tracks total number of items sold by this contract, including those
purchased free of charge by the contract owner.
*/
Monotonic.Increaser private _totalSold;
/// @notice Returns the total number of items sold by this contract.
function totalSold() internal view returns (uint256) {
return _totalSold.current();
}
/**
@notice Allows the contract owner to purchase without payment, within the
quota enforced by the SellerConfig.
*/
function managerSend(address to, uint256 n)
public
onlyOwner
whenNotPaused
{
uint256 totalInventory = total;
n = Math.min(n, totalInventory - _totalSold.current());
require(n > 0, "Seller: Sold out");
_handlePurchase(to, n, true);
_totalSold.add(n);
assert(_totalSold.current() <= totalInventory);
}
}
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
import "../utils/OwnerPausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
@notice An ERC721 contract with common functionality:
- OpenSea gas-free listings
- OpenZeppelin Pausable
- OpenZeppelin Pausable with functions exposed to Owner only
*/
contract ERC721Common is Context, ERC721Pausable, OwnerPausable {
constructor(string memory name, string memory symbol)
ERC721(name, symbol)
{}
/// @notice Requires that the token exists.
modifier tokenExists(uint256 tokenId) {
require(ERC721._exists(tokenId), "ERC721Common: Token doesn't exist");
_;
}
/// @notice Requires that msg.sender owns or is approved for the token.
modifier onlyApprovedOrOwner(uint256 tokenId) {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Common: Not approved nor owner"
);
_;
}
/// @notice Overrides _beforeTokenTransfer as required by inheritance.
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/// @notice Overrides supportsInterface as required by inheritance.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
@notice Returns true if either standard isApprovedForAll() returns true or
the operator is the OpenSea proxy for the owner.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return
super.isApprovedForAll(owner, operator);
}
}