Created
September 24, 2022 11:23
-
-
Save karooolis/ccf5665d6ddda82fb5cec40adeff1820 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// ERC721A Contracts v4.2.3 | |
// Creator: Chiru Labs | |
pragma solidity ^0.8.4; | |
import './IERC721A.sol'; | |
/** | |
* @dev Interface of ERC721 token receiver. | |
*/ | |
interface ERC721A__IERC721Receiver { | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (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). | |
*/ | |
contract ERC721A is IERC721A { | |
// Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364). | |
struct TokenApprovalRef { | |
address value; | |
} | |
// ============================================================= | |
// CONSTANTS | |
// ============================================================= | |
// Mask of an entry in packed address data. | |
uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; | |
// The bit position of `numberMinted` in packed address data. | |
uint256 private constant _BITPOS_NUMBER_MINTED = 64; | |
// The bit position of `numberBurned` in packed address data. | |
uint256 private constant _BITPOS_NUMBER_BURNED = 128; | |
// The bit position of `aux` in packed address data. | |
uint256 private constant _BITPOS_AUX = 192; | |
// Mask of all 256 bits in packed address data except the 64 bits for `aux`. | |
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; | |
// The bit position of `startTimestamp` in packed ownership. | |
uint256 private constant _BITPOS_START_TIMESTAMP = 160; | |
// The bit mask of the `burned` bit in packed ownership. | |
uint256 private constant _BITMASK_BURNED = 1 << 224; | |
// The bit position of the `nextInitialized` bit in packed ownership. | |
uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; | |
// The bit mask of the `nextInitialized` bit in packed ownership. | |
uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; | |
// The bit position of `extraData` in packed ownership. | |
uint256 private constant _BITPOS_EXTRA_DATA = 232; | |
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. | |
uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; | |
// The mask of the lower 160 bits for addresses. | |
uint256 private constant _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. | |
uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; | |
// The `Transfer` event signature is given by: | |
// `keccak256(bytes("Transfer(address,address,uint256)"))`. | |
bytes32 private constant _TRANSFER_EVENT_SIGNATURE = | |
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; | |
// ============================================================= | |
// STORAGE | |
// ============================================================= | |
// The next token ID to be minted. | |
uint256 private _currentIndex; | |
// The number of tokens burned. | |
uint256 private _burnCounter; | |
// Token name | |
string private _name; | |
// Token symbol | |
string private _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 approvals | |
mapping(address => mapping(address => bool)) private _operatorApprovals; | |
// ============================================================= | |
// CONSTRUCTOR | |
// ============================================================= | |
constructor(string memory name_, string memory 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() internal view virtual returns (uint256) { | |
return 0; | |
} | |
/** | |
* @dev Returns the next token ID to be minted. | |
*/ | |
function _nextTokenId() internal view virtual returns (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}. | |
*/ | |
function totalSupply() public view virtual override returns (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() internal view virtual returns (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() internal view virtual returns (uint256) { | |
return _burnCounter; | |
} | |
// ============================================================= | |
// ADDRESS DATA OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Returns the number of tokens in `owner`'s account. | |
*/ | |
function balanceOf(address owner) public view virtual override returns (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) internal view returns (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) internal view returns (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) internal view returns (uint64) { | |
return uint64(_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) internal virtual { | |
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. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (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. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the token collection symbol. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. | |
*/ | |
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { | |
if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); | |
string memory baseURI = _baseURI(); | |
return bytes(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() internal view virtual returns (string memory) { | |
return ''; | |
} | |
// ============================================================= | |
// OWNERSHIPS OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) public view virtual override returns (address) { | |
return address(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) internal view virtual returns (TokenOwnership memory) { | |
return _unpackedOwnership(_packedOwnershipOf(tokenId)); | |
} | |
/** | |
* @dev Returns the unpacked `TokenOwnership` struct at `index`. | |
*/ | |
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { | |
return _unpackedOwnership(_packedOwnerships[index]); | |
} | |
/** | |
* @dev Initializes the ownership slot minted at `index` for efficiency purposes. | |
*/ | |
function _initializeOwnershipAt(uint256 index) internal virtual { | |
if (_packedOwnerships[index] == 0) { | |
_packedOwnerships[index] = _packedOwnershipOf(index); | |
} | |
} | |
/** | |
* Returns the packed ownership data of `tokenId`. | |
*/ | |
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { | |
uint256 curr = tokenId; | |
unchecked { | |
if (_startTokenId() <= curr) | |
if (curr < _currentIndex) { | |
uint256 packed = _packedOwnerships[curr]; | |
// If not burned. | |
if (packed & _BITMASK_BURNED == 0) { | |
// 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, `curr` will not underflow. | |
// | |
// We can directly compare the packed value. | |
// If the address is zero, packed will be zero. | |
while (packed == 0) { | |
packed = _packedOwnerships[--curr]; | |
} | |
return packed; | |
} | |
} | |
} | |
revert OwnerQueryForNonexistentToken(); | |
} | |
/** | |
* @dev Returns the unpacked `TokenOwnership` struct from `packed`. | |
*/ | |
function _unpackedOwnership(uint256 packed) private pure returns (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) private view returns (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) private pure returns (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. | |
* 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) public payable virtual override { | |
address owner = ownerOf(tokenId); | |
if (_msgSenderERC721A() != owner) | |
if (!isApprovedForAll(owner, _msgSenderERC721A())) { | |
revert ApprovalCallerNotOwnerNorApproved(); | |
} | |
_tokenApprovals[tokenId].value = to; | |
emit Approval(owner, to, tokenId); | |
} | |
/** | |
* @dev Returns the account approved for `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function getApproved(uint256 tokenId) public view virtual override returns (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. | |
*/ | |
function setApprovalForAll(address operator, bool approved) public virtual override { | |
_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}. | |
*/ | |
function isApprovedForAll(address owner, address operator) public view virtual override returns (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) internal view virtual returns (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 | |
) private pure returns (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) | |
private | |
view | |
returns (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. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public payable virtual override { | |
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, '')`. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public payable virtual override { | |
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. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) public payable virtual override { | |
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( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
/** | |
* @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( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
/** | |
* @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( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) private returns (bool) { | |
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns ( | |
bytes4 retval | |
) { | |
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; | |
} catch (bytes memory 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) internal virtual { | |
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) internal virtual { | |
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, | |
bytes memory _data | |
) internal virtual { | |
_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) internal virtual { | |
_safeMint(to, quantity, ''); | |
} | |
// ============================================================= | |
// BURN OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Equivalent to `_burn(tokenId, false)`. | |
*/ | |
function _burn(uint256 tokenId) internal virtual { | |
_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) internal virtual { | |
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); | |
address from = 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) internal virtual { | |
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( | |
address from, | |
address to, | |
uint24 previousExtraData | |
) internal view virtual returns (uint24) {} | |
/** | |
* @dev Returns the next extra data for the packed ownership data. | |
* The returned result is shifted into position. | |
*/ | |
function _nextExtraData( | |
address from, | |
address to, | |
uint256 prevOwnershipPacked | |
) private view returns (uint256) { | |
uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); | |
return uint256(_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() internal view virtual returns (address) { | |
return msg.sender; | |
} | |
/** | |
* @dev Converts a uint256 to its ASCII string decimal representation. | |
*/ | |
function _toString(uint256 value) internal pure virtual returns (string memory 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-ignore | |
for { 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-ignore | |
if iszero(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) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// ERC721A Contracts v4.2.3 | |
// Creator: Chiru Labs | |
pragma solidity ^0.8.4; | |
/** | |
* @dev Interface of ERC721A. | |
*/ | |
interface IERC721A { | |
/** | |
* The caller must own the token or be an approved operator. | |
*/ | |
error ApprovalCallerNotOwnerNorApproved(); | |
/** | |
* The token does not exist. | |
*/ | |
error ApprovalQueryForNonexistentToken(); | |
/** | |
* Cannot query the balance for the zero address. | |
*/ | |
error BalanceQueryForZeroAddress(); | |
/** | |
* Cannot mint to the zero address. | |
*/ | |
error MintToZeroAddress(); | |
/** | |
* The quantity of tokens minted must be more than zero. | |
*/ | |
error MintZeroQuantity(); | |
/** | |
* The token does not exist. | |
*/ | |
error OwnerQueryForNonexistentToken(); | |
/** | |
* The caller must own the token or be an approved operator. | |
*/ | |
error TransferCallerNotOwnerNorApproved(); | |
/** | |
* The token must be owned by `from`. | |
*/ | |
error TransferFromIncorrectOwner(); | |
/** | |
* Cannot safely transfer to a contract that does not implement the | |
* ERC721Receiver interface. | |
*/ | |
error TransferToNonERC721ReceiverImplementer(); | |
/** | |
* Cannot transfer to the zero address. | |
*/ | |
error TransferToZeroAddress(); | |
/** | |
* The token does not exist. | |
*/ | |
error URIQueryForNonexistentToken(); | |
/** | |
* The `quantity` minted with ERC2309 exceeds the safety limit. | |
*/ | |
error MintERC2309QuantityExceedsLimit(); | |
/** | |
* The `extraData` cannot be set on an unintialized ownership slot. | |
*/ | |
error OwnershipNotInitializedForExtraData(); | |
// ============================================================= | |
// STRUCTS | |
// ============================================================= | |
struct TokenOwnership { | |
// 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}. | |
*/ | |
function totalSupply() external view returns (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. | |
*/ | |
function supportsInterface(bytes4 interfaceId) external view returns (bool); | |
// ============================================================= | |
// IERC721 | |
// ============================================================= | |
/** | |
* @dev Emitted when `tokenId` token is transferred from `from` to `to`. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. | |
*/ | |
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables or disables | |
* (`approved`) `operator` to manage all of its assets. | |
*/ | |
event ApprovalForAll(address indexed owner, address indexed operator, bool approved); | |
/** | |
* @dev Returns the number of tokens in `owner`'s account. | |
*/ | |
function balanceOf(address owner) external view returns (uint256 balance); | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) external view returns (address owner); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, | |
* checking first that contract recipients are aware of the ERC721 protocol | |
* to prevent tokens from being forever locked. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be have been allowed to move | |
* this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement | |
* {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes calldata data | |
) external payable; | |
/** | |
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external payable; | |
/** | |
* @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. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external payable; | |
/** | |
* @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 payable; | |
/** | |
* @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); | |
// ============================================================= | |
// IERC721Metadata | |
// ============================================================= | |
/** | |
* @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); | |
// ============================================================= | |
// 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. | |
*/ | |
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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/utils/cryptography/ECDSA.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
/** | |
@title SignatureChecker | |
@notice Additional functions for EnumerableSet.Addresset that require a valid | |
ECDSA signature of a standardized message, signed by any member of the set. | |
*/ | |
library SignatureChecker { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation + signature verification | |
+ marking message as used | |
@param signers Set of addresses from which signatures are accepted. | |
@param usedMessages Set of already-used messages. | |
@param signature ECDSA signature of message. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes memory data, | |
bytes calldata signature, | |
mapping(bytes32 => bool) storage usedMessages | |
) internal { | |
bytes32 message = generateMessage(data); | |
require( | |
!usedMessages[message], | |
"SignatureChecker: Message already used" | |
); | |
usedMessages[message] = true; | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation + signature verification. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes memory data, | |
bytes calldata signature | |
) internal view { | |
bytes32 message = generateMessage(data); | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation from address + | |
signature verification. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
address a, | |
bytes calldata signature | |
) internal view { | |
bytes32 message = generateMessage(abi.encodePacked(a)); | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Common validator logic, checking if the recovered signer is | |
contained in the signers AddressSet. | |
*/ | |
function validSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes32 message, | |
bytes calldata signature | |
) internal view returns (bool) { | |
return signers.contains(ECDSA.recover(message, signature)); | |
} | |
/** | |
@notice Requires that the recovered signer is contained in the signers | |
AddressSet. | |
@dev Convenience wrapper that reverts if the signature validation fails. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes32 message, | |
bytes calldata signature | |
) internal view { | |
require( | |
validSignature(signers, message, signature), | |
"SignatureChecker: Invalid signature" | |
); | |
} | |
/** | |
@notice Generates a message for a given data input that will be signed | |
off-chain using ECDSA. | |
@dev For multiple data fields, a standard concatenation using | |
`abi.encodePacked` is commonly used to build data. | |
*/ | |
function generateMessage(bytes memory data) | |
internal | |
pure | |
returns (bytes32) | |
{ | |
return ECDSA.toEthSignedMessageHash(data); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "@openzeppelin/contracts/access/Ownable.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
/** | |
@title SignerManager | |
@notice Manges addition and removal of a core set of addresses from which | |
valid ECDSA signatures can be accepted; see SignatureChecker. | |
*/ | |
contract SignerManager is Ownable { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
/** | |
@dev Addresses from which signatures can be accepted. | |
*/ | |
EnumerableSet.AddressSet internal signers; | |
/** | |
@notice Add an address to the set of accepted signers. | |
*/ | |
function addSigner(address signer) external onlyOwner { | |
signers.add(signer); | |
} | |
/** | |
@notice Remove an address previously added with addSigner(). | |
*/ | |
function removeSigner(address signer) external onlyOwner { | |
signers.remove(signer); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"; | |
/** | |
@notice ERC721 extension that overrides the OpenZeppelin _baseURI() function to | |
return a prefix that can be set by the contract owner. | |
*/ | |
contract BaseTokenURI is Ownable { | |
/// @notice Base token URI used as a prefix by tokenURI(). | |
string public baseTokenURI; | |
constructor(string memory _baseTokenURI) { | |
setBaseTokenURI(_baseTokenURI); | |
} | |
/// @notice Sets the base token URI prefix. | |
function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner { | |
baseTokenURI = _baseTokenURI; | |
} | |
/** | |
@notice Concatenates and returns the base token URI and the token ID without | |
any additional characters (e.g. a slash). | |
@dev This requires that an inheriting contract that also inherits from OZ's | |
ERC721 will have to override both contracts; although we could simply | |
require that users implement their own _baseURI() as here, this can easily | |
be forgotten and the current approach guides them with compiler errors. This | |
favours the latter half of "APIs should be easy to use and hard to misuse" | |
from https://www.infoq.com/articles/API-Design-Joshua-Bloch/. | |
*/ | |
function _baseURI() internal view virtual returns (string memory) { | |
return baseTokenURI; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "erc721a/contracts/ERC721A.sol"; | |
import "../utils/OwnerPausable.sol"; | |
import "@openzeppelin/contracts/token/common/ERC2981.sol"; | |
/** | |
@notice An ERC721A contract with common functionality: | |
- Pausable with toggling functions exposed to Owner only | |
- ERC2981 royalties | |
*/ | |
contract ERC721ACommon is ERC721A, OwnerPausable, ERC2981 { | |
constructor( | |
string memory name, | |
string memory symbol, | |
address payable royaltyReciever, | |
uint96 royaltyBasisPoints | |
) ERC721A(name, symbol) { | |
_setDefaultRoyalty(royaltyReciever, royaltyBasisPoints); | |
} | |
/// @notice Requires that the token exists. | |
modifier tokenExists(uint256 tokenId) { | |
require(ERC721A._exists(tokenId), "ERC721ACommon: Token doesn't exist"); | |
_; | |
} | |
/// @notice Requires that msg.sender owns or is approved for the token. | |
modifier onlyApprovedOrOwner(uint256 tokenId) { | |
require( | |
_ownershipOf(tokenId).addr == _msgSender() || | |
getApproved(tokenId) == _msgSender(), | |
"ERC721ACommon: Not approved nor owner" | |
); | |
_; | |
} | |
function _beforeTokenTransfers( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual override { | |
require(!paused(), "ERC721ACommon: paused"); | |
super._beforeTokenTransfers(from, to, startTokenId, quantity); | |
} | |
/// @notice Overrides supportsInterface as required by inheritance. | |
function supportsInterface(bytes4 interfaceId) | |
public | |
view | |
virtual | |
override(ERC721A, ERC2981) | |
returns (bool) | |
{ | |
return | |
ERC721A.supportsInterface(interfaceId) || | |
ERC2981.supportsInterface(interfaceId); | |
} | |
/// @notice Sets the royalty receiver and percentage (in units of basis | |
/// points = 0.01%). | |
function setDefaultRoyalty(address receiver, uint96 basisPoints) | |
public | |
virtual | |
onlyOwner | |
{ | |
_setDefaultRoyalty(receiver, basisPoints); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "@openzeppelin/contracts/interfaces/IERC721.sol"; | |
import "@openzeppelin/contracts/utils/Strings.sol"; | |
import "@openzeppelin/contracts/utils/structs/BitMaps.sol"; | |
/** | |
@notice Allows holders of ERC721 tokens to redeem rights to some claim; for | |
example, the right to mint a token of some other collection. | |
*/ | |
library ERC721Redeemer { | |
using BitMaps for BitMaps.BitMap; | |
using Strings for uint256; | |
/** | |
@notice Storage value to track already-claimed redemptions for a specific | |
token collection. | |
*/ | |
struct Claims { | |
/** | |
@dev This field MUST NOT be considered part of the public API. Instead, | |
prefer `using ERC721Redeemer for ERC721Redeemer.Claims` and utilise the | |
provided functions. | |
*/ | |
mapping(uint256 => uint256) _total; | |
} | |
/** | |
@notice Storage value to track already-claimed redemptions for a specific | |
token collection, given that there is only a single claim allowed per | |
tokenId. | |
*/ | |
struct SingleClaims { | |
/** | |
@dev This field MUST NOT be considered part of the public API. Instead, | |
prefer `using ERC721Redeemer for ERC721Redeemer.SingleClaims` and | |
utilise the provided functions. | |
*/ | |
BitMaps.BitMap _claimed; | |
} | |
/** | |
@notice Emitted when a token's claim is redeemed. | |
*/ | |
event Redemption( | |
IERC721 indexed token, | |
address indexed redeemer, | |
uint256 tokenId, | |
uint256 n | |
); | |
/** | |
@notice Checks that the redeemer is allowed to redeem the claims for the | |
tokenIds by being either the owner or approved address for all tokenIds, and | |
updates the Claims to reflect this. | |
@dev For more efficient gas usage, recurring values in tokenIds SHOULD be | |
adjacent to one another as this will batch expensive operations. The | |
simplest way to achieve this is by sorting tokenIds. | |
@param tokenIds The token IDs for which the claims are being redeemed. If | |
maxAllowance > 1 then identical tokenIds can be passed more than once; see | |
dev comments. | |
@return The number of redeemed claims; either 0 or tokenIds.length; | |
*/ | |
function redeem( | |
Claims storage claims, | |
uint256 maxAllowance, | |
address redeemer, | |
IERC721 token, | |
uint256[] calldata tokenIds | |
) internal returns (uint256) { | |
if (maxAllowance == 0 || tokenIds.length == 0) { | |
return 0; | |
} | |
// See comment for `endSameId`. | |
bool multi = maxAllowance > 1; | |
for ( | |
uint256 i = 0; | |
i < tokenIds.length; /* note increment at end */ | |
) { | |
uint256 tokenId = tokenIds[i]; | |
requireOwnerOrApproved(token, tokenId, redeemer); | |
uint256 n = 1; | |
if (multi) { | |
// If allowed > 1 we can save on expensive operations like | |
// checking ownership / remaining allowance by batching equal | |
// tokenIds. The algorithm assumes that equal IDs are adjacent | |
// in the array. | |
uint256 endSameId; | |
for ( | |
endSameId = i + 1; | |
endSameId < tokenIds.length && | |
tokenIds[endSameId] == tokenId; | |
endSameId++ | |
) {} // solhint-disable-line no-empty-blocks | |
n = endSameId - i; | |
} | |
claims._total[tokenId] += n; | |
if (claims._total[tokenId] > maxAllowance) { | |
revertWithTokenId( | |
"ERC721Redeemer: over allowance for", | |
tokenId | |
); | |
} | |
i += n; | |
emit Redemption(token, redeemer, tokenId, n); | |
} | |
return tokenIds.length; | |
} | |
/** | |
@notice Checks that the redeemer is allowed to redeem the single claim for | |
each of the tokenIds by being either the owner or approved address for all | |
tokenIds, and updates the SingleClaims to reflect this. | |
@param tokenIds The token IDs for which the claims are being redeemed. Only | |
a single claim can be made against a tokenId. | |
@return The number of redeemed claims; either 0 or tokenIds.length; | |
*/ | |
function redeem( | |
SingleClaims storage claims, | |
address redeemer, | |
IERC721 token, | |
uint256[] calldata tokenIds | |
) internal returns (uint256) { | |
if (tokenIds.length == 0) { | |
return 0; | |
} | |
for (uint256 i = 0; i < tokenIds.length; i++) { | |
uint256 tokenId = tokenIds[i]; | |
requireOwnerOrApproved(token, tokenId, redeemer); | |
if (claims._claimed.get(tokenId)) { | |
revertWithTokenId( | |
"ERC721Redeemer: over allowance for", | |
tokenId | |
); | |
} | |
claims._claimed.set(tokenId); | |
emit Redemption(token, redeemer, tokenId, 1); | |
} | |
return tokenIds.length; | |
} | |
/** | |
@dev Reverts if neither the owner nor approved for the tokenId. | |
*/ | |
function requireOwnerOrApproved( | |
IERC721 token, | |
uint256 tokenId, | |
address redeemer | |
) private view { | |
if ( | |
token.ownerOf(tokenId) != redeemer && | |
token.getApproved(tokenId) != redeemer | |
) { | |
revertWithTokenId( | |
"ERC721Redeemer: not approved nor owner of", | |
tokenId | |
); | |
} | |
} | |
/** | |
@notice Reverts with the concatenation of revertMsg and tokenId.toString(). | |
@dev Used to save gas by constructing the revert message only as required, | |
instead of passing it to require(). | |
*/ | |
function revertWithTokenId(string memory revertMsg, uint256 tokenId) | |
private | |
pure | |
{ | |
revert(string(abi.encodePacked(revertMsg, " ", tokenId.toString()))); | |
} | |
/** | |
@notice Returns the number of claimed redemptions for the token. | |
*/ | |
function claimed(Claims storage claims, uint256 tokenId) | |
internal | |
view | |
returns (uint256) | |
{ | |
return claims._total[tokenId]; | |
} | |
/** | |
@notice Returns whether the token has had a claim made against it. | |
*/ | |
function claimed(SingleClaims storage claims, uint256 tokenId) | |
internal | |
view | |
returns (bool) | |
{ | |
return claims._claimed.get(tokenId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "./Seller.sol"; | |
/// @notice A Seller with fixed per-item price. | |
abstract contract FixedPriceSeller is Seller { | |
constructor( | |
uint256 _price, | |
Seller.SellerConfig memory sellerConfig, | |
address payable _beneficiary | |
) Seller(sellerConfig, _beneficiary) { | |
setPrice(_price); | |
} | |
/** | |
@notice The fixed per-item price. | |
@dev Fixed as in not changing with time nor number of items, but not a | |
constant. | |
*/ | |
uint256 public price; | |
/// @notice Sets the per-item price. | |
function setPrice(uint256 _price) public onlyOwner { | |
price = _price; | |
} | |
/** | |
@notice Override of Seller.cost() with fixed price. | |
@dev The second parameter, metadata propagated from the call to _purchase(), | |
is ignored. | |
*/ | |
function cost(uint256 n, uint256) public view override returns (uint256) { | |
return n * price; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
/** | |
@dev Note that the address limits are vulnerable to wallet farming. | |
@param maxPerAddress Unlimited if zero. | |
@param maxPerTex Unlimited if zero. | |
@param freeQuota Maximum number that can be purchased free of charge by | |
the contract owner. | |
@param reserveFreeQuota Whether to excplitly reserve the freeQuota amount | |
and not let it be eroded by regular purchases. | |
@param lockFreeQuota If true, calls to setSellerConfig() will ignore changes | |
to freeQuota. Can be locked after initial setting, but not unlocked. This | |
allows a contract owner to commit to a maximum number of reserved items. | |
@param lockTotalInventory Similar to lockFreeQuota but applied to | |
totalInventory. | |
*/ | |
struct SellerConfig { | |
uint256 totalInventory; | |
uint256 maxPerAddress; | |
uint256 maxPerTx; | |
uint248 freeQuota; | |
bool reserveFreeQuota; | |
bool lockFreeQuota; | |
bool lockTotalInventory; | |
} | |
constructor(SellerConfig memory config, address payable _beneficiary) { | |
setSellerConfig(config); | |
setBeneficiary(_beneficiary); | |
} | |
/// @notice Configuration of purchase limits. | |
SellerConfig public sellerConfig; | |
/// @notice Sets the seller config. | |
function setSellerConfig(SellerConfig memory config) public onlyOwner { | |
require( | |
config.totalInventory >= config.freeQuota, | |
"Seller: excessive free quota" | |
); | |
require( | |
config.totalInventory >= _totalSold.current(), | |
"Seller: inventory < already sold" | |
); | |
require( | |
config.freeQuota >= purchasedFreeOfCharge.current(), | |
"Seller: free quota < already used" | |
); | |
// Overriding the in-memory fields before copying the whole struct, as | |
// against writing individual fields, gives a greater guarantee of | |
// correctness as the code is simpler to read. | |
if (sellerConfig.lockTotalInventory) { | |
config.lockTotalInventory = true; | |
config.totalInventory = sellerConfig.totalInventory; | |
} | |
if (sellerConfig.lockFreeQuota) { | |
config.lockFreeQuota = true; | |
config.freeQuota = sellerConfig.freeQuota; | |
} | |
sellerConfig = config; | |
} | |
/// @notice Recipient of revenues. | |
address payable public beneficiary; | |
/// @notice Sets the recipient of revenues. | |
function setBeneficiary(address payable _beneficiary) public onlyOwner { | |
beneficiary = _beneficiary; | |
} | |
/** | |
@dev Must return the current cost of a batch of items. This may be constant | |
or, for example, decreasing for a Dutch auction or increasing for a bonding | |
curve. | |
@param n The number of items being purchased. | |
@param metadata Arbitrary data, propagated by the call to _purchase() that | |
can be used to charge different prices. This value is a uint256 instead of | |
bytes as this allows simple passing of a set cost (see | |
ArbitraryPriceSeller). | |
*/ | |
function cost(uint256 n, uint256 metadata) | |
public | |
view | |
virtual | |
returns (uint256); | |
/** | |
@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 POST-purchase amount to allow for the | |
checks-effects-interactions (ECI) pattern as _handlePurchase() may include | |
an interaction. _handlePurchase() MUST itself implement the CEI pattern. | |
@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() public view returns (uint256) { | |
return _totalSold.current(); | |
} | |
/** | |
@notice Tracks the number of items already bought by an address, regardless | |
of transferring out (in the case of ERC721). | |
@dev This isn't public as it may be skewed due to differences in msg.sender | |
and tx.origin, which it treats in the same way such that | |
sum(_bought)>=totalSold(). | |
*/ | |
mapping(address => uint256) private _bought; | |
/** | |
@notice Returns min(n, max(extra items addr can purchase)) and reverts if 0. | |
@param zeroMsg The message with which to revert on 0 extra. | |
*/ | |
function _capExtra( | |
uint256 n, | |
address addr, | |
string memory zeroMsg | |
) internal view returns (uint256) { | |
uint256 extra = sellerConfig.maxPerAddress - _bought[addr]; | |
if (extra == 0) { | |
revert(string(abi.encodePacked("Seller: ", zeroMsg))); | |
} | |
return Math.min(n, extra); | |
} | |
/// @notice Emitted when a buyer is refunded. | |
event Refund(address indexed buyer, uint256 amount); | |
/// @notice Emitted on all purchases of non-zero amount. | |
event Revenue( | |
address indexed beneficiary, | |
uint256 numPurchased, | |
uint256 amount | |
); | |
/// @notice Tracks number of items purchased free of charge. | |
Monotonic.Increaser private purchasedFreeOfCharge; | |
/** | |
@notice Allows the contract owner to purchase without payment, within the | |
quota enforced by the SellerConfig. | |
*/ | |
function purchaseFreeOfCharge(address to, uint256 n) | |
public | |
onlyOwner | |
whenNotPaused | |
{ | |
/** | |
* ##### CHECKS | |
*/ | |
uint256 freeQuota = sellerConfig.freeQuota; | |
n = Math.min(n, freeQuota - purchasedFreeOfCharge.current()); | |
require(n > 0, "Seller: Free quota exceeded"); | |
uint256 totalInventory = sellerConfig.totalInventory; | |
n = Math.min(n, totalInventory - _totalSold.current()); | |
require(n > 0, "Seller: Sold out"); | |
/** | |
* ##### EFFECTS | |
*/ | |
_totalSold.add(n); | |
purchasedFreeOfCharge.add(n); | |
/** | |
* ##### INTERACTIONS | |
*/ | |
_handlePurchase(to, n, true); | |
assert(_totalSold.current() <= totalInventory); | |
assert(purchasedFreeOfCharge.current() <= freeQuota); | |
} | |
/** | |
@notice Convenience function for calling _purchase() with empty costMetadata | |
when unneeded. | |
*/ | |
function _purchase(address to, uint256 requested) internal virtual { | |
_purchase(to, requested, 0); | |
} | |
/** | |
@notice Enforces all purchase limits (counts and costs) before calling | |
_handlePurchase(), after which the received funds are disbursed to the | |
beneficiary, less any required refunds. | |
@param to The final recipient of the item(s). | |
@param requested The number of items requested for purchase, which MAY be | |
reduced when passed to _handlePurchase(). | |
@param costMetadata Arbitrary data, propagated in the call to cost(), to be | |
optionally used in determining the price. | |
*/ | |
function _purchase( | |
address to, | |
uint256 requested, | |
uint256 costMetadata | |
) internal nonReentrant whenNotPaused { | |
/** | |
* ##### CHECKS | |
*/ | |
SellerConfig memory config = sellerConfig; | |
uint256 n = config.maxPerTx == 0 | |
? requested | |
: Math.min(requested, config.maxPerTx); | |
uint256 maxAvailable; | |
uint256 sold; | |
if (config.reserveFreeQuota) { | |
maxAvailable = config.totalInventory - config.freeQuota; | |
sold = _totalSold.current() - purchasedFreeOfCharge.current(); | |
} else { | |
maxAvailable = config.totalInventory; | |
sold = _totalSold.current(); | |
} | |
n = Math.min(n, maxAvailable - sold); | |
require(n > 0, "Seller: Sold out"); | |
if (config.maxPerAddress > 0) { | |
bool alsoLimitSender = _msgSender() != to; | |
// solhint-disable-next-line avoid-tx-origin | |
bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to; | |
n = _capExtra(n, to, "Buyer limit"); | |
if (alsoLimitSender) { | |
n = _capExtra(n, _msgSender(), "Sender limit"); | |
} | |
if (alsoLimitOrigin) { | |
// solhint-disable-next-line avoid-tx-origin | |
n = _capExtra(n, tx.origin, "Origin limit"); | |
} | |
_bought[to] += n; | |
if (alsoLimitSender) { | |
_bought[_msgSender()] += n; | |
} | |
if (alsoLimitOrigin) { | |
// solhint-disable-next-line avoid-tx-origin | |
_bought[tx.origin] += n; | |
} | |
} | |
uint256 _cost = cost(n, costMetadata); | |
if (msg.value < _cost) { | |
revert( | |
string( | |
abi.encodePacked( | |
"Seller: Costs ", | |
(_cost / 1e9).toString(), | |
" GWei" | |
) | |
) | |
); | |
} | |
/** | |
* ##### EFFECTS | |
*/ | |
_totalSold.add(n); | |
assert(_totalSold.current() <= config.totalInventory); | |
/** | |
* ##### INTERACTIONS | |
*/ | |
// As _handlePurchase() is often an ERC721 safeMint(), it constitutes an | |
// interaction. | |
_handlePurchase(to, n, false); | |
// Ideally we'd be using a PullPayment here, but the user experience is | |
// poor when there's a variable cost or the number of items purchased | |
// has been capped. We've addressed reentrancy with both a nonReentrant | |
// modifier and the checks, effects, interactions pattern. | |
if (_cost > 0) { | |
beneficiary.sendValue(_cost); | |
emit Revenue(beneficiary, n, _cost); | |
} | |
if (msg.value > _cost) { | |
address payable reimburse = payable(_msgSender()); | |
uint256 refund = msg.value - _cost; | |
// Using Address.sendValue() here would mask the revertMsg upon | |
// reentrancy, but we want to expose it to allow for more precise | |
// testing. This otherwise uses the exact same pattern as | |
// Address.sendValue(). | |
// solhint-disable-next-line avoid-low-level-calls | |
(bool success, bytes memory returnData) = reimburse.call{ | |
value: refund | |
}(""); | |
// Although `returnData` will have a spurious prefix, all we really | |
// care about is that it contains the ReentrancyGuard reversion | |
// message so we can check in the tests. | |
require(success, string(returnData)); | |
emit Refund(reimburse, refund); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControl.sol"; | |
import "../utils/Context.sol"; | |
import "../utils/Strings.sol"; | |
import "../utils/introspection/ERC165.sol"; | |
/** | |
* @dev Contract module that allows children to implement role-based access | |
* control mechanisms. This is a lightweight version that doesn't allow enumerating role | |
* members except through off-chain means by accessing the contract event logs. Some | |
* applications may benefit from on-chain enumerability, for those cases see | |
* {AccessControlEnumerable}. | |
* | |
* Roles are referred to by their `bytes32` identifier. These should be exposed | |
* in the external API and be unique. The best way to achieve this is by | |
* using `public constant` hash digests: | |
* | |
* ``` | |
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); | |
* ``` | |
* | |
* Roles can be used to represent a set of permissions. To restrict access to a | |
* function call, use {hasRole}: | |
* | |
* ``` | |
* function foo() public { | |
* require(hasRole(MY_ROLE, msg.sender)); | |
* ... | |
* } | |
* ``` | |
* | |
* Roles can be granted and revoked dynamically via the {grantRole} and | |
* {revokeRole} functions. Each role has an associated admin role, and only | |
* accounts that have a role's admin role can call {grantRole} and {revokeRole}. | |
* | |
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means | |
* that only accounts with this role will be able to grant or revoke other | |
* roles. More complex role relationships can be created by using | |
* {_setRoleAdmin}. | |
* | |
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to | |
* grant and revoke this role. Extra precautions should be taken to secure | |
* accounts that have been granted it. | |
*/ | |
abstract contract AccessControl is Context, IAccessControl, ERC165 { | |
struct RoleData { | |
mapping(address => bool) members; | |
bytes32 adminRole; | |
} | |
mapping(bytes32 => RoleData) private _roles; | |
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; | |
/** | |
* @dev Modifier that checks that an account has a specific role. Reverts | |
* with a standardized message including the required role. | |
* | |
* The format of the revert reason is given by the following regular expression: | |
* | |
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ | |
* | |
* _Available since v4.1._ | |
*/ | |
modifier onlyRole(bytes32 role) { | |
_checkRole(role); | |
_; | |
} | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev Returns `true` if `account` has been granted `role`. | |
*/ | |
function hasRole(bytes32 role, address account) public view virtual override returns (bool) { | |
return _roles[role].members[account]; | |
} | |
/** | |
* @dev Revert with a standard message if `_msgSender()` is missing `role`. | |
* Overriding this function changes the behavior of the {onlyRole} modifier. | |
* | |
* Format of the revert message is described in {_checkRole}. | |
* | |
* _Available since v4.6._ | |
*/ | |
function _checkRole(bytes32 role) internal view virtual { | |
_checkRole(role, _msgSender()); | |
} | |
/** | |
* @dev Revert with a standard message if `account` is missing `role`. | |
* | |
* The format of the revert reason is given by the following regular expression: | |
* | |
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ | |
*/ | |
function _checkRole(bytes32 role, address account) internal view virtual { | |
if (!hasRole(role, account)) { | |
revert( | |
string( | |
abi.encodePacked( | |
"AccessControl: account ", | |
Strings.toHexString(uint160(account), 20), | |
" is missing role ", | |
Strings.toHexString(uint256(role), 32) | |
) | |
) | |
); | |
} | |
} | |
/** | |
* @dev Returns the admin role that controls `role`. See {grantRole} and | |
* {revokeRole}. | |
* | |
* To change a role's admin, use {_setRoleAdmin}. | |
*/ | |
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { | |
return _roles[role].adminRole; | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
* | |
* May emit a {RoleGranted} event. | |
*/ | |
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* If `account` had been granted `role`, emits a {RoleRevoked} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
* | |
* May emit a {RoleRevoked} event. | |
*/ | |
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from the calling account. | |
* | |
* Roles are often managed via {grantRole} and {revokeRole}: this function's | |
* purpose is to provide a mechanism for accounts to lose their privileges | |
* if they are compromised (such as when a trusted device is misplaced). | |
* | |
* If the calling account had been revoked `role`, emits a {RoleRevoked} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must be `account`. | |
* | |
* May emit a {RoleRevoked} event. | |
*/ | |
function renounceRole(bytes32 role, address account) public virtual override { | |
require(account == _msgSender(), "AccessControl: can only renounce roles for self"); | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. Note that unlike {grantRole}, this function doesn't perform any | |
* checks on the calling account. | |
* | |
* May emit a {RoleGranted} event. | |
* | |
* [WARNING] | |
* ==== | |
* This function should only be called from the constructor when setting | |
* up the initial roles for the system. | |
* | |
* Using this function in any other way is effectively circumventing the admin | |
* system imposed by {AccessControl}. | |
* ==== | |
* | |
* NOTE: This function is deprecated in favor of {_grantRole}. | |
*/ | |
function _setupRole(bytes32 role, address account) internal virtual { | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Sets `adminRole` as ``role``'s admin role. | |
* | |
* Emits a {RoleAdminChanged} event. | |
*/ | |
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { | |
bytes32 previousAdminRole = getRoleAdmin(role); | |
_roles[role].adminRole = adminRole; | |
emit RoleAdminChanged(role, previousAdminRole, adminRole); | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* Internal function without access restriction. | |
* | |
* May emit a {RoleGranted} event. | |
*/ | |
function _grantRole(bytes32 role, address account) internal virtual { | |
if (!hasRole(role, account)) { | |
_roles[role].members[account] = true; | |
emit RoleGranted(role, account, _msgSender()); | |
} | |
} | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* Internal function without access restriction. | |
* | |
* May emit a {RoleRevoked} event. | |
*/ | |
function _revokeRole(bytes32 role, address account) internal virtual { | |
if (hasRole(role, account)) { | |
_roles[role].members[account] = false; | |
emit RoleRevoked(role, account, _msgSender()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControlEnumerable.sol"; | |
import "./AccessControl.sol"; | |
import "../utils/structs/EnumerableSet.sol"; | |
/** | |
* @dev Extension of {AccessControl} that allows enumerating the members of each role. | |
*/ | |
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev Returns one of the accounts that have `role`. `index` must be a | |
* value between 0 and {getRoleMemberCount}, non-inclusive. | |
* | |
* Role bearers are not sorted in any particular way, and their ordering may | |
* change at any point. | |
* | |
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure | |
* you perform all queries on the same block. See the following | |
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] | |
* for more information. | |
*/ | |
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { | |
return _roleMembers[role].at(index); | |
} | |
/** | |
* @dev Returns the number of accounts that have `role`. Can be used | |
* together with {getRoleMember} to enumerate all bearers of a role. | |
*/ | |
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { | |
return _roleMembers[role].length(); | |
} | |
/** | |
* @dev Overload {_grantRole} to track enumerable memberships | |
*/ | |
function _grantRole(bytes32 role, address account) internal virtual override { | |
super._grantRole(role, account); | |
_roleMembers[role].add(account); | |
} | |
/** | |
* @dev Overload {_revokeRole} to track enumerable memberships | |
*/ | |
function _revokeRole(bytes32 role, address account) internal virtual override { | |
super._revokeRole(role, account); | |
_roleMembers[role].remove(account); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev External interface of AccessControl declared to support ERC165 detection. | |
*/ | |
interface IAccessControl { | |
/** | |
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` | |
* | |
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite | |
* {RoleAdminChanged} not being emitted signaling this. | |
* | |
* _Available since v3.1._ | |
*/ | |
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); | |
/** | |
* @dev Emitted when `account` is granted `role`. | |
* | |
* `sender` is the account that originated the contract call, an admin role | |
* bearer except when using {AccessControl-_setupRole}. | |
*/ | |
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); | |
/** | |
* @dev Emitted when `account` is revoked `role`. | |
* | |
* `sender` is the account that originated the contract call: | |
* - if using `revokeRole`, it is the admin role bearer | |
* - if using `renounceRole`, it is the role bearer (i.e. `account`) | |
*/ | |
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); | |
/** | |
* @dev Returns `true` if `account` has been granted `role`. | |
*/ | |
function hasRole(bytes32 role, address account) external view returns (bool); | |
/** | |
* @dev Returns the admin role that controls `role`. See {grantRole} and | |
* {revokeRole}. | |
* | |
* To change a role's admin, use {AccessControl-_setRoleAdmin}. | |
*/ | |
function getRoleAdmin(bytes32 role) external view returns (bytes32); | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function grantRole(bytes32 role, address account) external; | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* If `account` had been granted `role`, emits a {RoleRevoked} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function revokeRole(bytes32 role, address account) external; | |
/** | |
* @dev Revokes `role` from the calling account. | |
* | |
* Roles are often managed via {grantRole} and {revokeRole}: this function's | |
* purpose is to provide a mechanism for accounts to lose their privileges | |
* if they are compromised (such as when a trusted device is misplaced). | |
* | |
* If the calling account had been granted `role`, emits a {RoleRevoked} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must be `account`. | |
*/ | |
function renounceRole(bytes32 role, address account) external; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControl.sol"; | |
/** | |
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection. | |
*/ | |
interface IAccessControlEnumerable is IAccessControl { | |
/** | |
* @dev Returns one of the accounts that have `role`. `index` must be a | |
* value between 0 and {getRoleMemberCount}, non-inclusive. | |
* | |
* Role bearers are not sorted in any particular way, and their ordering may | |
* change at any point. | |
* | |
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure | |
* you perform all queries on the same block. See the following | |
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] | |
* for more information. | |
*/ | |
function getRoleMember(bytes32 role, uint256 index) external view returns (address); | |
/** | |
* @dev Returns the number of accounts that have `role`. Can be used | |
* together with {getRoleMember} to enumerate all bearers of a role. | |
*/ | |
function getRoleMemberCount(bytes32 role) external view returns (uint256); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol) | |
pragma solidity ^0.8.0; | |
import "../utils/introspection/IERC165.sol"; | |
/** | |
* @dev Interface for the NFT Royalty Standard. | |
* | |
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal | |
* support for royalty payments across all NFT marketplaces and ecosystem participants. | |
* | |
* _Available since v4.5._ | |
*/ | |
interface IERC2981 is IERC165 { | |
/** | |
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of | |
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange. | |
*/ | |
function royaltyInfo(uint256 tokenId, uint256 salePrice) | |
external | |
view | |
returns (address receiver, uint256 royaltyAmount); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) | |
pragma solidity ^0.8.0; | |
import "../token/ERC721/IERC721.sol"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol) | |
pragma solidity ^0.8.0; | |
import "../../interfaces/IERC2981.sol"; | |
import "../../utils/introspection/ERC165.sol"; | |
/** | |
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. | |
* | |
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for | |
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. | |
* | |
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the | |
* fee is specified in basis points by default. | |
* | |
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See | |
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to | |
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. | |
* | |
* _Available since v4.5._ | |
*/ | |
abstract contract ERC2981 is IERC2981, ERC165 { | |
struct RoyaltyInfo { | |
address receiver; | |
uint96 royaltyFraction; | |
} | |
RoyaltyInfo private _defaultRoyaltyInfo; | |
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { | |
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @inheritdoc IERC2981 | |
*/ | |
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) { | |
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; | |
if (royalty.receiver == address(0)) { | |
royalty = _defaultRoyaltyInfo; | |
} | |
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); | |
return (royalty.receiver, royaltyAmount); | |
} | |
/** | |
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a | |
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an | |
* override. | |
*/ | |
function _feeDenominator() internal pure virtual returns (uint96) { | |
return 10000; | |
} | |
/** | |
* @dev Sets the royalty information that all ids in this contract will default to. | |
* | |
* Requirements: | |
* | |
* - `receiver` cannot be the zero address. | |
* - `feeNumerator` cannot be greater than the fee denominator. | |
*/ | |
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { | |
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); | |
require(receiver != address(0), "ERC2981: invalid receiver"); | |
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); | |
} | |
/** | |
* @dev Removes default royalty information. | |
*/ | |
function _deleteDefaultRoyalty() internal virtual { | |
delete _defaultRoyaltyInfo; | |
} | |
/** | |
* @dev Sets the royalty information for a specific token id, overriding the global default. | |
* | |
* Requirements: | |
* | |
* - `receiver` cannot be the zero address. | |
* - `feeNumerator` cannot be greater than the fee denominator. | |
*/ | |
function _setTokenRoyalty( | |
uint256 tokenId, | |
address receiver, | |
uint96 feeNumerator | |
) internal virtual { | |
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); | |
require(receiver != address(0), "ERC2981: Invalid parameters"); | |
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); | |
} | |
/** | |
* @dev Resets royalty information for the token id back to the global default. | |
*/ | |
function _resetTokenRoyalty(uint256 tokenId) internal virtual { | |
delete _tokenRoyaltyInfo[tokenId]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Provides a set of functions to operate with Base64 strings. | |
* | |
* _Available since v4.5._ | |
*/ | |
library Base64 { | |
/** | |
* @dev Base64 Encoding/Decoding Table | |
*/ | |
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
/** | |
* @dev Converts a `bytes` to its Bytes64 `string` representation. | |
*/ | |
function encode(bytes memory data) internal pure returns (string memory) { | |
/** | |
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence | |
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol | |
*/ | |
if (data.length == 0) return ""; | |
// Loads the table into memory | |
string memory table = _TABLE; | |
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter | |
// and split into 4 numbers of 6 bits. | |
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up | |
// - `data.length + 2` -> Round up | |
// - `/ 3` -> Number of 3-bytes chunks | |
// - `4 *` -> 4 characters for each chunk | |
string memory result = new string(4 * ((data.length + 2) / 3)); | |
/// @solidity memory-safe-assembly | |
assembly { | |
// Prepare the lookup table (skip the first "length" byte) | |
let tablePtr := add(table, 1) | |
// Prepare result pointer, jump over length | |
let resultPtr := add(result, 32) | |
// Run over the input, 3 bytes at a time | |
for { | |
let dataPtr := data | |
let endPtr := add(data, mload(data)) | |
} lt(dataPtr, endPtr) { | |
} { | |
// Advance 3 bytes | |
dataPtr := add(dataPtr, 3) | |
let input := mload(dataPtr) | |
// To write each character, shift the 3 bytes (18 bits) chunk | |
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0) | |
// and apply logical AND with 0x3F which is the number of | |
// the previous character in the ASCII table prior to the Base64 Table | |
// The result is then added to the table to get the character to write, | |
// and finally write it in the result pointer but with a left shift | |
// of 256 (1 byte) - 8 (1 ASCII char) = 248 bits | |
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) | |
resultPtr := add(resultPtr, 1) // Advance | |
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) | |
resultPtr := add(resultPtr, 1) // Advance | |
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) | |
resultPtr := add(resultPtr, 1) // Advance | |
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) | |
resultPtr := add(resultPtr, 1) // Advance | |
} | |
// When data `bytes` is not exactly 3 bytes long | |
// it is padded with `=` characters at the end | |
switch mod(mload(data), 3) | |
case 1 { | |
mstore8(sub(resultPtr, 1), 0x3d) | |
mstore8(sub(resultPtr, 2), 0x3d) | |
} | |
case 2 { | |
mstore8(sub(resultPtr, 1), 0x3d) | |
} | |
} | |
return result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol) | |
pragma solidity ^0.8.0; | |
import "../Strings.sol"; | |
/** | |
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. | |
* | |
* These functions can be used to verify that a message was signed by the holder | |
* of the private keys of a given address. | |
*/ | |
library ECDSA { | |
enum RecoverError { | |
NoError, | |
InvalidSignature, | |
InvalidSignatureLength, | |
InvalidSignatureS, | |
InvalidSignatureV | |
} | |
function _throwError(RecoverError error) private pure { | |
if (error == RecoverError.NoError) { | |
return; // no error: do nothing | |
} else if (error == RecoverError.InvalidSignature) { | |
revert("ECDSA: invalid signature"); | |
} else if (error == RecoverError.InvalidSignatureLength) { | |
revert("ECDSA: invalid signature length"); | |
} else if (error == RecoverError.InvalidSignatureS) { | |
revert("ECDSA: invalid signature 's' value"); | |
} else if (error == RecoverError.InvalidSignatureV) { | |
revert("ECDSA: invalid signature 'v' value"); | |
} | |
} | |
/** | |
* @dev Returns the address that signed a hashed message (`hash`) with | |
* `signature` or error string. This address can then be used for verification purposes. | |
* | |
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: | |
* this function rejects them by requiring the `s` value to be in the lower | |
* half order, and the `v` value to be either 27 or 28. | |
* | |
* IMPORTANT: `hash` _must_ be the result of a hash operation for the | |
* verification to be secure: it is possible to craft signatures that | |
* recover to arbitrary addresses for non-hashed data. A safe way to ensure | |
* this is by receiving a hash of the original message (which may otherwise | |
* be too long), and then calling {toEthSignedMessageHash} on it. | |
* | |
* Documentation for signature generation: | |
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] | |
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { | |
if (signature.length == 65) { | |
bytes32 r; | |
bytes32 s; | |
uint8 v; | |
// ecrecover takes the signature parameters, and the only way to get them | |
// currently is to use assembly. | |
/// @solidity memory-safe-assembly | |
assembly { | |
r := mload(add(signature, 0x20)) | |
s := mload(add(signature, 0x40)) | |
v := byte(0, mload(add(signature, 0x60))) | |
} | |
return tryRecover(hash, v, r, s); | |
} else { | |
return (address(0), RecoverError.InvalidSignatureLength); | |
} | |
} | |
/** | |
* @dev Returns the address that signed a hashed message (`hash`) with | |
* `signature`. This address can then be used for verification purposes. | |
* | |
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: | |
* this function rejects them by requiring the `s` value to be in the lower | |
* half order, and the `v` value to be either 27 or 28. | |
* | |
* IMPORTANT: `hash` _must_ be the result of a hash operation for the | |
* verification to be secure: it is possible to craft signatures that | |
* recover to arbitrary addresses for non-hashed data. A safe way to ensure | |
* this is by receiving a hash of the original message (which may otherwise | |
* be too long), and then calling {toEthSignedMessageHash} on it. | |
*/ | |
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, signature); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. | |
* | |
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover( | |
bytes32 hash, | |
bytes32 r, | |
bytes32 vs | |
) internal pure returns (address, RecoverError) { | |
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); | |
uint8 v = uint8((uint256(vs) >> 255) + 27); | |
return tryRecover(hash, v, r, s); | |
} | |
/** | |
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. | |
* | |
* _Available since v4.2._ | |
*/ | |
function recover( | |
bytes32 hash, | |
bytes32 r, | |
bytes32 vs | |
) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, r, vs); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Overload of {ECDSA-tryRecover} that receives the `v`, | |
* `r` and `s` signature fields separately. | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover( | |
bytes32 hash, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) internal pure returns (address, RecoverError) { | |
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature | |
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines | |
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most | |
// signatures from current libraries generate a unique signature with an s-value in the lower half order. | |
// | |
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value | |
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or | |
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept | |
// these malleable signatures as well. | |
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { | |
return (address(0), RecoverError.InvalidSignatureS); | |
} | |
if (v != 27 && v != 28) { | |
return (address(0), RecoverError.InvalidSignatureV); | |
} | |
// If the signature is valid (and not malleable), return the signer address | |
address signer = ecrecover(hash, v, r, s); | |
if (signer == address(0)) { | |
return (address(0), RecoverError.InvalidSignature); | |
} | |
return (signer, RecoverError.NoError); | |
} | |
/** | |
* @dev Overload of {ECDSA-recover} that receives the `v`, | |
* `r` and `s` signature fields separately. | |
*/ | |
function recover( | |
bytes32 hash, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, v, r, s); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Returns an Ethereum Signed Message, created from a `hash`. This | |
* produces hash corresponding to the one signed with the | |
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] | |
* JSON-RPC method as part of EIP-191. | |
* | |
* See {recover}. | |
*/ | |
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { | |
// 32 is the length in bytes of hash, | |
// enforced by the type signature above | |
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); | |
} | |
/** | |
* @dev Returns an Ethereum Signed Message, created from `s`. This | |
* produces hash corresponding to the one signed with the | |
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] | |
* JSON-RPC method as part of EIP-191. | |
* | |
* See {recover}. | |
*/ | |
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { | |
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); | |
} | |
/** | |
* @dev Returns an Ethereum Signed Typed Data, created from a | |
* `domainSeparator` and a `structHash`. This produces hash corresponding | |
* to the one signed with the | |
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] | |
* JSON-RPC method as part of EIP-712. | |
* | |
* See {recover}. | |
*/ | |
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { | |
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. | |
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. | |
*/ | |
library BitMaps { | |
struct BitMap { | |
mapping(uint256 => uint256) _data; | |
} | |
/** | |
* @dev Returns whether the bit at `index` is set. | |
*/ | |
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
return bitmap._data[bucket] & mask != 0; | |
} | |
/** | |
* @dev Sets the bit at `index` to the boolean `value`. | |
*/ | |
function setTo( | |
BitMap storage bitmap, | |
uint256 index, | |
bool value | |
) internal { | |
if (value) { | |
set(bitmap, index); | |
} else { | |
unset(bitmap, index); | |
} | |
} | |
/** | |
* @dev Sets the bit at `index`. | |
*/ | |
function set(BitMap storage bitmap, uint256 index) internal { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
bitmap._data[bucket] |= mask; | |
} | |
/** | |
* @dev Unsets the bit at `index`. | |
*/ | |
function unset(BitMap storage bitmap, uint256 index) internal { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
bitmap._data[bucket] &= ~mask; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing | |
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive | |
* types. | |
* | |
* Sets have the following properties: | |
* | |
* - Elements are added, removed, and checked for existence in constant time | |
* (O(1)). | |
* - Elements are enumerated in O(n). No guarantees are made on the ordering. | |
* | |
* ``` | |
* contract Example { | |
* // Add the library methods | |
* using EnumerableSet for EnumerableSet.AddressSet; | |
* | |
* // Declare a set state variable | |
* EnumerableSet.AddressSet private mySet; | |
* } | |
* ``` | |
* | |
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) | |
* and `uint256` (`UintSet`) are supported. | |
* | |
* [WARNING] | |
* ==== | |
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. | |
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. | |
* | |
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. | |
* ==== | |
*/ | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
if (lastIndex != toDeleteIndex) { | |
bytes32 lastValue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastValue; | |
// Update the index for the moved value | |
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex | |
} | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) private view returns (bool) { | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) private view returns (bytes32) { | |
return set._values[index]; | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function _values(Set storage set) private view returns (bytes32[] memory) { | |
return set._values; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { | |
return _at(set._inner, index); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { | |
return _values(set._inner); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) internal returns (bool) { | |
return _add(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) internal returns (bool) { | |
return _remove(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) internal view returns (address) { | |
return address(uint160(uint256(_at(set._inner, index)))); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(AddressSet storage set) internal view returns (address[] memory) { | |
bytes32[] memory store = _values(set._inner); | |
address[] memory result; | |
/// @solidity memory-safe-assembly | |
assembly { | |
result := store | |
} | |
return result; | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) internal returns (bool) { | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) internal view returns (uint256) { | |
return uint256(_at(set._inner, index)); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(UintSet storage set) internal view returns (uint256[] memory) { | |
bytes32[] memory store = _values(set._inner); | |
uint256[] memory result; | |
/// @solidity memory-safe-assembly | |
assembly { | |
result := store | |
} | |
return result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// ERC721A Contracts v4.2.2 | |
// Creator: Chiru Labs | |
pragma solidity ^0.8.4; | |
import './IERC721A.sol'; | |
/** | |
* @dev Interface of ERC721 token receiver. | |
*/ | |
interface ERC721A__IERC721Receiver { | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (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). | |
*/ | |
contract ERC721A is IERC721A { | |
// Reference type for token approval. | |
struct TokenApprovalRef { | |
address value; | |
} | |
// ============================================================= | |
// CONSTANTS | |
// ============================================================= | |
// Mask of an entry in packed address data. | |
uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; | |
// The bit position of `numberMinted` in packed address data. | |
uint256 private constant _BITPOS_NUMBER_MINTED = 64; | |
// The bit position of `numberBurned` in packed address data. | |
uint256 private constant _BITPOS_NUMBER_BURNED = 128; | |
// The bit position of `aux` in packed address data. | |
uint256 private constant _BITPOS_AUX = 192; | |
// Mask of all 256 bits in packed address data except the 64 bits for `aux`. | |
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; | |
// The bit position of `startTimestamp` in packed ownership. | |
uint256 private constant _BITPOS_START_TIMESTAMP = 160; | |
// The bit mask of the `burned` bit in packed ownership. | |
uint256 private constant _BITMASK_BURNED = 1 << 224; | |
// The bit position of the `nextInitialized` bit in packed ownership. | |
uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; | |
// The bit mask of the `nextInitialized` bit in packed ownership. | |
uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; | |
// The bit position of `extraData` in packed ownership. | |
uint256 private constant _BITPOS_EXTRA_DATA = 232; | |
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. | |
uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; | |
// The mask of the lower 160 bits for addresses. | |
uint256 private constant _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. | |
uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; | |
// The `Transfer` event signature is given by: | |
// `keccak256(bytes("Transfer(address,address,uint256)"))`. | |
bytes32 private constant _TRANSFER_EVENT_SIGNATURE = | |
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; | |
// ============================================================= | |
// STORAGE | |
// ============================================================= | |
// The next token ID to be minted. | |
uint256 private _currentIndex; | |
// The number of tokens burned. | |
uint256 private _burnCounter; | |
// Token name | |
string private _name; | |
// Token symbol | |
string private _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 approvals | |
mapping(address => mapping(address => bool)) private _operatorApprovals; | |
// ============================================================= | |
// CONSTRUCTOR | |
// ============================================================= | |
constructor(string memory name_, string memory 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() internal view virtual returns (uint256) { | |
return 0; | |
} | |
/** | |
* @dev Returns the next token ID to be minted. | |
*/ | |
function _nextTokenId() internal view virtual returns (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}. | |
*/ | |
function totalSupply() public view virtual override returns (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() internal view virtual returns (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() internal view virtual returns (uint256) { | |
return _burnCounter; | |
} | |
// ============================================================= | |
// ADDRESS DATA OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Returns the number of tokens in `owner`'s account. | |
*/ | |
function balanceOf(address owner) public view virtual override returns (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) internal view returns (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) internal view returns (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) internal view returns (uint64) { | |
return uint64(_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) internal virtual { | |
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. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (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. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the token collection symbol. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. | |
*/ | |
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { | |
if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); | |
string memory baseURI = _baseURI(); | |
return bytes(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() internal view virtual returns (string memory) { | |
return ''; | |
} | |
// ============================================================= | |
// OWNERSHIPS OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) public view virtual override returns (address) { | |
return address(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) internal view virtual returns (TokenOwnership memory) { | |
return _unpackedOwnership(_packedOwnershipOf(tokenId)); | |
} | |
/** | |
* @dev Returns the unpacked `TokenOwnership` struct at `index`. | |
*/ | |
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { | |
return _unpackedOwnership(_packedOwnerships[index]); | |
} | |
/** | |
* @dev Initializes the ownership slot minted at `index` for efficiency purposes. | |
*/ | |
function _initializeOwnershipAt(uint256 index) internal virtual { | |
if (_packedOwnerships[index] == 0) { | |
_packedOwnerships[index] = _packedOwnershipOf(index); | |
} | |
} | |
/** | |
* Returns the packed ownership data of `tokenId`. | |
*/ | |
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { | |
uint256 curr = tokenId; | |
unchecked { | |
if (_startTokenId() <= curr) | |
if (curr < _currentIndex) { | |
uint256 packed = _packedOwnerships[curr]; | |
// If not burned. | |
if (packed & _BITMASK_BURNED == 0) { | |
// 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, `curr` will not underflow. | |
// | |
// We can directly compare the packed value. | |
// If the address is zero, packed will be zero. | |
while (packed == 0) { | |
packed = _packedOwnerships[--curr]; | |
} | |
return packed; | |
} | |
} | |
} | |
revert OwnerQueryForNonexistentToken(); | |
} | |
/** | |
* @dev Returns the unpacked `TokenOwnership` struct from `packed`. | |
*/ | |
function _unpackedOwnership(uint256 packed) private pure returns (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) private view returns (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) private pure returns (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. | |
* 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) public virtual override { | |
address owner = ownerOf(tokenId); | |
if (_msgSenderERC721A() != owner) | |
if (!isApprovedForAll(owner, _msgSenderERC721A())) { | |
revert ApprovalCallerNotOwnerNorApproved(); | |
} | |
_tokenApprovals[tokenId].value = to; | |
emit Approval(owner, to, tokenId); | |
} | |
/** | |
* @dev Returns the account approved for `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function getApproved(uint256 tokenId) public view virtual override returns (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. | |
*/ | |
function setApprovalForAll(address operator, bool approved) public virtual override { | |
if (operator == _msgSenderERC721A()) revert ApproveToCaller(); | |
_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}. | |
*/ | |
function isApprovedForAll(address owner, address operator) public view virtual override returns (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) internal view virtual returns (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 | |
) private pure returns (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) | |
private | |
view | |
returns (uint256 approvedAddressSlot, address approvedAddress) | |
{ | |
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; | |
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`. | |
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. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public virtual override { | |
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, '')`. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public virtual override { | |
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. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) public virtual override { | |
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( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
/** | |
* @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( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
/** | |
* @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( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) private returns (bool) { | |
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns ( | |
bytes4 retval | |
) { | |
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; | |
} catch (bytes memory 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) internal virtual { | |
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. | |
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`. | |
) | |
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) internal virtual { | |
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, | |
bytes memory _data | |
) internal virtual { | |
_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) internal virtual { | |
_safeMint(to, quantity, ''); | |
} | |
// ============================================================= | |
// BURN OPERATIONS | |
// ============================================================= | |
/** | |
* @dev Equivalent to `_burn(tokenId, false)`. | |
*/ | |
function _burn(uint256 tokenId) internal virtual { | |
_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) internal virtual { | |
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); | |
address from = 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) internal virtual { | |
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( | |
address from, | |
address to, | |
uint24 previousExtraData | |
) internal view virtual returns (uint24) {} | |
/** | |
* @dev Returns the next extra data for the packed ownership data. | |
* The returned result is shifted into position. | |
*/ | |
function _nextExtraData( | |
address from, | |
address to, | |
uint256 prevOwnershipPacked | |
) private view returns (uint256) { | |
uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); | |
return uint256(_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() internal view virtual returns (address) { | |
return msg.sender; | |
} | |
/** | |
* @dev Converts a uint256 to its ASCII string decimal representation. | |
*/ | |
function _toString(uint256 value) internal pure virtual returns (string memory str) { | |
assembly { | |
// The maximum value of a uint256 contains 78 digits (1 byte per digit), | |
// but we allocate 0x80 bytes to keep the free memory pointer 32-byte word aliged. | |
// We will need 1 32-byte word to store the length, | |
// and 3 32-byte words to store a maximum of 78 digits. Total: 0x20 + 3 * 0x20 = 0x80. | |
str := add(mload(0x40), 0x80) | |
// Update the free memory pointer to allocate. | |
mstore(0x40, str) | |
// 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-ignore | |
for { 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-ignore | |
if iszero(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) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// ERC721A Contracts v4.2.2 | |
// Creator: Chiru Labs | |
pragma solidity ^0.8.4; | |
/** | |
* @dev Interface of ERC721A. | |
*/ | |
interface IERC721A { | |
/** | |
* The caller must own the token or be an approved operator. | |
*/ | |
error ApprovalCallerNotOwnerNorApproved(); | |
/** | |
* The token does not exist. | |
*/ | |
error ApprovalQueryForNonexistentToken(); | |
/** | |
* The caller cannot approve to their own address. | |
*/ | |
error ApproveToCaller(); | |
/** | |
* Cannot query the balance for the zero address. | |
*/ | |
error BalanceQueryForZeroAddress(); | |
/** | |
* Cannot mint to the zero address. | |
*/ | |
error MintToZeroAddress(); | |
/** | |
* The quantity of tokens minted must be more than zero. | |
*/ | |
error MintZeroQuantity(); | |
/** | |
* The token does not exist. | |
*/ | |
error OwnerQueryForNonexistentToken(); | |
/** | |
* The caller must own the token or be an approved operator. | |
*/ | |
error TransferCallerNotOwnerNorApproved(); | |
/** | |
* The token must be owned by `from`. | |
*/ | |
error TransferFromIncorrectOwner(); | |
/** | |
* Cannot safely transfer to a contract that does not implement the | |
* ERC721Receiver interface. | |
*/ | |
error TransferToNonERC721ReceiverImplementer(); | |
/** | |
* Cannot transfer to the zero address. | |
*/ | |
error TransferToZeroAddress(); | |
/** | |
* The token does not exist. | |
*/ | |
error URIQueryForNonexistentToken(); | |
/** | |
* The `quantity` minted with ERC2309 exceeds the safety limit. | |
*/ | |
error MintERC2309QuantityExceedsLimit(); | |
/** | |
* The `extraData` cannot be set on an unintialized ownership slot. | |
*/ | |
error OwnershipNotInitializedForExtraData(); | |
// ============================================================= | |
// STRUCTS | |
// ============================================================= | |
struct TokenOwnership { | |
// 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}. | |
*/ | |
function totalSupply() external view returns (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. | |
*/ | |
function supportsInterface(bytes4 interfaceId) external view returns (bool); | |
// ============================================================= | |
// IERC721 | |
// ============================================================= | |
/** | |
* @dev Emitted when `tokenId` token is transferred from `from` to `to`. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. | |
*/ | |
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables or disables | |
* (`approved`) `operator` to manage all of its assets. | |
*/ | |
event ApprovalForAll(address indexed owner, address indexed operator, bool approved); | |
/** | |
* @dev Returns the number of tokens in `owner`'s account. | |
*/ | |
function balanceOf(address owner) external view returns (uint256 balance); | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) external view returns (address owner); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, | |
* checking first that contract recipients are aware of the ERC721 protocol | |
* to prevent tokens from being forever locked. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be have been allowed to move | |
* this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement | |
* {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes calldata data | |
) external; | |
/** | |
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external; | |
/** | |
* @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. | |
*/ | |
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); | |
// ============================================================= | |
// IERC721Metadata | |
// ============================================================= | |
/** | |
* @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); | |
// ============================================================= | |
// 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. | |
*/ | |
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity >= 0.4.22 <0.9.0; | |
library console { | |
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); | |
function _sendLogPayload(bytes memory payload) private view { | |
uint256 payloadLength = payload.length; | |
address consoleAddress = CONSOLE_ADDRESS; | |
assembly { | |
let payloadStart := add(payload, 32) | |
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) | |
} | |
} | |
function log() internal view { | |
_sendLogPayload(abi.encodeWithSignature("log()")); | |
} | |
function logInt(int256 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(int256)", p0)); | |
} | |
function logUint(uint256 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); | |
} | |
function logString(string memory p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string)", p0)); | |
} | |
function logBool(bool p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); | |
} | |
function logAddress(address p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address)", p0)); | |
} | |
function logBytes(bytes memory p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); | |
} | |
function logBytes1(bytes1 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); | |
} | |
function logBytes2(bytes2 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); | |
} | |
function logBytes3(bytes3 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); | |
} | |
function logBytes4(bytes4 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); | |
} | |
function logBytes5(bytes5 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); | |
} | |
function logBytes6(bytes6 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); | |
} | |
function logBytes7(bytes7 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); | |
} | |
function logBytes8(bytes8 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); | |
} | |
function logBytes9(bytes9 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); | |
} | |
function logBytes10(bytes10 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); | |
} | |
function logBytes11(bytes11 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); | |
} | |
function logBytes12(bytes12 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); | |
} | |
function logBytes13(bytes13 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); | |
} | |
function logBytes14(bytes14 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); | |
} | |
function logBytes15(bytes15 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); | |
} | |
function logBytes16(bytes16 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); | |
} | |
function logBytes17(bytes17 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); | |
} | |
function logBytes18(bytes18 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); | |
} | |
function logBytes19(bytes19 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); | |
} | |
function logBytes20(bytes20 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); | |
} | |
function logBytes21(bytes21 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); | |
} | |
function logBytes22(bytes22 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); | |
} | |
function logBytes23(bytes23 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); | |
} | |
function logBytes24(bytes24 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); | |
} | |
function logBytes25(bytes25 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); | |
} | |
function logBytes26(bytes26 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); | |
} | |
function logBytes27(bytes27 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); | |
} | |
function logBytes28(bytes28 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); | |
} | |
function logBytes29(bytes29 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); | |
} | |
function logBytes30(bytes30 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); | |
} | |
function logBytes31(bytes31 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); | |
} | |
function logBytes32(bytes32 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); | |
} | |
function log(uint256 p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0)); | |
} | |
function log(string memory p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string)", p0)); | |
} | |
function log(bool p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); | |
} | |
function log(address p0) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address)", p0)); | |
} | |
function log(uint256 p0, uint256 p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1)); | |
} | |
function log(uint256 p0, string memory p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1)); | |
} | |
function log(uint256 p0, bool p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1)); | |
} | |
function log(uint256 p0, address p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1)); | |
} | |
function log(string memory p0, uint256 p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1)); | |
} | |
function log(string memory p0, string memory p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); | |
} | |
function log(string memory p0, bool p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); | |
} | |
function log(string memory p0, address p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); | |
} | |
function log(bool p0, uint256 p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1)); | |
} | |
function log(bool p0, string memory p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); | |
} | |
function log(bool p0, bool p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); | |
} | |
function log(bool p0, address p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); | |
} | |
function log(address p0, uint256 p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1)); | |
} | |
function log(address p0, string memory p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); | |
} | |
function log(address p0, bool p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); | |
} | |
function log(address p0, address p1) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); | |
} | |
function log(uint256 p0, uint256 p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2)); | |
} | |
function log(uint256 p0, uint256 p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2)); | |
} | |
function log(uint256 p0, uint256 p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2)); | |
} | |
function log(uint256 p0, uint256 p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2)); | |
} | |
function log(uint256 p0, string memory p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2)); | |
} | |
function log(uint256 p0, string memory p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2)); | |
} | |
function log(uint256 p0, string memory p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2)); | |
} | |
function log(uint256 p0, string memory p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2)); | |
} | |
function log(uint256 p0, bool p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2)); | |
} | |
function log(uint256 p0, bool p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2)); | |
} | |
function log(uint256 p0, bool p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2)); | |
} | |
function log(uint256 p0, bool p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2)); | |
} | |
function log(uint256 p0, address p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2)); | |
} | |
function log(uint256 p0, address p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2)); | |
} | |
function log(uint256 p0, address p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2)); | |
} | |
function log(uint256 p0, address p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2)); | |
} | |
function log(string memory p0, uint256 p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2)); | |
} | |
function log(string memory p0, uint256 p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2)); | |
} | |
function log(string memory p0, uint256 p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2)); | |
} | |
function log(string memory p0, uint256 p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2)); | |
} | |
function log(string memory p0, string memory p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2)); | |
} | |
function log(string memory p0, string memory p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); | |
} | |
function log(string memory p0, string memory p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); | |
} | |
function log(string memory p0, string memory p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); | |
} | |
function log(string memory p0, bool p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2)); | |
} | |
function log(string memory p0, bool p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); | |
} | |
function log(string memory p0, bool p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); | |
} | |
function log(string memory p0, bool p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); | |
} | |
function log(string memory p0, address p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2)); | |
} | |
function log(string memory p0, address p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); | |
} | |
function log(string memory p0, address p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); | |
} | |
function log(string memory p0, address p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); | |
} | |
function log(bool p0, uint256 p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2)); | |
} | |
function log(bool p0, uint256 p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2)); | |
} | |
function log(bool p0, uint256 p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2)); | |
} | |
function log(bool p0, uint256 p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2)); | |
} | |
function log(bool p0, string memory p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2)); | |
} | |
function log(bool p0, string memory p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); | |
} | |
function log(bool p0, string memory p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); | |
} | |
function log(bool p0, string memory p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); | |
} | |
function log(bool p0, bool p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2)); | |
} | |
function log(bool p0, bool p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); | |
} | |
function log(bool p0, bool p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); | |
} | |
function log(bool p0, bool p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); | |
} | |
function log(bool p0, address p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2)); | |
} | |
function log(bool p0, address p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); | |
} | |
function log(bool p0, address p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); | |
} | |
function log(bool p0, address p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); | |
} | |
function log(address p0, uint256 p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2)); | |
} | |
function log(address p0, uint256 p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2)); | |
} | |
function log(address p0, uint256 p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2)); | |
} | |
function log(address p0, uint256 p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2)); | |
} | |
function log(address p0, string memory p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2)); | |
} | |
function log(address p0, string memory p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); | |
} | |
function log(address p0, string memory p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); | |
} | |
function log(address p0, string memory p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); | |
} | |
function log(address p0, bool p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2)); | |
} | |
function log(address p0, bool p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); | |
} | |
function log(address p0, bool p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); | |
} | |
function log(address p0, bool p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); | |
} | |
function log(address p0, address p1, uint256 p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2)); | |
} | |
function log(address p0, address p1, string memory p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); | |
} | |
function log(address p0, address p1, bool p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); | |
} | |
function log(address p0, address p1, address p2) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); | |
} | |
function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, uint256 p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, string memory p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, bool p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(uint256 p0, address p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, uint256 p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, string memory p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, bool p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(string memory p0, address p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, uint256 p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, string memory p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, bool p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(bool p0, address p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, uint256 p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, string memory p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, bool p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, uint256 p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, uint256 p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, uint256 p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, uint256 p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, string memory p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, string memory p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, string memory p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, string memory p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, bool p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, bool p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, bool p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, bool p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, address p2, uint256 p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, address p2, string memory p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, address p2, bool p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); | |
} | |
function log(address p0, address p1, address p2, address p3) internal view { | |
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.9; | |
import "https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol"; | |
import "@openzeppelin/contracts/utils/Strings.sol"; | |
import "@openzeppelin/contracts/utils/Base64.sol"; | |
contract SampleERC721A is ERC721A { | |
constructor() ERC721A("Sample ERC721A", "ERC721A") {} | |
function mint(uint256 quantity) external { | |
_mint(msg.sender, quantity); | |
} | |
function tokenURI(uint256 tokenId) | |
public | |
view | |
virtual | |
override | |
returns (string memory) | |
{ | |
if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); | |
// Get all the JSON metadata in place and base64 encode it. | |
string memory json = Base64.encode( | |
bytes( | |
string( | |
abi.encodePacked( | |
'{"name": "', | |
string( | |
abi.encodePacked( | |
"Sample ERC721A #", | |
Strings.toString(tokenId) | |
) | |
), | |
'", "description": "Placeholder NFT is an unlimited supply, fully on-chain, NFT collection available on any EVM-compatible chain. You may mint it freely, and use it for testing, or your own satisfaction.", "image": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzExIDExIDUwIDUwJz48Zz48cmVjdCB4PScxMicgeT0nMTInIHdpZHRoPSc0OCcgaGVpZ2h0PSc0OCcgZmlsbD0nI0E1NzkzOScgc3Ryb2tlPSdub25lJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJz48L3JlY3Q+PHJlY3QgeD0nMTgnIHk9JzE4JyB3aWR0aD0nMzYnIGhlaWdodD0nMzYnIGZpbGw9JyM5MkQzRjUnIHN0cm9rZT0nbm9uZScgc3Ryb2tlLWxpbmVjYXA9J3JvdW5kJyBzdHJva2UtbGluZWpvaW49J3JvdW5kJyBzdHJva2UtbWl0ZXJsaW1pdD0nMTAnIHN0cm9rZS13aWR0aD0nMic+PC9yZWN0PjxjaXJjbGUgY3g9JzI2JyBjeT0nMzAnIHI9JzQnIGZpbGw9JyNGQ0VBMkInIHN0cm9rZT0nbm9uZScgc3Ryb2tlLWxpbmVjYXA9J3JvdW5kJyBzdHJva2UtbGluZWpvaW49J3JvdW5kJyBzdHJva2UtbWl0ZXJsaW1pdD0nMTAnIHN0cm9rZS13aWR0aD0nMic+PC9jaXJjbGU+PHBhdGggZmlsbD0nIzVDOUUzMScgc3Ryb2tlPScjNUM5RTMxJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJyBkPSdNNTAsMzVjLTIuODk1OC0wLjg1NDItNi4yNzk1LTcuOTg4Ni04LThjLTQuMjA4LTAuMDI3OC02LjI1NCw1LjgzNi0xMSw5Yy0zLDItMy4zNzQ1LDIuODQ5Ny02LDRjLTIuMjgyNCwxLTMsMy0zLjI1LDMuNjQwNiBjLTAuMzAzMSwwLjc3NjYtMS40NzUxLDIuNTIxNC0wLjk1ODMsMy4xMDk0YzEuMjA4MywxLjM3NSwyLjQ1ODMsMS41LDUsMC43MTc5YzIuMTQ3LTAuNjYwNiw0Ljk3NjktNC44MDc0LDYuODc1LTYuMjE3OSBjMi4yNzA4LTEuNjg3NSw0LjY0NTgtMi41LDguMDgzMy0yYzIuNDc5NSwwLjM2MDYsNi42NiwzLjE3MjMsNy44MTI1LDMuMDYyNWMxLjMxMjUtMC4xMjUtMS41OTM3LTIuNTYyNS0wLjUzMTItNC4xODc1IGMxLjEzMjctMS43MzI1LDIuOTEwMiwwLjE1MjksMy42MzU0LTEuMDgzM0M1MS45ODQ0LDM2LjUsNTAuNjMyLDM1LjE4NjQsNTAsMzV6Jz48L3BhdGg+PC9nPjxnPjxyZWN0IHg9JzEyJyB5PScxMicgd2lkdGg9JzQ4JyBoZWlnaHQ9JzQ4JyBmaWxsPSdub25lJyBzdHJva2U9JyMwMDAwMDAnIHN0cm9rZS1saW5lY2FwPSdyb3VuZCcgc3Ryb2tlLWxpbmVqb2luPSdyb3VuZCcgc3Ryb2tlLW1pdGVybGltaXQ9JzEwJyBzdHJva2Utd2lkdGg9JzInPjwvcmVjdD48cmVjdCB4PScxOCcgeT0nMTgnIHdpZHRoPSczNicgaGVpZ2h0PSczNicgZmlsbD0nbm9uZScgc3Ryb2tlPScjMDAwMDAwJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJz48L3JlY3Q+PGNpcmNsZSBjeD0nMjYnIGN5PSczMCcgcj0nNCcgZmlsbD0nbm9uZScgc3Ryb2tlPScjMDAwMDAwJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJz48L2NpcmNsZT48cmVjdCB4PScxOCcgeT0nMTgnIHdpZHRoPSczNicgaGVpZ2h0PSczNicgZmlsbD0nbm9uZScgc3Ryb2tlPScjMDAwMDAwJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJz48L3JlY3Q+PHBhdGggZmlsbD0nbm9uZScgc3Ryb2tlPScjMDAwMDAwJyBzdHJva2UtbGluZWNhcD0ncm91bmQnIHN0cm9rZS1saW5lam9pbj0ncm91bmQnIHN0cm9rZS1taXRlcmxpbWl0PScxMCcgc3Ryb2tlLXdpZHRoPScyJyBkPSdNMjIsNDNjMC41MjU5LTEuMDE5OCwwLjcyNzUtMS45NjcyLDMtM2MyLjYwOTYtMS4xODU5LDMtMiw2LTRjNC43NDYtMy4xNjQsNi43OTItOS4wMjc4LDExLTljMS43MjA1LDAuMDExNCw1LDcsOCw4Jz48L3BhdGg+PC9nPjwvc3ZnPg=="}' | |
) | |
) | |
) | |
); | |
// Prepend data:application/json;base64, to our data. | |
string memory finalTokenUri = string( | |
abi.encodePacked("data:application/json;base64,", json) | |
); | |
return finalTokenUri; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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/utils/cryptography/ECDSA.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
/** | |
@title SignatureChecker | |
@notice Additional functions for EnumerableSet.Addresset that require a valid | |
ECDSA signature of a standardized message, signed by any member of the set. | |
*/ | |
library SignatureChecker { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation + signature verification | |
+ marking message as used | |
@param signers Set of addresses from which signatures are accepted. | |
@param usedMessages Set of already-used messages. | |
@param signature ECDSA signature of message. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes memory data, | |
bytes calldata signature, | |
mapping(bytes32 => bool) storage usedMessages | |
) internal { | |
bytes32 message = generateMessage(data); | |
require( | |
!usedMessages[message], | |
"SignatureChecker: Message already used" | |
); | |
usedMessages[message] = true; | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation + signature verification. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes memory data, | |
bytes calldata signature | |
) internal view { | |
bytes32 message = generateMessage(data); | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Requires that the message has not been used previously and that the | |
recovered signer is contained in the signers AddressSet. | |
@dev Convenience wrapper for message generation from address + | |
signature verification. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
address a, | |
bytes calldata signature | |
) internal view { | |
bytes32 message = generateMessage(abi.encodePacked(a)); | |
requireValidSignature(signers, message, signature); | |
} | |
/** | |
@notice Common validator logic, checking if the recovered signer is | |
contained in the signers AddressSet. | |
*/ | |
function validSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes32 message, | |
bytes calldata signature | |
) internal view returns (bool) { | |
return signers.contains(ECDSA.recover(message, signature)); | |
} | |
/** | |
@notice Requires that the recovered signer is contained in the signers | |
AddressSet. | |
@dev Convenience wrapper that reverts if the signature validation fails. | |
*/ | |
function requireValidSignature( | |
EnumerableSet.AddressSet storage signers, | |
bytes32 message, | |
bytes calldata signature | |
) internal view { | |
require( | |
validSignature(signers, message, signature), | |
"SignatureChecker: Invalid signature" | |
); | |
} | |
/** | |
@notice Generates a message for a given data input that will be signed | |
off-chain using ECDSA. | |
@dev For multiple data fields, a standard concatenation using | |
`abi.encodePacked` is commonly used to build data. | |
*/ | |
function generateMessage(bytes memory data) | |
internal | |
pure | |
returns (bytes32) | |
{ | |
return ECDSA.toEthSignedMessageHash(data); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "@openzeppelin/contracts/access/Ownable.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
/** | |
@title SignerManager | |
@notice Manges addition and removal of a core set of addresses from which | |
valid ECDSA signatures can be accepted; see SignatureChecker. | |
*/ | |
contract SignerManager is Ownable { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
/** | |
@dev Addresses from which signatures can be accepted. | |
*/ | |
EnumerableSet.AddressSet internal signers; | |
/** | |
@notice Add an address to the set of accepted signers. | |
*/ | |
function addSigner(address signer) external onlyOwner { | |
signers.add(signer); | |
} | |
/** | |
@notice Remove an address previously added with addSigner(). | |
*/ | |
function removeSigner(address signer) external onlyOwner { | |
signers.remove(signer); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"; | |
/** | |
@notice ERC721 extension that overrides the OpenZeppelin _baseURI() function to | |
return a prefix that can be set by the contract owner. | |
*/ | |
contract BaseTokenURI is Ownable { | |
/// @notice Base token URI used as a prefix by tokenURI(). | |
string public baseTokenURI; | |
constructor(string memory _baseTokenURI) { | |
setBaseTokenURI(_baseTokenURI); | |
} | |
/// @notice Sets the base token URI prefix. | |
function setBaseTokenURI(string memory _baseTokenURI) public onlyOwner { | |
baseTokenURI = _baseTokenURI; | |
} | |
/** | |
@notice Concatenates and returns the base token URI and the token ID without | |
any additional characters (e.g. a slash). | |
@dev This requires that an inheriting contract that also inherits from OZ's | |
ERC721 will have to override both contracts; although we could simply | |
require that users implement their own _baseURI() as here, this can easily | |
be forgotten and the current approach guides them with compiler errors. This | |
favours the latter half of "APIs should be easy to use and hard to misuse" | |
from https://www.infoq.com/articles/API-Design-Joshua-Bloch/. | |
*/ | |
function _baseURI() internal view virtual returns (string memory) { | |
return baseTokenURI; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "./ERC721APreApproval.sol"; | |
import "../utils/OwnerPausable.sol"; | |
/** | |
@notice An ERC721A contract with common functionality: | |
- OpenSea gas-free listings | |
- Pausable with toggling functions exposed to Owner only | |
*/ | |
contract ERC721ACommon is ERC721APreApproval, OwnerPausable { | |
constructor(string memory name, string memory symbol) | |
ERC721A(name, symbol) | |
{} // solhint-disable-line no-empty-blocks | |
/// @notice Requires that the token exists. | |
modifier tokenExists(uint256 tokenId) { | |
require(ERC721A._exists(tokenId), "ERC721ACommon: Token doesn't exist"); | |
_; | |
} | |
/// @notice Requires that msg.sender owns or is approved for the token. | |
modifier onlyApprovedOrOwner(uint256 tokenId) { | |
require( | |
_ownershipOf(tokenId).addr == _msgSender() || | |
getApproved(tokenId) == _msgSender(), | |
"ERC721ACommon: Not approved nor owner" | |
); | |
_; | |
} | |
function _beforeTokenTransfers( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual override { | |
require(!paused(), "ERC721ACommon: paused"); | |
super._beforeTokenTransfers(from, to, startTokenId, quantity); | |
} | |
/// @notice Overrides supportsInterface as required by inheritance. | |
function supportsInterface(bytes4 interfaceId) | |
public | |
view | |
virtual | |
override(ERC721A) | |
returns (bool) | |
{ | |
return super.supportsInterface(interfaceId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "../thirdparty/opensea/OpenSeaGasFreeListing.sol"; | |
import "erc721a/contracts/ERC721A.sol"; | |
/// @notice Pre-approval of OpenSea proxies for gas-less listing | |
/// @dev This wrapper allows users to revoke the pre-approval of their | |
/// associated proxy and emits the corresponding events. This is necessary for | |
/// external tools to index approvals correctly and inform the user. | |
/// @dev The pre-approval is triggered on a per-wallet basis during the first | |
/// transfer transactions. It will only be enabled for wallets with an existing | |
/// proxy. Not having a proxy incurs a gas overhead. | |
/// @dev This wrapper optimizes for the following scenario: | |
/// - The majority of users already have a wyvern proxy | |
/// - Most of them want to transfer tokens via wyvern exchanges | |
abstract contract ERC721APreApproval is ERC721A { | |
/// @dev It is important that Active remains at first position, since this | |
/// is the scenario that we are trying to optimize for. | |
enum State { | |
Active, | |
Inactive | |
} | |
/// @notice The state of the pre-approval for a given owner | |
mapping(address => State) private state; | |
/// @dev Returns true if either standard `isApprovedForAll()` or if the | |
/// `operator` is the OpenSea proxy for the `owner` provided the | |
/// pre-approval is active. | |
function isApprovedForAll(address owner, address operator) | |
public | |
view | |
virtual | |
override | |
returns (bool) | |
{ | |
if (super.isApprovedForAll(owner, operator)) { | |
return true; | |
} | |
return | |
state[owner] == State.Active && | |
OpenSeaGasFreeListing.isApprovedForAll(owner, operator); | |
} | |
/// @dev Uses the standard `setApprovalForAll` or toggles the pre-approval | |
/// state if `operator` is the OpenSea proxy for the sender. | |
function setApprovalForAll(address operator, bool approved) | |
public | |
virtual | |
override | |
{ | |
address owner = _msgSender(); | |
if (operator == OpenSeaGasFreeListing.proxyFor(owner)) { | |
state[owner] = approved ? State.Active : State.Inactive; | |
emit ApprovalForAll(owner, operator, approved); | |
} else { | |
super.setApprovalForAll(operator, approved); | |
} | |
} | |
/// @dev Checks if the receiver has an existing proxy. If not, the | |
/// pre-approval is disabled. | |
function _beforeTokenTransfers( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual override { | |
super._beforeTokenTransfers(from, to, startTokenId, quantity); | |
// Exclude burns and inactive pre-approvals | |
if (to == address(0) || state[to] == State.Inactive) { | |
return; | |
} | |
address operator = OpenSeaGasFreeListing.proxyFor(to); | |
// Disable if `to` has no proxy | |
if (operator == address(0)) { | |
state[to] = State.Inactive; | |
return; | |
} | |
// Avoid emitting unnecessary events. | |
if (balanceOf(to) == 0) { | |
emit ApprovalForAll(to, operator, true); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2022 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "@openzeppelin/contracts/interfaces/IERC721.sol"; | |
import "@openzeppelin/contracts/utils/Strings.sol"; | |
import "@openzeppelin/contracts/utils/structs/BitMaps.sol"; | |
/** | |
@notice Allows holders of ERC721 tokens to redeem rights to some claim; for | |
example, the right to mint a token of some other collection. | |
*/ | |
library ERC721Redeemer { | |
using BitMaps for BitMaps.BitMap; | |
using Strings for uint256; | |
/** | |
@notice Storage value to track already-claimed redemptions for a specific | |
token collection. | |
*/ | |
struct Claims { | |
/** | |
@dev This field MUST NOT be considered part of the public API. Instead, | |
prefer `using ERC721Redeemer for ERC721Redeemer.Claims` and utilise the | |
provided functions. | |
*/ | |
mapping(uint256 => uint256) _total; | |
} | |
/** | |
@notice Storage value to track already-claimed redemptions for a specific | |
token collection, given that there is only a single claim allowed per | |
tokenId. | |
*/ | |
struct SingleClaims { | |
/** | |
@dev This field MUST NOT be considered part of the public API. Instead, | |
prefer `using ERC721Redeemer for ERC721Redeemer.SingleClaims` and | |
utilise the provided functions. | |
*/ | |
BitMaps.BitMap _claimed; | |
} | |
/** | |
@notice Emitted when a token's claim is redeemed. | |
*/ | |
event Redemption( | |
IERC721 indexed token, | |
address indexed redeemer, | |
uint256 tokenId, | |
uint256 n | |
); | |
/** | |
@notice Checks that the redeemer is allowed to redeem the claims for the | |
tokenIds by being either the owner or approved address for all tokenIds, and | |
updates the Claims to reflect this. | |
@dev For more efficient gas usage, recurring values in tokenIds SHOULD be | |
adjacent to one another as this will batch expensive operations. The | |
simplest way to achieve this is by sorting tokenIds. | |
@param tokenIds The token IDs for which the claims are being redeemed. If | |
maxAllowance > 1 then identical tokenIds can be passed more than once; see | |
dev comments. | |
@return The number of redeemed claims; either 0 or tokenIds.length; | |
*/ | |
function redeem( | |
Claims storage claims, | |
uint256 maxAllowance, | |
address redeemer, | |
IERC721 token, | |
uint256[] calldata tokenIds | |
) internal returns (uint256) { | |
if (maxAllowance == 0 || tokenIds.length == 0) { | |
return 0; | |
} | |
// See comment for `endSameId`. | |
bool multi = maxAllowance > 1; | |
for ( | |
uint256 i = 0; | |
i < tokenIds.length; /* note increment at end */ | |
) { | |
uint256 tokenId = tokenIds[i]; | |
requireOwnerOrApproved(token, tokenId, redeemer); | |
uint256 n = 1; | |
if (multi) { | |
// If allowed > 1 we can save on expensive operations like | |
// checking ownership / remaining allowance by batching equal | |
// tokenIds. The algorithm assumes that equal IDs are adjacent | |
// in the array. | |
uint256 endSameId; | |
for ( | |
endSameId = i + 1; | |
endSameId < tokenIds.length && | |
tokenIds[endSameId] == tokenId; | |
endSameId++ | |
) {} // solhint-disable-line no-empty-blocks | |
n = endSameId - i; | |
} | |
claims._total[tokenId] += n; | |
if (claims._total[tokenId] > maxAllowance) { | |
revertWithTokenId( | |
"ERC721Redeemer: over allowance for", | |
tokenId | |
); | |
} | |
i += n; | |
emit Redemption(token, redeemer, tokenId, n); | |
} | |
return tokenIds.length; | |
} | |
/** | |
@notice Checks that the redeemer is allowed to redeem the single claim for | |
each of the tokenIds by being either the owner or approved address for all | |
tokenIds, and updates the SingleClaims to reflect this. | |
@param tokenIds The token IDs for which the claims are being redeemed. Only | |
a single claim can be made against a tokenId. | |
@return The number of redeemed claims; either 0 or tokenIds.length; | |
*/ | |
function redeem( | |
SingleClaims storage claims, | |
address redeemer, | |
IERC721 token, | |
uint256[] calldata tokenIds | |
) internal returns (uint256) { | |
if (tokenIds.length == 0) { | |
return 0; | |
} | |
for (uint256 i = 0; i < tokenIds.length; i++) { | |
uint256 tokenId = tokenIds[i]; | |
requireOwnerOrApproved(token, tokenId, redeemer); | |
if (claims._claimed.get(tokenId)) { | |
revertWithTokenId( | |
"ERC721Redeemer: over allowance for", | |
tokenId | |
); | |
} | |
claims._claimed.set(tokenId); | |
emit Redemption(token, redeemer, tokenId, 1); | |
} | |
return tokenIds.length; | |
} | |
/** | |
@dev Reverts if neither the owner nor approved for the tokenId. | |
*/ | |
function requireOwnerOrApproved( | |
IERC721 token, | |
uint256 tokenId, | |
address redeemer | |
) private view { | |
if ( | |
token.ownerOf(tokenId) != redeemer && | |
token.getApproved(tokenId) != redeemer | |
) { | |
revertWithTokenId( | |
"ERC721Redeemer: not approved nor owner of", | |
tokenId | |
); | |
} | |
} | |
/** | |
@notice Reverts with the concatenation of revertMsg and tokenId.toString(). | |
@dev Used to save gas by constructing the revert message only as required, | |
instead of passing it to require(). | |
*/ | |
function revertWithTokenId(string memory revertMsg, uint256 tokenId) | |
private | |
pure | |
{ | |
revert(string(abi.encodePacked(revertMsg, " ", tokenId.toString()))); | |
} | |
/** | |
@notice Returns the number of claimed redemptions for the token. | |
*/ | |
function claimed(Claims storage claims, uint256 tokenId) | |
internal | |
view | |
returns (uint256) | |
{ | |
return claims._total[tokenId]; | |
} | |
/** | |
@notice Returns whether the token has had a claim made against it. | |
*/ | |
function claimed(SingleClaims storage claims, uint256 tokenId) | |
internal | |
view | |
returns (bool) | |
{ | |
return claims._claimed.get(tokenId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
import "./Seller.sol"; | |
/// @notice A Seller with fixed per-item price. | |
abstract contract FixedPriceSeller is Seller { | |
constructor( | |
uint256 _price, | |
Seller.SellerConfig memory sellerConfig, | |
address payable _beneficiary | |
) Seller(sellerConfig, _beneficiary) { | |
setPrice(_price); | |
} | |
/** | |
@notice The fixed per-item price. | |
@dev Fixed as in not changing with time nor number of items, but not a | |
constant. | |
*/ | |
uint256 public price; | |
/// @notice Sets the per-item price. | |
function setPrice(uint256 _price) public onlyOwner { | |
price = _price; | |
} | |
/** | |
@notice Override of Seller.cost() with fixed price. | |
@dev The second parameter, metadata propagated from the call to _purchase(), | |
is ignored. | |
*/ | |
function cost(uint256 n, uint256) public view override returns (uint256) { | |
return n * price; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
/** | |
@dev Note that the address limits are vulnerable to wallet farming. | |
@param maxPerAddress Unlimited if zero. | |
@param maxPerTex Unlimited if zero. | |
@param freeQuota Maximum number that can be purchased free of charge by | |
the contract owner. | |
@param reserveFreeQuota Whether to excplitly reserve the freeQuota amount | |
and not let it be eroded by regular purchases. | |
@param lockFreeQuota If true, calls to setSellerConfig() will ignore changes | |
to freeQuota. Can be locked after initial setting, but not unlocked. This | |
allows a contract owner to commit to a maximum number of reserved items. | |
@param lockTotalInventory Similar to lockFreeQuota but applied to | |
totalInventory. | |
*/ | |
struct SellerConfig { | |
uint256 totalInventory; | |
uint256 maxPerAddress; | |
uint256 maxPerTx; | |
uint248 freeQuota; | |
bool reserveFreeQuota; | |
bool lockFreeQuota; | |
bool lockTotalInventory; | |
} | |
constructor(SellerConfig memory config, address payable _beneficiary) { | |
setSellerConfig(config); | |
setBeneficiary(_beneficiary); | |
} | |
/// @notice Configuration of purchase limits. | |
SellerConfig public sellerConfig; | |
/// @notice Sets the seller config. | |
function setSellerConfig(SellerConfig memory config) public onlyOwner { | |
require( | |
config.totalInventory >= config.freeQuota, | |
"Seller: excessive free quota" | |
); | |
require( | |
config.totalInventory >= _totalSold.current(), | |
"Seller: inventory < already sold" | |
); | |
require( | |
config.freeQuota >= purchasedFreeOfCharge.current(), | |
"Seller: free quota < already used" | |
); | |
// Overriding the in-memory fields before copying the whole struct, as | |
// against writing individual fields, gives a greater guarantee of | |
// correctness as the code is simpler to read. | |
if (sellerConfig.lockTotalInventory) { | |
config.lockTotalInventory = true; | |
config.totalInventory = sellerConfig.totalInventory; | |
} | |
if (sellerConfig.lockFreeQuota) { | |
config.lockFreeQuota = true; | |
config.freeQuota = sellerConfig.freeQuota; | |
} | |
sellerConfig = config; | |
} | |
/// @notice Recipient of revenues. | |
address payable public beneficiary; | |
/// @notice Sets the recipient of revenues. | |
function setBeneficiary(address payable _beneficiary) public onlyOwner { | |
beneficiary = _beneficiary; | |
} | |
/** | |
@dev Must return the current cost of a batch of items. This may be constant | |
or, for example, decreasing for a Dutch auction or increasing for a bonding | |
curve. | |
@param n The number of items being purchased. | |
@param metadata Arbitrary data, propagated by the call to _purchase() that | |
can be used to charge different prices. This value is a uint256 instead of | |
bytes as this allows simple passing of a set cost (see | |
ArbitraryPriceSeller). | |
*/ | |
function cost(uint256 n, uint256 metadata) | |
public | |
view | |
virtual | |
returns (uint256); | |
/** | |
@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() public view returns (uint256) { | |
return _totalSold.current(); | |
} | |
/** | |
@notice Tracks the number of items already bought by an address, regardless | |
of transferring out (in the case of ERC721). | |
@dev This isn't public as it may be skewed due to differences in msg.sender | |
and tx.origin, which it treats in the same way such that | |
sum(_bought)>=totalSold(). | |
*/ | |
mapping(address => uint256) private _bought; | |
/** | |
@notice Returns min(n, max(extra items addr can purchase)) and reverts if 0. | |
@param zeroMsg The message with which to revert on 0 extra. | |
*/ | |
function _capExtra( | |
uint256 n, | |
address addr, | |
string memory zeroMsg | |
) internal view returns (uint256) { | |
uint256 extra = sellerConfig.maxPerAddress - _bought[addr]; | |
if (extra == 0) { | |
revert(string(abi.encodePacked("Seller: ", zeroMsg))); | |
} | |
return Math.min(n, extra); | |
} | |
/// @notice Emitted when a buyer is refunded. | |
event Refund(address indexed buyer, uint256 amount); | |
/// @notice Emitted on all purchases of non-zero amount. | |
event Revenue( | |
address indexed beneficiary, | |
uint256 numPurchased, | |
uint256 amount | |
); | |
/// @notice Tracks number of items purchased free of charge. | |
Monotonic.Increaser private purchasedFreeOfCharge; | |
/** | |
@notice Allows the contract owner to purchase without payment, within the | |
quota enforced by the SellerConfig. | |
*/ | |
function purchaseFreeOfCharge(address to, uint256 n) | |
public | |
onlyOwner | |
whenNotPaused | |
{ | |
uint256 freeQuota = sellerConfig.freeQuota; | |
n = Math.min(n, freeQuota - purchasedFreeOfCharge.current()); | |
require(n > 0, "Seller: Free quota exceeded"); | |
uint256 totalInventory = sellerConfig.totalInventory; | |
n = Math.min(n, totalInventory - _totalSold.current()); | |
require(n > 0, "Seller: Sold out"); | |
_handlePurchase(to, n, true); | |
_totalSold.add(n); | |
purchasedFreeOfCharge.add(n); | |
assert(_totalSold.current() <= totalInventory); | |
assert(purchasedFreeOfCharge.current() <= freeQuota); | |
} | |
/** | |
@notice Convenience function for calling _purchase() with empty costMetadata | |
when unneeded. | |
*/ | |
function _purchase(address to, uint256 requested) internal virtual { | |
_purchase(to, requested, 0); | |
} | |
/** | |
@notice Enforces all purchase limits (counts and costs) before calling | |
_handlePurchase(), after which the received funds are disbursed to the | |
beneficiary, less any required refunds. | |
@param to The final recipient of the item(s). | |
@param requested The number of items requested for purchase, which MAY be | |
reduced when passed to _handlePurchase(). | |
@param costMetadata Arbitrary data, propagated in the call to cost(), to be | |
optionally used in determining the price. | |
*/ | |
function _purchase( | |
address to, | |
uint256 requested, | |
uint256 costMetadata | |
) internal nonReentrant whenNotPaused { | |
/** | |
* ##### CHECKS | |
*/ | |
SellerConfig memory config = sellerConfig; | |
uint256 n = config.maxPerTx == 0 | |
? requested | |
: Math.min(requested, config.maxPerTx); | |
uint256 maxAvailable; | |
uint256 sold; | |
if (config.reserveFreeQuota) { | |
maxAvailable = config.totalInventory - config.freeQuota; | |
sold = _totalSold.current() - purchasedFreeOfCharge.current(); | |
} else { | |
maxAvailable = config.totalInventory; | |
sold = _totalSold.current(); | |
} | |
n = Math.min(n, maxAvailable - sold); | |
require(n > 0, "Seller: Sold out"); | |
if (config.maxPerAddress > 0) { | |
bool alsoLimitSender = _msgSender() != to; | |
// solhint-disable-next-line avoid-tx-origin | |
bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to; | |
n = _capExtra(n, to, "Buyer limit"); | |
if (alsoLimitSender) { | |
n = _capExtra(n, _msgSender(), "Sender limit"); | |
} | |
if (alsoLimitOrigin) { | |
// solhint-disable-next-line avoid-tx-origin | |
n = _capExtra(n, tx.origin, "Origin limit"); | |
} | |
_bought[to] += n; | |
if (alsoLimitSender) { | |
_bought[_msgSender()] += n; | |
} | |
if (alsoLimitOrigin) { | |
// solhint-disable-next-line avoid-tx-origin | |
_bought[tx.origin] += n; | |
} | |
} | |
uint256 _cost = cost(n, costMetadata); | |
if (msg.value < _cost) { | |
revert( | |
string( | |
abi.encodePacked( | |
"Seller: Costs ", | |
(_cost / 1e9).toString(), | |
" GWei" | |
) | |
) | |
); | |
} | |
/** | |
* ##### EFFECTS | |
*/ | |
_handlePurchase(to, n, false); | |
_totalSold.add(n); | |
assert(_totalSold.current() <= config.totalInventory); | |
/** | |
* ##### INTERACTIONS | |
*/ | |
// Ideally we'd be using a PullPayment here, but the user experience is | |
// poor when there's a variable cost or the number of items purchased | |
// has been capped. We've addressed reentrancy with both a nonReentrant | |
// modifier and the checks, effects, interactions pattern. | |
if (_cost > 0) { | |
beneficiary.sendValue(_cost); | |
emit Revenue(beneficiary, n, _cost); | |
} | |
if (msg.value > _cost) { | |
address payable reimburse = payable(_msgSender()); | |
uint256 refund = msg.value - _cost; | |
// Using Address.sendValue() here would mask the revertMsg upon | |
// reentrancy, but we want to expose it to allow for more precise | |
// testing. This otherwise uses the exact same pattern as | |
// Address.sendValue(). | |
// solhint-disable-next-line avoid-low-level-calls | |
(bool success, bytes memory returnData) = reimburse.call{ | |
value: refund | |
}(""); | |
// Although `returnData` will have a spurious prefix, all we really | |
// care about is that it contains the ReentrancyGuard reversion | |
// message so we can check in the tests. | |
require(success, string(returnData)); | |
emit Refund(reimburse, refund); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
// Inspired by BaseOpenSea by Simon Fremaux (@dievardump) but without the need | |
// to pass specific addresses depending on deployment network. | |
// https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/ | |
import "./ProxyRegistry.sol"; | |
/// @notice Library to achieve gas-free listings on OpenSea. | |
library OpenSeaGasFreeListing { | |
/** | |
@notice Returns whether the operator is an OpenSea proxy for the owner, thus | |
allowing it to list without the token owner paying gas. | |
@dev ERC{721,1155}.isApprovedForAll should be overriden to also check if | |
this function returns true. | |
*/ | |
function isApprovedForAll(address owner, address operator) | |
internal | |
view | |
returns (bool) | |
{ | |
address proxy = proxyFor(owner); | |
return proxy != address(0) && proxy == operator; | |
} | |
/** | |
@notice Returns the OpenSea proxy address for the owner. | |
*/ | |
function proxyFor(address owner) internal view returns (address) { | |
address registry; | |
uint256 chainId; | |
assembly { | |
chainId := chainid() | |
switch chainId | |
// Production networks are placed higher to minimise the number of | |
// checks performed and therefore reduce gas. By the same rationale, | |
// mainnet comes before Polygon as it's more expensive. | |
case 1 { | |
// mainnet | |
registry := 0xa5409ec958c83c3f309868babaca7c86dcb077c1 | |
} | |
case 137 { | |
// polygon | |
registry := 0x58807baD0B376efc12F5AD86aAc70E78ed67deaE | |
} | |
case 4 { | |
// rinkeby | |
registry := 0xf57b2c51ded3a29e6891aba85459d600256cf317 | |
} | |
case 80001 { | |
// mumbai | |
registry := 0xff7Ca10aF37178BdD056628eF42fD7F799fAc77c | |
} | |
case 1337 { | |
// The geth SimulatedBackend iff used with the ethier | |
// openseatest package. This is mocked as a Wyvern proxy as it's | |
// more complex than the 0x ones. | |
registry := 0xE1a2bbc877b29ADBC56D2659DBcb0ae14ee62071 | |
} | |
} | |
// Unlike Wyvern, the registry itself is the proxy for all owners on 0x | |
// chains. | |
if (registry == address(0) || chainId == 137 || chainId == 80001) { | |
return registry; | |
} | |
return address(ProxyRegistry(registry).proxies(owner)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) | |
pragma solidity >=0.8.0 <0.9.0; | |
/// @notice A minimal interface describing OpenSea's Wyvern proxy registry. | |
contract ProxyRegistry { | |
mapping(address => OwnableDelegateProxy) public proxies; | |
} | |
/** | |
@dev This pattern of using an empty contract is cargo-culted directly from | |
OpenSea's example code. TODO: it's likely that the above mapping can be changed | |
to address => address without affecting anything, but further investigation is | |
needed (i.e. is there a subtle reason that OpenSea released it like this?). | |
*/ | |
// solhint-disable-next-line no-empty-blocks | |
contract OwnableDelegateProxy { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControl.sol"; | |
import "../utils/Context.sol"; | |
import "../utils/Strings.sol"; | |
import "../utils/introspection/ERC165.sol"; | |
/** | |
* @dev Contract module that allows children to implement role-based access | |
* control mechanisms. This is a lightweight version that doesn't allow enumerating role | |
* members except through off-chain means by accessing the contract event logs. Some | |
* applications may benefit from on-chain enumerability, for those cases see | |
* {AccessControlEnumerable}. | |
* | |
* Roles are referred to by their `bytes32` identifier. These should be exposed | |
* in the external API and be unique. The best way to achieve this is by | |
* using `public constant` hash digests: | |
* | |
* ``` | |
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); | |
* ``` | |
* | |
* Roles can be used to represent a set of permissions. To restrict access to a | |
* function call, use {hasRole}: | |
* | |
* ``` | |
* function foo() public { | |
* require(hasRole(MY_ROLE, msg.sender)); | |
* ... | |
* } | |
* ``` | |
* | |
* Roles can be granted and revoked dynamically via the {grantRole} and | |
* {revokeRole} functions. Each role has an associated admin role, and only | |
* accounts that have a role's admin role can call {grantRole} and {revokeRole}. | |
* | |
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means | |
* that only accounts with this role will be able to grant or revoke other | |
* roles. More complex role relationships can be created by using | |
* {_setRoleAdmin}. | |
* | |
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to | |
* grant and revoke this role. Extra precautions should be taken to secure | |
* accounts that have been granted it. | |
*/ | |
abstract contract AccessControl is Context, IAccessControl, ERC165 { | |
struct RoleData { | |
mapping(address => bool) members; | |
bytes32 adminRole; | |
} | |
mapping(bytes32 => RoleData) private _roles; | |
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; | |
/** | |
* @dev Modifier that checks that an account has a specific role. Reverts | |
* with a standardized message including the required role. | |
* | |
* The format of the revert reason is given by the following regular expression: | |
* | |
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ | |
* | |
* _Available since v4.1._ | |
*/ | |
modifier onlyRole(bytes32 role) { | |
_checkRole(role, _msgSender()); | |
_; | |
} | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev Returns `true` if `account` has been granted `role`. | |
*/ | |
function hasRole(bytes32 role, address account) public view virtual override returns (bool) { | |
return _roles[role].members[account]; | |
} | |
/** | |
* @dev Revert with a standard message if `account` is missing `role`. | |
* | |
* The format of the revert reason is given by the following regular expression: | |
* | |
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ | |
*/ | |
function _checkRole(bytes32 role, address account) internal view virtual { | |
if (!hasRole(role, account)) { | |
revert( | |
string( | |
abi.encodePacked( | |
"AccessControl: account ", | |
Strings.toHexString(uint160(account), 20), | |
" is missing role ", | |
Strings.toHexString(uint256(role), 32) | |
) | |
) | |
); | |
} | |
} | |
/** | |
* @dev Returns the admin role that controls `role`. See {grantRole} and | |
* {revokeRole}. | |
* | |
* To change a role's admin, use {_setRoleAdmin}. | |
*/ | |
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { | |
return _roles[role].adminRole; | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* If `account` had been granted `role`, emits a {RoleRevoked} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Revokes `role` from the calling account. | |
* | |
* Roles are often managed via {grantRole} and {revokeRole}: this function's | |
* purpose is to provide a mechanism for accounts to lose their privileges | |
* if they are compromised (such as when a trusted device is misplaced). | |
* | |
* If the calling account had been revoked `role`, emits a {RoleRevoked} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must be `account`. | |
*/ | |
function renounceRole(bytes32 role, address account) public virtual override { | |
require(account == _msgSender(), "AccessControl: can only renounce roles for self"); | |
_revokeRole(role, account); | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. Note that unlike {grantRole}, this function doesn't perform any | |
* checks on the calling account. | |
* | |
* [WARNING] | |
* ==== | |
* This function should only be called from the constructor when setting | |
* up the initial roles for the system. | |
* | |
* Using this function in any other way is effectively circumventing the admin | |
* system imposed by {AccessControl}. | |
* ==== | |
* | |
* NOTE: This function is deprecated in favor of {_grantRole}. | |
*/ | |
function _setupRole(bytes32 role, address account) internal virtual { | |
_grantRole(role, account); | |
} | |
/** | |
* @dev Sets `adminRole` as ``role``'s admin role. | |
* | |
* Emits a {RoleAdminChanged} event. | |
*/ | |
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { | |
bytes32 previousAdminRole = getRoleAdmin(role); | |
_roles[role].adminRole = adminRole; | |
emit RoleAdminChanged(role, previousAdminRole, adminRole); | |
} | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* Internal function without access restriction. | |
*/ | |
function _grantRole(bytes32 role, address account) internal virtual { | |
if (!hasRole(role, account)) { | |
_roles[role].members[account] = true; | |
emit RoleGranted(role, account, _msgSender()); | |
} | |
} | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* Internal function without access restriction. | |
*/ | |
function _revokeRole(bytes32 role, address account) internal virtual { | |
if (hasRole(role, account)) { | |
_roles[role].members[account] = false; | |
emit RoleRevoked(role, account, _msgSender()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControlEnumerable.sol"; | |
import "./AccessControl.sol"; | |
import "../utils/structs/EnumerableSet.sol"; | |
/** | |
* @dev Extension of {AccessControl} that allows enumerating the members of each role. | |
*/ | |
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { | |
using EnumerableSet for EnumerableSet.AddressSet; | |
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev Returns one of the accounts that have `role`. `index` must be a | |
* value between 0 and {getRoleMemberCount}, non-inclusive. | |
* | |
* Role bearers are not sorted in any particular way, and their ordering may | |
* change at any point. | |
* | |
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure | |
* you perform all queries on the same block. See the following | |
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] | |
* for more information. | |
*/ | |
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { | |
return _roleMembers[role].at(index); | |
} | |
/** | |
* @dev Returns the number of accounts that have `role`. Can be used | |
* together with {getRoleMember} to enumerate all bearers of a role. | |
*/ | |
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { | |
return _roleMembers[role].length(); | |
} | |
/** | |
* @dev Overload {_grantRole} to track enumerable memberships | |
*/ | |
function _grantRole(bytes32 role, address account) internal virtual override { | |
super._grantRole(role, account); | |
_roleMembers[role].add(account); | |
} | |
/** | |
* @dev Overload {_revokeRole} to track enumerable memberships | |
*/ | |
function _revokeRole(bytes32 role, address account) internal virtual override { | |
super._revokeRole(role, account); | |
_roleMembers[role].remove(account); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev External interface of AccessControl declared to support ERC165 detection. | |
*/ | |
interface IAccessControl { | |
/** | |
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` | |
* | |
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite | |
* {RoleAdminChanged} not being emitted signaling this. | |
* | |
* _Available since v3.1._ | |
*/ | |
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); | |
/** | |
* @dev Emitted when `account` is granted `role`. | |
* | |
* `sender` is the account that originated the contract call, an admin role | |
* bearer except when using {AccessControl-_setupRole}. | |
*/ | |
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); | |
/** | |
* @dev Emitted when `account` is revoked `role`. | |
* | |
* `sender` is the account that originated the contract call: | |
* - if using `revokeRole`, it is the admin role bearer | |
* - if using `renounceRole`, it is the role bearer (i.e. `account`) | |
*/ | |
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); | |
/** | |
* @dev Returns `true` if `account` has been granted `role`. | |
*/ | |
function hasRole(bytes32 role, address account) external view returns (bool); | |
/** | |
* @dev Returns the admin role that controls `role`. See {grantRole} and | |
* {revokeRole}. | |
* | |
* To change a role's admin, use {AccessControl-_setRoleAdmin}. | |
*/ | |
function getRoleAdmin(bytes32 role) external view returns (bytes32); | |
/** | |
* @dev Grants `role` to `account`. | |
* | |
* If `account` had not been already granted `role`, emits a {RoleGranted} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function grantRole(bytes32 role, address account) external; | |
/** | |
* @dev Revokes `role` from `account`. | |
* | |
* If `account` had been granted `role`, emits a {RoleRevoked} event. | |
* | |
* Requirements: | |
* | |
* - the caller must have ``role``'s admin role. | |
*/ | |
function revokeRole(bytes32 role, address account) external; | |
/** | |
* @dev Revokes `role` from the calling account. | |
* | |
* Roles are often managed via {grantRole} and {revokeRole}: this function's | |
* purpose is to provide a mechanism for accounts to lose their privileges | |
* if they are compromised (such as when a trusted device is misplaced). | |
* | |
* If the calling account had been granted `role`, emits a {RoleRevoked} | |
* event. | |
* | |
* Requirements: | |
* | |
* - the caller must be `account`. | |
*/ | |
function renounceRole(bytes32 role, address account) external; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) | |
pragma solidity ^0.8.0; | |
import "./IAccessControl.sol"; | |
/** | |
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection. | |
*/ | |
interface IAccessControlEnumerable is IAccessControl { | |
/** | |
* @dev Returns one of the accounts that have `role`. `index` must be a | |
* value between 0 and {getRoleMemberCount}, non-inclusive. | |
* | |
* Role bearers are not sorted in any particular way, and their ordering may | |
* change at any point. | |
* | |
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure | |
* you perform all queries on the same block. See the following | |
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] | |
* for more information. | |
*/ | |
function getRoleMember(bytes32 role, uint256 index) external view returns (address); | |
/** | |
* @dev Returns the number of accounts that have `role`. Can be used | |
* together with {getRoleMember} to enumerate all bearers of a role. | |
*/ | |
function getRoleMemberCount(bytes32 role) external view returns (uint256); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) | |
pragma solidity ^0.8.0; | |
import "../utils/Context.sol"; | |
/** | |
* @dev Contract module which provides a basic access control mechanism, where | |
* there is an account (an owner) that can be granted exclusive access to | |
* specific functions. | |
* | |
* By default, the owner account will be the one that deploys the contract. This | |
* can later be changed with {transferOwnership}. | |
* | |
* This module is used through inheritance. It will make available the modifier | |
* `onlyOwner`, which can be applied to your functions to restrict their use to | |
* the owner. | |
*/ | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() { | |
_transferOwnership(_msgSender()); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view virtual returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(owner() == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
_transferOwnership(address(0)); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require(newOwner != address(0), "Ownable: new owner is the zero address"); | |
_transferOwnership(newOwner); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Internal function without access restriction. | |
*/ | |
function _transferOwnership(address newOwner) internal virtual { | |
address oldOwner = _owner; | |
_owner = newOwner; | |
emit OwnershipTransferred(oldOwner, newOwner); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) | |
pragma solidity ^0.8.0; | |
import "../utils/introspection/IERC165.sol"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) | |
pragma solidity ^0.8.0; | |
import "./IERC165.sol"; | |
/** | |
* @dev Interface for the NFT Royalty Standard. | |
* | |
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal | |
* support for royalty payments across all NFT marketplaces and ecosystem participants. | |
* | |
* _Available since v4.5._ | |
*/ | |
interface IERC2981 is IERC165 { | |
/** | |
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of | |
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange. | |
*/ | |
function royaltyInfo(uint256 tokenId, uint256 salePrice) | |
external | |
view | |
returns (address receiver, uint256 royaltyAmount); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) | |
pragma solidity ^0.8.0; | |
import "../token/ERC721/IERC721.sol"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) | |
pragma solidity ^0.8.0; | |
import "../utils/Context.sol"; | |
/** | |
* @dev Contract module which allows children to implement an emergency stop | |
* mechanism that can be triggered by an authorized account. | |
* | |
* This module is used through inheritance. It will make available the | |
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to | |
* the functions of your contract. Note that they will not be pausable by | |
* simply including this module, only once the modifiers are put in place. | |
*/ | |
abstract contract Pausable is Context { | |
/** | |
* @dev Emitted when the pause is triggered by `account`. | |
*/ | |
event Paused(address account); | |
/** | |
* @dev Emitted when the pause is lifted by `account`. | |
*/ | |
event Unpaused(address account); | |
bool private _paused; | |
/** | |
* @dev Initializes the contract in unpaused state. | |
*/ | |
constructor() { | |
_paused = false; | |
} | |
/** | |
* @dev Returns true if the contract is paused, and false otherwise. | |
*/ | |
function paused() public view virtual returns (bool) { | |
return _paused; | |
} | |
/** | |
* @dev Modifier to make a function callable only when the contract is not paused. | |
* | |
* Requirements: | |
* | |
* - The contract must not be paused. | |
*/ | |
modifier whenNotPaused() { | |
require(!paused(), "Pausable: paused"); | |
_; | |
} | |
/** | |
* @dev Modifier to make a function callable only when the contract is paused. | |
* | |
* Requirements: | |
* | |
* - The contract must be paused. | |
*/ | |
modifier whenPaused() { | |
require(paused(), "Pausable: not paused"); | |
_; | |
} | |
/** | |
* @dev Triggers stopped state. | |
* | |
* Requirements: | |
* | |
* - The contract must not be paused. | |
*/ | |
function _pause() internal virtual whenNotPaused { | |
_paused = true; | |
emit Paused(_msgSender()); | |
} | |
/** | |
* @dev Returns to normal state. | |
* | |
* Requirements: | |
* | |
* - The contract must be paused. | |
*/ | |
function _unpause() internal virtual whenPaused { | |
_paused = false; | |
emit Unpaused(_msgSender()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) | |
pragma solidity ^0.8.0; | |
import "../../interfaces/IERC2981.sol"; | |
import "../../utils/introspection/ERC165.sol"; | |
/** | |
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. | |
* | |
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for | |
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. | |
* | |
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the | |
* fee is specified in basis points by default. | |
* | |
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See | |
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to | |
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. | |
* | |
* _Available since v4.5._ | |
*/ | |
abstract contract ERC2981 is IERC2981, ERC165 { | |
struct RoyaltyInfo { | |
address receiver; | |
uint96 royaltyFraction; | |
} | |
RoyaltyInfo private _defaultRoyaltyInfo; | |
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { | |
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @inheritdoc IERC2981 | |
*/ | |
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) | |
external | |
view | |
virtual | |
override | |
returns (address, uint256) | |
{ | |
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; | |
if (royalty.receiver == address(0)) { | |
royalty = _defaultRoyaltyInfo; | |
} | |
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); | |
return (royalty.receiver, royaltyAmount); | |
} | |
/** | |
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a | |
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an | |
* override. | |
*/ | |
function _feeDenominator() internal pure virtual returns (uint96) { | |
return 10000; | |
} | |
/** | |
* @dev Sets the royalty information that all ids in this contract will default to. | |
* | |
* Requirements: | |
* | |
* - `receiver` cannot be the zero address. | |
* - `feeNumerator` cannot be greater than the fee denominator. | |
*/ | |
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { | |
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); | |
require(receiver != address(0), "ERC2981: invalid receiver"); | |
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); | |
} | |
/** | |
* @dev Removes default royalty information. | |
*/ | |
function _deleteDefaultRoyalty() internal virtual { | |
delete _defaultRoyaltyInfo; | |
} | |
/** | |
* @dev Sets the royalty information for a specific token id, overriding the global default. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must be already minted. | |
* - `receiver` cannot be the zero address. | |
* - `feeNumerator` cannot be greater than the fee denominator. | |
*/ | |
function _setTokenRoyalty( | |
uint256 tokenId, | |
address receiver, | |
uint96 feeNumerator | |
) internal virtual { | |
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); | |
require(receiver != address(0), "ERC2981: Invalid parameters"); | |
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); | |
} | |
/** | |
* @dev Resets royalty information for the token id back to the global default. | |
*/ | |
function _resetTokenRoyalty(uint256 tokenId) internal virtual { | |
delete _tokenRoyaltyInfo[tokenId]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) | |
pragma solidity ^0.8.0; | |
import "../../utils/introspection/IERC165.sol"; | |
/** | |
* @dev Required interface of an ERC721 compliant contract. | |
*/ | |
interface IERC721 is IERC165 { | |
/** | |
* @dev Emitted when `tokenId` token is transferred from `from` to `to`. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. | |
*/ | |
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. | |
*/ | |
event ApprovalForAll(address indexed owner, address indexed operator, bool approved); | |
/** | |
* @dev Returns the number of tokens in ``owner``'s account. | |
*/ | |
function balanceOf(address owner) external view returns (uint256 balance); | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) external view returns (address owner); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients | |
* are aware of the ERC721 protocol to prevent tokens from being forever locked. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external; | |
/** | |
* @dev Transfers `tokenId` token from `from` to `to`. | |
* | |
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external; | |
/** | |
* @dev Gives permission to `to` to transfer `tokenId` token to another account. | |
* The approval is cleared when the token is transferred. | |
* | |
* Only a single account can be approved at a time, so approving the zero address clears previous approvals. | |
* | |
* Requirements: | |
* | |
* - The caller must own the token or be an approved operator. | |
* - `tokenId` must exist. | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address to, uint256 tokenId) external; | |
/** | |
* @dev Returns the account approved for `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function getApproved(uint256 tokenId) external view returns (address operator); | |
/** | |
* @dev Approve or remove `operator` as an operator for the caller. | |
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. | |
* | |
* Requirements: | |
* | |
* - The `operator` cannot be the caller. | |
* | |
* Emits an {ApprovalForAll} event. | |
*/ | |
function setApprovalForAll(address operator, bool _approved) external; | |
/** | |
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. | |
* | |
* See {setApprovalForAll} | |
*/ | |
function isApprovedForAll(address owner, address operator) external view returns (bool); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes calldata data | |
) external; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC721 token receiver interface | |
* @dev Interface for any contract that wants to support safeTransfers | |
* from ERC721 asset contracts. | |
*/ | |
interface IERC721Receiver { | |
/** | |
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} | |
* by `operator` from `from`, this function is called. | |
* | |
* It must return its Solidity selector to confirm the token transfer. | |
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. | |
* | |
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. | |
*/ | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (bytes4); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.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 | |
assembly { | |
let returndata_size := mload(returndata) | |
revert(add(32, returndata), returndata_size) | |
} | |
} else { | |
revert(errorMessage); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) | |
pragma solidity ^0.8.0; | |
import "../Strings.sol"; | |
/** | |
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. | |
* | |
* These functions can be used to verify that a message was signed by the holder | |
* of the private keys of a given address. | |
*/ | |
library ECDSA { | |
enum RecoverError { | |
NoError, | |
InvalidSignature, | |
InvalidSignatureLength, | |
InvalidSignatureS, | |
InvalidSignatureV | |
} | |
function _throwError(RecoverError error) private pure { | |
if (error == RecoverError.NoError) { | |
return; // no error: do nothing | |
} else if (error == RecoverError.InvalidSignature) { | |
revert("ECDSA: invalid signature"); | |
} else if (error == RecoverError.InvalidSignatureLength) { | |
revert("ECDSA: invalid signature length"); | |
} else if (error == RecoverError.InvalidSignatureS) { | |
revert("ECDSA: invalid signature 's' value"); | |
} else if (error == RecoverError.InvalidSignatureV) { | |
revert("ECDSA: invalid signature 'v' value"); | |
} | |
} | |
/** | |
* @dev Returns the address that signed a hashed message (`hash`) with | |
* `signature` or error string. This address can then be used for verification purposes. | |
* | |
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: | |
* this function rejects them by requiring the `s` value to be in the lower | |
* half order, and the `v` value to be either 27 or 28. | |
* | |
* IMPORTANT: `hash` _must_ be the result of a hash operation for the | |
* verification to be secure: it is possible to craft signatures that | |
* recover to arbitrary addresses for non-hashed data. A safe way to ensure | |
* this is by receiving a hash of the original message (which may otherwise | |
* be too long), and then calling {toEthSignedMessageHash} on it. | |
* | |
* Documentation for signature generation: | |
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] | |
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { | |
// Check the signature length | |
// - case 65: r,s,v signature (standard) | |
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ | |
if (signature.length == 65) { | |
bytes32 r; | |
bytes32 s; | |
uint8 v; | |
// ecrecover takes the signature parameters, and the only way to get them | |
// currently is to use assembly. | |
assembly { | |
r := mload(add(signature, 0x20)) | |
s := mload(add(signature, 0x40)) | |
v := byte(0, mload(add(signature, 0x60))) | |
} | |
return tryRecover(hash, v, r, s); | |
} else if (signature.length == 64) { | |
bytes32 r; | |
bytes32 vs; | |
// ecrecover takes the signature parameters, and the only way to get them | |
// currently is to use assembly. | |
assembly { | |
r := mload(add(signature, 0x20)) | |
vs := mload(add(signature, 0x40)) | |
} | |
return tryRecover(hash, r, vs); | |
} else { | |
return (address(0), RecoverError.InvalidSignatureLength); | |
} | |
} | |
/** | |
* @dev Returns the address that signed a hashed message (`hash`) with | |
* `signature`. This address can then be used for verification purposes. | |
* | |
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: | |
* this function rejects them by requiring the `s` value to be in the lower | |
* half order, and the `v` value to be either 27 or 28. | |
* | |
* IMPORTANT: `hash` _must_ be the result of a hash operation for the | |
* verification to be secure: it is possible to craft signatures that | |
* recover to arbitrary addresses for non-hashed data. A safe way to ensure | |
* this is by receiving a hash of the original message (which may otherwise | |
* be too long), and then calling {toEthSignedMessageHash} on it. | |
*/ | |
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, signature); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. | |
* | |
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover( | |
bytes32 hash, | |
bytes32 r, | |
bytes32 vs | |
) internal pure returns (address, RecoverError) { | |
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); | |
uint8 v = uint8((uint256(vs) >> 255) + 27); | |
return tryRecover(hash, v, r, s); | |
} | |
/** | |
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. | |
* | |
* _Available since v4.2._ | |
*/ | |
function recover( | |
bytes32 hash, | |
bytes32 r, | |
bytes32 vs | |
) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, r, vs); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Overload of {ECDSA-tryRecover} that receives the `v`, | |
* `r` and `s` signature fields separately. | |
* | |
* _Available since v4.3._ | |
*/ | |
function tryRecover( | |
bytes32 hash, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) internal pure returns (address, RecoverError) { | |
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature | |
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines | |
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most | |
// signatures from current libraries generate a unique signature with an s-value in the lower half order. | |
// | |
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value | |
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or | |
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept | |
// these malleable signatures as well. | |
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { | |
return (address(0), RecoverError.InvalidSignatureS); | |
} | |
if (v != 27 && v != 28) { | |
return (address(0), RecoverError.InvalidSignatureV); | |
} | |
// If the signature is valid (and not malleable), return the signer address | |
address signer = ecrecover(hash, v, r, s); | |
if (signer == address(0)) { | |
return (address(0), RecoverError.InvalidSignature); | |
} | |
return (signer, RecoverError.NoError); | |
} | |
/** | |
* @dev Overload of {ECDSA-recover} that receives the `v`, | |
* `r` and `s` signature fields separately. | |
*/ | |
function recover( | |
bytes32 hash, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) internal pure returns (address) { | |
(address recovered, RecoverError error) = tryRecover(hash, v, r, s); | |
_throwError(error); | |
return recovered; | |
} | |
/** | |
* @dev Returns an Ethereum Signed Message, created from a `hash`. This | |
* produces hash corresponding to the one signed with the | |
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] | |
* JSON-RPC method as part of EIP-191. | |
* | |
* See {recover}. | |
*/ | |
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { | |
// 32 is the length in bytes of hash, | |
// enforced by the type signature above | |
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); | |
} | |
/** | |
* @dev Returns an Ethereum Signed Message, created from `s`. This | |
* produces hash corresponding to the one signed with the | |
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] | |
* JSON-RPC method as part of EIP-191. | |
* | |
* See {recover}. | |
*/ | |
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { | |
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); | |
} | |
/** | |
* @dev Returns an Ethereum Signed Typed Data, created from a | |
* `domainSeparator` and a `structHash`. This produces hash corresponding | |
* to the one signed with the | |
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] | |
* JSON-RPC method as part of EIP-712. | |
* | |
* See {recover}. | |
*/ | |
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { | |
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Standard math utilities missing in the Solidity language. | |
*/ | |
library Math { | |
/** | |
* @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 / b + (a % b == 0 ? 0 : 1); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev String operations. | |
*/ | |
library Strings { | |
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` decimal representation. | |
*/ | |
function toString(uint256 value) internal pure returns (string memory) { | |
// Inspired by OraclizeAPI's implementation - MIT licence | |
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol | |
if (value == 0) { | |
return "0"; | |
} | |
uint256 temp = value; | |
uint256 digits; | |
while (temp != 0) { | |
digits++; | |
temp /= 10; | |
} | |
bytes memory buffer = new bytes(digits); | |
while (value != 0) { | |
digits -= 1; | |
buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); | |
value /= 10; | |
} | |
return string(buffer); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. | |
*/ | |
function toHexString(uint256 value) internal pure returns (string memory) { | |
if (value == 0) { | |
return "0x00"; | |
} | |
uint256 temp = value; | |
uint256 length = 0; | |
while (temp != 0) { | |
length++; | |
temp >>= 8; | |
} | |
return toHexString(value, length); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. | |
*/ | |
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { | |
bytes memory buffer = new bytes(2 * length + 2); | |
buffer[0] = "0"; | |
buffer[1] = "x"; | |
for (uint256 i = 2 * length + 1; i > 1; --i) { | |
buffer[i] = _HEX_SYMBOLS[value & 0xf]; | |
value >>= 4; | |
} | |
require(value == 0, "Strings: hex length insufficient"); | |
return string(buffer); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential. | |
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor]. | |
*/ | |
library BitMaps { | |
struct BitMap { | |
mapping(uint256 => uint256) _data; | |
} | |
/** | |
* @dev Returns whether the bit at `index` is set. | |
*/ | |
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
return bitmap._data[bucket] & mask != 0; | |
} | |
/** | |
* @dev Sets the bit at `index` to the boolean `value`. | |
*/ | |
function setTo( | |
BitMap storage bitmap, | |
uint256 index, | |
bool value | |
) internal { | |
if (value) { | |
set(bitmap, index); | |
} else { | |
unset(bitmap, index); | |
} | |
} | |
/** | |
* @dev Sets the bit at `index`. | |
*/ | |
function set(BitMap storage bitmap, uint256 index) internal { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
bitmap._data[bucket] |= mask; | |
} | |
/** | |
* @dev Unsets the bit at `index`. | |
*/ | |
function unset(BitMap storage bitmap, uint256 index) internal { | |
uint256 bucket = index >> 8; | |
uint256 mask = 1 << (index & 0xff); | |
bitmap._data[bucket] &= ~mask; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing | |
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive | |
* types. | |
* | |
* Sets have the following properties: | |
* | |
* - Elements are added, removed, and checked for existence in constant time | |
* (O(1)). | |
* - Elements are enumerated in O(n). No guarantees are made on the ordering. | |
* | |
* ``` | |
* contract Example { | |
* // Add the library methods | |
* using EnumerableSet for EnumerableSet.AddressSet; | |
* | |
* // Declare a set state variable | |
* EnumerableSet.AddressSet private mySet; | |
* } | |
* ``` | |
* | |
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) | |
* and `uint256` (`UintSet`) are supported. | |
*/ | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping(bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { | |
// Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
if (lastIndex != toDeleteIndex) { | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex | |
} | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) private view returns (bool) { | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) private view returns (bytes32) { | |
return set._values[index]; | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function _values(Set storage set) private view returns (bytes32[] memory) { | |
return set._values; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { | |
return _at(set._inner, index); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { | |
return _values(set._inner); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) internal returns (bool) { | |
return _add(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) internal returns (bool) { | |
return _remove(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) internal view returns (address) { | |
return address(uint160(uint256(_at(set._inner, index)))); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(AddressSet storage set) internal view returns (address[] memory) { | |
bytes32[] memory store = _values(set._inner); | |
address[] memory result; | |
assembly { | |
result := store | |
} | |
return result; | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) internal returns (bool) { | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) internal view returns (uint256) { | |
return uint256(_at(set._inner, index)); | |
} | |
/** | |
* @dev Return the entire set in an array | |
* | |
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed | |
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that | |
* this function has an unbounded cost, and using it as part of a state-changing function may render the function | |
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. | |
*/ | |
function values(UintSet storage set) internal view returns (uint256[] memory) { | |
bytes32[] memory store = _values(set._inner); | |
uint256[] memory result; | |
assembly { | |
result := store | |
} | |
return result; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity >=0.8.10 <0.9.0; | |
import "@divergencetech/ethier/contracts/crypto/SignatureChecker.sol"; | |
import "@divergencetech/ethier/contracts/crypto/SignerManager.sol"; | |
import "@divergencetech/ethier/contracts/erc721/BaseTokenURI.sol"; | |
import "@divergencetech/ethier/contracts/erc721/ERC721ACommon.sol"; | |
import "@divergencetech/ethier/contracts/erc721/ERC721Redeemer.sol"; | |
import "@divergencetech/ethier/contracts/sales/FixedPriceSeller.sol"; | |
import "@divergencetech/ethier/contracts/utils/Monotonic.sol"; | |
import "@openzeppelin/contracts/token/common/ERC2981.sol"; | |
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; | |
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; | |
interface ITokenURIGenerator { | |
function tokenURI(uint256 tokenId) external view returns (string memory); | |
} | |
// @author divergence.xyz | |
contract Moonbirds is | |
ERC721ACommon, | |
BaseTokenURI, | |
FixedPriceSeller, | |
SignerManager, | |
ERC2981, | |
AccessControlEnumerable | |
{ | |
using EnumerableSet for EnumerableSet.AddressSet; | |
using ERC721Redeemer for ERC721Redeemer.Claims; | |
using Monotonic for Monotonic.Increaser; | |
using SignatureChecker for EnumerableSet.AddressSet; | |
IERC721 public immutable proof; | |
/** | |
@notice Role of administrative users allowed to expel a Moonbird from the | |
nest. | |
@dev See expelFromNest(). | |
*/ | |
bytes32 public constant EXPULSION_ROLE = keccak256("EXPULSION_ROLE"); | |
constructor( | |
string memory name, | |
string memory symbol, | |
IERC721 _proof, | |
address payable beneficiary, | |
address payable royaltyReceiver | |
) | |
ERC721ACommon(name, symbol) | |
BaseTokenURI("") | |
FixedPriceSeller( | |
2.5 ether, | |
// Not including a separate pool for PROOF holders, taking the total | |
// to 10k. We don't enforce buyer limits here because it's already | |
// done by only issuing a single signature per address, and double | |
// enforcement would waste gas. | |
Seller.SellerConfig({ | |
totalInventory: 8_000, | |
lockTotalInventory: true, | |
maxPerAddress: 0, | |
maxPerTx: 0, | |
freeQuota: 125, | |
lockFreeQuota: false, | |
reserveFreeQuota: true | |
}), | |
beneficiary | |
) | |
{ | |
proof = _proof; | |
_setDefaultRoyalty(royaltyReceiver, 500); | |
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender); | |
} | |
/** | |
@dev Mint tokens purchased via the Seller. | |
*/ | |
function _handlePurchase( | |
address to, | |
uint256 n, | |
bool | |
) internal override { | |
_safeMint(to, n); | |
// We're using two separate pools (one from Seller, and one for PROOF | |
// minting), so add an extra layer of checks for this invariant. This | |
// should never fail as each pool has its own restriction, and is in | |
// place purely for tests (hence assert). | |
assert(totalSupply() <= 10_000); | |
} | |
/** | |
@dev Record of already-used signatures. | |
*/ | |
mapping(bytes32 => bool) public usedMessages; | |
/** | |
@notice Mint as a non-holder of PROOF tokens. | |
*/ | |
function mintPublic( | |
address to, | |
bytes32 nonce, | |
bytes calldata sig | |
) external payable { | |
signers.requireValidSignature( | |
signaturePayload(to, nonce), | |
sig, | |
usedMessages | |
); | |
_purchase(to, 1); | |
} | |
/** | |
@notice Returns whether the address has minted with the particular nonce. If | |
true, future calls to mint() with the same parameters will fail. | |
@dev In production we will never issue more than a single nonce per address, | |
but this allows for testing with a single address. | |
*/ | |
function alreadyMinted(address to, bytes32 nonce) | |
external | |
view | |
returns (bool) | |
{ | |
return | |
usedMessages[ | |
SignatureChecker.generateMessage(signaturePayload(to, nonce)) | |
]; | |
} | |
/** | |
@dev Constructs the buffer that is hashed for validation with a minting | |
signature. | |
*/ | |
function signaturePayload(address to, bytes32 nonce) | |
internal | |
pure | |
returns (bytes memory) | |
{ | |
return abi.encodePacked(to, nonce); | |
} | |
/** | |
@notice Two guaranteed mints per PROOF holder. | |
@dev This is specifically tracked because unclaimed tokens will be minted to | |
the PROOF wallet, so the pool guarantees an upper bound. | |
*/ | |
uint256 public proofPoolRemaining = 2000; | |
ERC721Redeemer.Claims private redeemedPROOF; | |
/** | |
@dev Used by both PROOF-holder and PROOF-admin minting from the pool. | |
*/ | |
modifier reducePROOFPool(uint256 n) { | |
require(n <= proofPoolRemaining, "Moonbirds: PROOF pool exhausted"); | |
proofPoolRemaining -= n; | |
_; | |
} | |
/** | |
@notice Flag indicating whether holders of PROOF passes can mint. | |
*/ | |
bool public proofMintingOpen = false; | |
/** | |
@notice Sets whether holders of PROOF passes can mint. | |
*/ | |
function setPROOFMintingOpen(bool open) external onlyOwner { | |
proofMintingOpen = open; | |
} | |
/** | |
@notice Mint as a holder of a PROOF token. | |
@dev Repeat a PROOF token ID twice to redeem both of its claims; recurring | |
values SHOULD be adjacent for improved gas (eg [1,1,2,2] not [1,2,1,2]). | |
*/ | |
function mintPROOF(uint256[] calldata proofTokenIds) | |
external | |
reducePROOFPool(proofTokenIds.length) | |
{ | |
require(proofMintingOpen, "Moonbirds: PROOF minting closed"); | |
uint256 n = redeemedPROOF.redeem(2, msg.sender, proof, proofTokenIds); | |
_handlePurchase(msg.sender, n, true); | |
} | |
/** | |
@notice Returns how many additional Moonbirds can be claimed with the PROOF | |
token. | |
*/ | |
function proofClaimsRemaining(uint256 tokenId) | |
external | |
view | |
returns (uint256) | |
{ | |
require(tokenId < 1000, "Token doesn't exist"); | |
return 2 - redeemedPROOF.claimed(tokenId); | |
} | |
/** | |
@notice Mint unclaimed tokens from the PROOF-holder pool. | |
*/ | |
function mintUnclaimed(address to, uint256 n) | |
external | |
onlyOwner | |
reducePROOFPool(n) | |
{ | |
_handlePurchase(to, n, true); | |
} | |
/** | |
@dev tokenId to nesting start time (0 = not nesting). | |
*/ | |
mapping(uint256 => uint256) private nestingStarted; | |
/** | |
@dev Cumulative per-token nesting, excluding the current period. | |
*/ | |
mapping(uint256 => uint256) private nestingTotal; | |
/** | |
@notice Returns the length of time, in seconds, that the Moonbird has | |
nested. | |
@dev Nesting is tied to a specific Moonbird, not to the owner, so it doesn't | |
reset upon sale. | |
@return nesting Whether the Moonbird is currently nesting. MAY be true with | |
zero current nesting if in the same block as nesting began. | |
@return current Zero if not currently nesting, otherwise the length of time | |
since the most recent nesting began. | |
@return total Total period of time for which the Moonbird has nested across | |
its life, including the current period. | |
*/ | |
function nestingPeriod(uint256 tokenId) | |
external | |
view | |
returns ( | |
bool nesting, | |
uint256 current, | |
uint256 total | |
) | |
{ | |
uint256 start = nestingStarted[tokenId]; | |
if (start != 0) { | |
nesting = true; | |
current = block.timestamp - start; | |
} | |
total = current + nestingTotal[tokenId]; | |
} | |
/** | |
@dev MUST only be modified by safeTransferWhileNesting(); if set to 2 then | |
the _beforeTokenTransfer() block while nesting is disabled. | |
*/ | |
uint256 private nestingTransfer = 1; | |
/** | |
@notice Transfer a token between addresses while the Moonbird is minting, | |
thus not resetting the nesting period. | |
*/ | |
function safeTransferWhileNesting( | |
address from, | |
address to, | |
uint256 tokenId | |
) external { | |
require(ownerOf(tokenId) == _msgSender(), "Moonbirds: Only owner"); | |
nestingTransfer = 2; | |
safeTransferFrom(from, to, tokenId); | |
nestingTransfer = 1; | |
} | |
/** | |
@dev Block transfers while nesting. | |
*/ | |
function _beforeTokenTransfers( | |
address, | |
address, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal view override { | |
uint256 tokenId = startTokenId; | |
for (uint256 end = tokenId + quantity; tokenId < end; ++tokenId) { | |
require( | |
nestingStarted[tokenId] == 0 || nestingTransfer == 2, | |
"Moonbirds: nesting" | |
); | |
} | |
} | |
/** | |
@dev Emitted when a Moonbird begins nesting. | |
*/ | |
event Nested(uint256 indexed tokenId); | |
/** | |
@dev Emitted when a Moonbird stops nesting; either through standard means or | |
by expulsion. | |
*/ | |
event Unnested(uint256 indexed tokenId); | |
/** | |
@dev Emitted when a Moonbird is expelled from the nest. | |
*/ | |
event Expelled(uint256 indexed tokenId); | |
/** | |
@notice Whether nesting is currently allowed. | |
@dev If false then nesting is blocked, but unnesting is always allowed. | |
*/ | |
bool public nestingOpen = false; | |
/** | |
@notice Toggles the `nestingOpen` flag. | |
*/ | |
function setNestingOpen(bool open) external onlyOwner { | |
nestingOpen = open; | |
} | |
/** | |
@notice Changes the Moonbird's nesting status. | |
*/ | |
function toggleNesting(uint256 tokenId) | |
internal | |
onlyApprovedOrOwner(tokenId) | |
{ | |
uint256 start = nestingStarted[tokenId]; | |
if (start == 0) { | |
require(nestingOpen, "Moonbirds: nesting closed"); | |
nestingStarted[tokenId] = block.timestamp; | |
emit Nested(tokenId); | |
} else { | |
nestingTotal[tokenId] += block.timestamp - start; | |
nestingStarted[tokenId] = 0; | |
emit Unnested(tokenId); | |
} | |
} | |
/** | |
@notice Changes the Moonbirds' nesting statuss (what's the plural of status? | |
statii? statuses? status? The plural of sheep is sheep; maybe it's also the | |
plural of status). | |
@dev Changes the Moonbirds' nesting sheep (see @notice). | |
*/ | |
function toggleNesting(uint256[] calldata tokenIds) external { | |
uint256 n = tokenIds.length; | |
for (uint256 i = 0; i < n; ++i) { | |
toggleNesting(tokenIds[i]); | |
} | |
} | |
/** | |
@notice Admin-only ability to expel a Moonbird from the nest. | |
@dev As most sales listings use off-chain signatures it's impossible to | |
detect someone who has nested and then deliberately undercuts the floor | |
price in the knowledge that the sale can't proceed. This function allows for | |
monitoring of such practices and expulsion if abuse is detected, allowing | |
the undercutting bird to be sold on the open market. Since OpenSea uses | |
isApprovedForAll() in its pre-listing checks, we can't block by that means | |
because nesting would then be all-or-nothing for all of a particular owner's | |
Moonbirds. | |
*/ | |
function expelFromNest(uint256 tokenId) external onlyRole(EXPULSION_ROLE) { | |
require(nestingStarted[tokenId] != 0, "Moonbirds: not nested"); | |
nestingTotal[tokenId] += block.timestamp - nestingStarted[tokenId]; | |
nestingStarted[tokenId] = 0; | |
emit Unnested(tokenId); | |
emit Expelled(tokenId); | |
} | |
/** | |
@dev Required override to select the correct baseTokenURI. | |
*/ | |
function _baseURI() | |
internal | |
view | |
override(BaseTokenURI, ERC721A) | |
returns (string memory) | |
{ | |
return BaseTokenURI._baseURI(); | |
} | |
/** | |
@notice If set, contract to which tokenURI() calls are proxied. | |
*/ | |
ITokenURIGenerator public renderingContract; | |
/** | |
@notice Sets the optional tokenURI override contract. | |
*/ | |
function setRenderingContract(ITokenURIGenerator _contract) | |
external | |
onlyOwner | |
{ | |
renderingContract = _contract; | |
} | |
/** | |
@notice If renderingContract is set then returns its tokenURI(tokenId) | |
return value, otherwise returns the standard baseTokenURI + tokenId. | |
*/ | |
function tokenURI(uint256 tokenId) | |
public | |
view | |
override | |
returns (string memory) | |
{ | |
if (address(renderingContract) != address(0)) { | |
return renderingContract.tokenURI(tokenId); | |
} | |
return super.tokenURI(tokenId); | |
} | |
/** | |
@notice Sets the contract-wide royalty info. | |
*/ | |
function setRoyaltyInfo(address receiver, uint96 feeBasisPoints) | |
external | |
onlyOwner | |
{ | |
_setDefaultRoyalty(receiver, feeBasisPoints); | |
} | |
function supportsInterface(bytes4 interfaceId) | |
public | |
view | |
override(ERC721ACommon, ERC2981, AccessControlEnumerable) | |
returns (bool) | |
{ | |
return super.supportsInterface(interfaceId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
// Creator: Chiru Labs | |
pragma solidity ^0.8.4; | |
import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; | |
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; | |
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; | |
import '@openzeppelin/contracts/utils/Address.sol'; | |
import '@openzeppelin/contracts/utils/Context.sol'; | |
import '@openzeppelin/contracts/utils/Strings.sol'; | |
import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; | |
error ApprovalCallerNotOwnerNorApproved(); | |
error ApprovalQueryForNonexistentToken(); | |
error ApproveToCaller(); | |
error ApprovalToCurrentOwner(); | |
error BalanceQueryForZeroAddress(); | |
error MintToZeroAddress(); | |
error MintZeroQuantity(); | |
error OwnerQueryForNonexistentToken(); | |
error TransferCallerNotOwnerNorApproved(); | |
error TransferFromIncorrectOwner(); | |
error TransferToNonERC721ReceiverImplementer(); | |
error TransferToZeroAddress(); | |
error URIQueryForNonexistentToken(); | |
/** | |
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including | |
* the Metadata extension. Built to optimize for lower gas during batch mints. | |
* | |
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). | |
* | |
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. | |
* | |
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). | |
*/ | |
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { | |
using Address for address; | |
using Strings for uint256; | |
// Compiler will pack this into a single 256bit word. | |
struct TokenOwnership { | |
// The address of the owner. | |
address addr; | |
// Keeps track of the start time of ownership with minimal overhead for tokenomics. | |
uint64 startTimestamp; | |
// Whether the token has been burned. | |
bool burned; | |
} | |
// Compiler will pack this into a single 256bit word. | |
struct AddressData { | |
// Realistically, 2**64-1 is more than enough. | |
uint64 balance; | |
// Keeps track of mint count with minimal overhead for tokenomics. | |
uint64 numberMinted; | |
// Keeps track of burn count with minimal overhead for tokenomics. | |
uint64 numberBurned; | |
// For miscellaneous variable(s) pertaining to the address | |
// (e.g. number of whitelist mint slots used). | |
// If there are multiple variables, please pack them into a uint64. | |
uint64 aux; | |
} | |
// The tokenId of the next token to be minted. | |
uint256 internal _currentIndex; | |
// The number of tokens burned. | |
uint256 internal _burnCounter; | |
// Token name | |
string private _name; | |
// Token symbol | |
string private _symbol; | |
// Mapping from token ID to ownership details | |
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. | |
mapping(uint256 => TokenOwnership) internal _ownerships; | |
// Mapping owner address to address data | |
mapping(address => AddressData) private _addressData; | |
// 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; | |
constructor(string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
_currentIndex = _startTokenId(); | |
} | |
/** | |
* To change the starting tokenId, please override this function. | |
*/ | |
function _startTokenId() internal view virtual returns (uint256) { | |
return 0; | |
} | |
/** | |
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. | |
*/ | |
function totalSupply() public view returns (uint256) { | |
// Counter underflow is impossible as _burnCounter cannot be incremented | |
// more than _currentIndex - _startTokenId() times | |
unchecked { | |
return _currentIndex - _burnCounter - _startTokenId(); | |
} | |
} | |
/** | |
* Returns the total amount of tokens minted in the contract. | |
*/ | |
function _totalMinted() internal view returns (uint256) { | |
// Counter underflow is impossible as _currentIndex does not decrement, | |
// and it is initialized to _startTokenId() | |
unchecked { | |
return _currentIndex - _startTokenId(); | |
} | |
} | |
/** | |
* @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 override returns (uint256) { | |
if (owner == address(0)) revert BalanceQueryForZeroAddress(); | |
return uint256(_addressData[owner].balance); | |
} | |
/** | |
* Returns the number of tokens minted by `owner`. | |
*/ | |
function _numberMinted(address owner) internal view returns (uint256) { | |
return uint256(_addressData[owner].numberMinted); | |
} | |
/** | |
* Returns the number of tokens burned by or on behalf of `owner`. | |
*/ | |
function _numberBurned(address owner) internal view returns (uint256) { | |
return uint256(_addressData[owner].numberBurned); | |
} | |
/** | |
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). | |
*/ | |
function _getAux(address owner) internal view returns (uint64) { | |
return _addressData[owner].aux; | |
} | |
/** | |
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). | |
* If there are multiple variables, please pack them into a uint64. | |
*/ | |
function _setAux(address owner, uint64 aux) internal { | |
_addressData[owner].aux = aux; | |
} | |
/** | |
* Gas spent here starts off proportional to the maximum mint batch size. | |
* It gradually moves to O(1) as tokens get transferred around in the collection over time. | |
*/ | |
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { | |
uint256 curr = tokenId; | |
unchecked { | |
if (_startTokenId() <= curr && curr < _currentIndex) { | |
TokenOwnership memory ownership = _ownerships[curr]; | |
if (!ownership.burned) { | |
if (ownership.addr != address(0)) { | |
return ownership; | |
} | |
// Invariant: | |
// There will always be an ownership that has an address and is not burned | |
// before an ownership that does not have an address and is not burned. | |
// Hence, curr will not underflow. | |
while (true) { | |
curr--; | |
ownership = _ownerships[curr]; | |
if (ownership.addr != address(0)) { | |
return ownership; | |
} | |
} | |
} | |
} | |
} | |
revert OwnerQueryForNonexistentToken(); | |
} | |
/** | |
* @dev See {IERC721-ownerOf}. | |
*/ | |
function ownerOf(uint256 tokenId) public view override returns (address) { | |
return _ownershipOf(tokenId).addr; | |
} | |
/** | |
* @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) { | |
if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); | |
string memory baseURI = _baseURI(); | |
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; | |
} | |
/** | |
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each | |
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty | |
* by default, can be overriden in child contracts. | |
*/ | |
function _baseURI() internal view virtual returns (string memory) { | |
return ''; | |
} | |
/** | |
* @dev See {IERC721-approve}. | |
*/ | |
function approve(address to, uint256 tokenId) public override { | |
address owner = ERC721A.ownerOf(tokenId); | |
if (to == owner) revert ApprovalToCurrentOwner(); | |
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { | |
revert ApprovalCallerNotOwnerNorApproved(); | |
} | |
_approve(to, tokenId, owner); | |
} | |
/** | |
* @dev See {IERC721-getApproved}. | |
*/ | |
function getApproved(uint256 tokenId) public view override returns (address) { | |
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); | |
return _tokenApprovals[tokenId]; | |
} | |
/** | |
* @dev See {IERC721-setApprovalForAll}. | |
*/ | |
function setApprovalForAll(address operator, bool approved) public virtual override { | |
if (operator == _msgSender()) revert ApproveToCaller(); | |
_operatorApprovals[_msgSender()][operator] = approved; | |
emit ApprovalForAll(_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 { | |
_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 { | |
_transfer(from, to, tokenId); | |
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { | |
revert TransferToNonERC721ReceiverImplementer(); | |
} | |
} | |
/** | |
* @dev Returns whether `tokenId` exists. | |
* | |
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. | |
* | |
* Tokens start existing when they are minted (`_mint`), | |
*/ | |
function _exists(uint256 tokenId) internal view returns (bool) { | |
return _startTokenId() <= tokenId && tokenId < _currentIndex && | |
!_ownerships[tokenId].burned; | |
} | |
function _safeMint(address to, uint256 quantity) internal { | |
_safeMint(to, quantity, ''); | |
} | |
/** | |
* @dev Safely mints `quantity` tokens and transfers them to `to`. | |
* | |
* Requirements: | |
* | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. | |
* - `quantity` must be greater than 0. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _safeMint( | |
address to, | |
uint256 quantity, | |
bytes memory _data | |
) internal { | |
_mint(to, quantity, _data, true); | |
} | |
/** | |
* @dev Mints `quantity` tokens and transfers them to `to`. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
* - `quantity` must be greater than 0. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _mint( | |
address to, | |
uint256 quantity, | |
bytes memory _data, | |
bool safe | |
) internal { | |
uint256 startTokenId = _currentIndex; | |
if (to == address(0)) revert MintToZeroAddress(); | |
if (quantity == 0) revert MintZeroQuantity(); | |
_beforeTokenTransfers(address(0), to, startTokenId, quantity); | |
// Overflows are incredibly unrealistic. | |
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 | |
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 | |
unchecked { | |
_addressData[to].balance += uint64(quantity); | |
_addressData[to].numberMinted += uint64(quantity); | |
_ownerships[startTokenId].addr = to; | |
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp); | |
uint256 updatedIndex = startTokenId; | |
uint256 end = updatedIndex + quantity; | |
if (safe && to.isContract()) { | |
do { | |
emit Transfer(address(0), to, updatedIndex); | |
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { | |
revert TransferToNonERC721ReceiverImplementer(); | |
} | |
} while (updatedIndex != end); | |
// Reentrancy protection | |
if (_currentIndex != startTokenId) revert(); | |
} else { | |
do { | |
emit Transfer(address(0), to, updatedIndex++); | |
} while (updatedIndex != end); | |
} | |
_currentIndex = updatedIndex; | |
} | |
_afterTokenTransfers(address(0), to, startTokenId, quantity); | |
} | |
/** | |
* @dev Transfers `tokenId` from `from` to `to`. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _transfer( | |
address from, | |
address to, | |
uint256 tokenId | |
) private { | |
TokenOwnership memory prevOwnership = _ownershipOf(tokenId); | |
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); | |
bool isApprovedOrOwner = (_msgSender() == from || | |
isApprovedForAll(from, _msgSender()) || | |
getApproved(tokenId) == _msgSender()); | |
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); | |
if (to == address(0)) revert TransferToZeroAddress(); | |
_beforeTokenTransfers(from, to, tokenId, 1); | |
// Clear approvals from the previous owner | |
_approve(address(0), tokenId, from); | |
// Underflow of the sender's balance is impossible because we check for | |
// ownership above and the recipient's balance can't realistically overflow. | |
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. | |
unchecked { | |
_addressData[from].balance -= 1; | |
_addressData[to].balance += 1; | |
TokenOwnership storage currSlot = _ownerships[tokenId]; | |
currSlot.addr = to; | |
currSlot.startTimestamp = uint64(block.timestamp); | |
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. | |
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. | |
uint256 nextTokenId = tokenId + 1; | |
TokenOwnership storage nextSlot = _ownerships[nextTokenId]; | |
if (nextSlot.addr == address(0)) { | |
// This will suffice for checking _exists(nextTokenId), | |
// as a burned slot cannot contain the zero address. | |
if (nextTokenId != _currentIndex) { | |
nextSlot.addr = from; | |
nextSlot.startTimestamp = prevOwnership.startTimestamp; | |
} | |
} | |
} | |
emit Transfer(from, to, tokenId); | |
_afterTokenTransfers(from, to, tokenId, 1); | |
} | |
/** | |
* @dev This is equivalent to _burn(tokenId, false) | |
*/ | |
function _burn(uint256 tokenId) internal virtual { | |
_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) internal virtual { | |
TokenOwnership memory prevOwnership = _ownershipOf(tokenId); | |
address from = prevOwnership.addr; | |
if (approvalCheck) { | |
bool isApprovedOrOwner = (_msgSender() == from || | |
isApprovedForAll(from, _msgSender()) || | |
getApproved(tokenId) == _msgSender()); | |
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); | |
} | |
_beforeTokenTransfers(from, address(0), tokenId, 1); | |
// Clear approvals from the previous owner | |
_approve(address(0), tokenId, from); | |
// Underflow of the sender's balance is impossible because we check for | |
// ownership above and the recipient's balance can't realistically overflow. | |
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. | |
unchecked { | |
AddressData storage addressData = _addressData[from]; | |
addressData.balance -= 1; | |
addressData.numberBurned += 1; | |
// Keep track of who burned the token, and the timestamp of burning. | |
TokenOwnership storage currSlot = _ownerships[tokenId]; | |
currSlot.addr = from; | |
currSlot.startTimestamp = uint64(block.timestamp); | |
currSlot.burned = true; | |
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. | |
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. | |
uint256 nextTokenId = tokenId + 1; | |
TokenOwnership storage nextSlot = _ownerships[nextTokenId]; | |
if (nextSlot.addr == address(0)) { | |
// This will suffice for checking _exists(nextTokenId), | |
// as a burned slot cannot contain the zero address. | |
if (nextTokenId != _currentIndex) { | |
nextSlot.addr = from; | |
nextSlot.startTimestamp = prevOwnership.startTimestamp; | |
} | |
} | |
} | |
emit Transfer(from, address(0), tokenId); | |
_afterTokenTransfers(from, address(0), tokenId, 1); | |
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. | |
unchecked { | |
_burnCounter++; | |
} | |
} | |
/** | |
* @dev Approve `to` to operate on `tokenId` | |
* | |
* Emits a {Approval} event. | |
*/ | |
function _approve( | |
address to, | |
uint256 tokenId, | |
address owner | |
) private { | |
_tokenApprovals[tokenId] = to; | |
emit Approval(owner, to, tokenId); | |
} | |
/** | |
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. | |
* | |
* @param from address representing the previous owner of the given token ID | |
* @param to target address that will receive the tokens | |
* @param tokenId uint256 ID of the token to be transferred | |
* @param _data bytes optional data to send along with the call | |
* @return bool whether the call correctly returned the expected magic value | |
*/ | |
function _checkContractOnERC721Received( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) private returns (bool) { | |
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { | |
return retval == IERC721Receiver(to).onERC721Received.selector; | |
} catch (bytes memory reason) { | |
if (reason.length == 0) { | |
revert TransferToNonERC721ReceiverImplementer(); | |
} else { | |
assembly { | |
revert(add(32, reason), mload(reason)) | |
} | |
} | |
} | |
} | |
/** | |
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. | |
* And also called before burning one token. | |
* | |
* startTokenId - the first token id to be transferred | |
* quantity - the amount to be transferred | |
* | |
* Calling conditions: | |
* | |
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be | |
* transferred to `to`. | |
* - When `from` is zero, `tokenId` will be minted for `to`. | |
* - When `to` is zero, `tokenId` will be burned by `from`. | |
* - `from` and `to` are never both zero. | |
*/ | |
function _beforeTokenTransfers( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
/** | |
* @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( | |
address from, | |
address to, | |
uint256 startTokenId, | |
uint256 quantity | |
) internal virtual {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./Interfaces/IWETH.sol"; | |
import "./OpenZeppelin/math/Math.sol"; | |
import "./OpenZeppelin/token/ERC20/ERC20.sol"; | |
import "./OpenZeppelin/token/ERC721/ERC721.sol"; | |
import "./OpenZeppelin/token/ERC721/ERC721Holder.sol"; | |
import "./Settings.sol"; | |
import "./OpenZeppelin/upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; | |
import "./OpenZeppelin/upgradeable/token/ERC20/ERC20Upgradeable.sol"; | |
contract TokenVault is ERC20Upgradeable, ERC721HolderUpgradeable { | |
using Address for address; | |
/// ----------------------------------- | |
/// -------- BASIC INFORMATION -------- | |
/// ----------------------------------- | |
/// @notice weth address | |
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; | |
/// ----------------------------------- | |
/// -------- TOKEN INFORMATION -------- | |
/// ----------------------------------- | |
/// @notice the ERC721 token address of the vault's token | |
address public token; | |
/// @notice the ERC721 token ID of the vault's token | |
uint256 public id; | |
/// ------------------------------------- | |
/// -------- AUCTION INFORMATION -------- | |
/// ------------------------------------- | |
/// @notice the unix timestamp end time of the token auction | |
uint256 public auctionEnd; | |
/// @notice the length of auctions | |
uint256 public auctionLength; | |
/// @notice reservePrice * votingTokens | |
uint256 public reserveTotal; | |
/// @notice the current price of the token during an auction | |
uint256 public livePrice; | |
/// @notice the current user winning the token auction | |
address payable public winning; | |
enum State { inactive, live, ended, redeemed } | |
State public auctionState; | |
/// ----------------------------------- | |
/// -------- VAULT INFORMATION -------- | |
/// ----------------------------------- | |
string public constant version = "1.1"; | |
/// @notice the governance contract which gets paid in ETH | |
address public immutable settings; | |
/// @notice the address who initially deposited the NFT | |
address public curator; | |
/// @notice the AUM fee paid to the curator yearly. 3 decimals. ie. 100 = 10% | |
uint256 public fee; | |
/// @notice the last timestamp where fees were claimed | |
uint256 public lastClaimed; | |
/// @notice a boolean to indicate if the vault has closed | |
bool public vaultClosed; | |
/// @notice the number of ownership tokens voting on the reserve price at any given time | |
uint256 public votingTokens; | |
/// @notice a mapping of users to their desired token price | |
mapping(address => uint256) public userPrices; | |
/// ------------------------ | |
/// -------- EVENTS -------- | |
/// ------------------------ | |
/// @notice An event emitted when a user updates their price | |
event PriceUpdate(address indexed user, uint price); | |
/// @notice An event emitted when an auction starts | |
event Start(address indexed buyer, uint price); | |
/// @notice An event emitted when a bid is made | |
event Bid(address indexed buyer, uint price); | |
/// @notice An event emitted when an auction is won | |
event Won(address indexed buyer, uint price); | |
/// @notice An event emitted when someone redeems all tokens for the NFT | |
event Redeem(address indexed redeemer); | |
/// @notice An event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale | |
event Cash(address indexed owner, uint256 shares); | |
event UpdateAuctionLength(uint256 length); | |
event UpdateCuratorFee(uint256 fee); | |
event FeeClaimed(uint256 fee); | |
constructor(address _settings) { | |
settings = _settings; | |
} | |
function initialize(address _curator, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee, string memory _name, string memory _symbol) external initializer { | |
// initialize inherited contracts | |
__ERC20_init(_name, _symbol); | |
__ERC721Holder_init(); | |
// set storage variables | |
token = _token; | |
id = _id; | |
auctionLength = 3 days; | |
curator = _curator; | |
fee = _fee; | |
lastClaimed = block.timestamp; | |
auctionState = State.inactive; | |
userPrices[_curator] = _listPrice; | |
_mint(_curator, _supply); | |
} | |
/// -------------------------------- | |
/// -------- VIEW FUNCTIONS -------- | |
/// -------------------------------- | |
function reservePrice() public view returns(uint256) { | |
return votingTokens == 0 ? 0 : reserveTotal / votingTokens; | |
} | |
/// ------------------------------- | |
/// -------- GOV FUNCTIONS -------- | |
/// ------------------------------- | |
/// @notice allow governance to boot a bad actor curator | |
/// @param _curator the new curator | |
function kickCurator(address _curator) external { | |
require(msg.sender == Ownable(settings).owner(), "kick:not gov"); | |
curator = _curator; | |
} | |
/// @notice allow governance to remove bad reserve prices | |
function removeReserve(address _user) external { | |
require(msg.sender == Ownable(settings).owner(), "remove:not gov"); | |
require(auctionState == State.inactive, "update:auction live cannot update price"); | |
uint256 old = userPrices[_user]; | |
require(0 != old, "update:not an update"); | |
uint256 weight = balanceOf(_user); | |
votingTokens -= weight; | |
reserveTotal -= weight * old; | |
userPrices[_user] = 0; | |
emit PriceUpdate(_user, 0); | |
} | |
/// ----------------------------------- | |
/// -------- CURATOR FUNCTIONS -------- | |
/// ----------------------------------- | |
/// @notice allow curator to update the curator address | |
/// @param _curator the new curator | |
function updateCurator(address _curator) external { | |
require(msg.sender == curator, "update:not curator"); | |
curator = _curator; | |
} | |
/// @notice allow curator to update the auction length | |
/// @param _length the new base price | |
function updateAuctionLength(uint256 _length) external { | |
require(msg.sender == curator, "update:not curator"); | |
require(_length >= ISettings(settings).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(), "update:invalid auction length"); | |
auctionLength = _length; | |
emit UpdateAuctionLength(_length); | |
} | |
/// @notice allow the curator to change their fee | |
/// @param _fee the new fee | |
function updateFee(uint256 _fee) external { | |
require(msg.sender == curator, "update:not curator"); | |
require(_fee < fee, "update:can't raise"); | |
require(_fee <= ISettings(settings).maxCuratorFee(), "update:cannot increase fee this high"); | |
_claimFees(); | |
fee = _fee; | |
emit UpdateCuratorFee(fee); | |
} | |
/// @notice external function to claim fees for the curator and governance | |
function claimFees() external { | |
_claimFees(); | |
} | |
/// @dev interal fuction to calculate and mint fees | |
function _claimFees() internal { | |
require(auctionState != State.ended, "claim:cannot claim after auction ends"); | |
// get how much in fees the curator would make in a year | |
uint256 currentAnnualFee = fee * totalSupply() / 1000; | |
// get how much that is per second; | |
uint256 feePerSecond = currentAnnualFee / 31536000; | |
// get how many seconds they are eligible to claim | |
uint256 sinceLastClaim = block.timestamp - lastClaimed; | |
// get the amount of tokens to mint | |
uint256 curatorMint = sinceLastClaim * feePerSecond; | |
// now lets do the same for governance | |
address govAddress = ISettings(settings).feeReceiver(); | |
uint256 govFee = ISettings(settings).governanceFee(); | |
currentAnnualFee = govFee * totalSupply() / 1000; | |
feePerSecond = currentAnnualFee / 31536000; | |
uint256 govMint = sinceLastClaim * feePerSecond; | |
lastClaimed = block.timestamp; | |
if (curator != address(0)) { | |
_mint(curator, curatorMint); | |
emit FeeClaimed(curatorMint); | |
} | |
if (govAddress != address(0)) { | |
_mint(govAddress, govMint); | |
emit FeeClaimed(govMint); | |
} | |
} | |
/// -------------------------------- | |
/// -------- CORE FUNCTIONS -------- | |
/// -------------------------------- | |
/// @notice a function for an end user to update their desired sale price | |
/// @param _new the desired price in ETH | |
function updateUserPrice(uint256 _new) external { | |
require(auctionState == State.inactive, "update:auction live cannot update price"); | |
uint256 old = userPrices[msg.sender]; | |
require(_new != old, "update:not an update"); | |
uint256 weight = balanceOf(msg.sender); | |
if (votingTokens == 0) { | |
votingTokens = weight; | |
reserveTotal = weight * _new; | |
} | |
// they are the only one voting | |
else if (weight == votingTokens && old != 0) { | |
reserveTotal = weight * _new; | |
} | |
// previously they were not voting | |
else if (old == 0) { | |
uint256 averageReserve = reserveTotal / votingTokens; | |
uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; | |
require(_new >= reservePriceMin, "update:reserve price too low"); | |
uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; | |
require(_new <= reservePriceMax, "update:reserve price too high"); | |
votingTokens += weight; | |
reserveTotal += weight * _new; | |
} | |
// they no longer want to vote | |
else if (_new == 0) { | |
votingTokens -= weight; | |
reserveTotal -= weight * old; | |
} | |
// they are updating their vote | |
else { | |
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight); | |
uint256 reservePriceMin = averageReserve * ISettings(settings).minReserveFactor() / 1000; | |
require(_new >= reservePriceMin, "update:reserve price too low"); | |
uint256 reservePriceMax = averageReserve * ISettings(settings).maxReserveFactor() / 1000; | |
require(_new <= reservePriceMax, "update:reserve price too high"); | |
reserveTotal = reserveTotal + (weight * _new) - (weight * old); | |
} | |
userPrices[msg.sender] = _new; | |
emit PriceUpdate(msg.sender, _new); | |
} | |
/// @notice an internal function used to update sender and receivers price on token transfer | |
/// @param _from the ERC20 token sender | |
/// @param _to the ERC20 token receiver | |
/// @param _amount the ERC20 token amount | |
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override { | |
if (auctionState == State.inactive) { | |
uint256 fromPrice = userPrices[_from]; | |
uint256 toPrice = userPrices[_to]; | |
// only do something if users have different reserve price | |
if (toPrice != fromPrice) { | |
// new holder is not a voter | |
if (toPrice == 0) { | |
// get the average reserve price ignoring the senders amount | |
votingTokens -= _amount; | |
reserveTotal -= _amount * fromPrice; | |
} | |
// old holder is not a voter | |
else if (fromPrice == 0) { | |
votingTokens += _amount; | |
reserveTotal += _amount * toPrice; | |
} | |
// both holders are voters | |
else { | |
reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice); | |
} | |
} | |
} | |
} | |
/// @notice kick off an auction. Must send reservePrice in ETH | |
function start() external payable { | |
require(auctionState == State.inactive, "start:no auction starts"); | |
require(msg.value >= reservePrice(), "start:too low bid"); | |
require(votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply(), "start:not enough voters"); | |
auctionEnd = block.timestamp + auctionLength; | |
auctionState = State.live; | |
livePrice = msg.value; | |
winning = payable(msg.sender); | |
emit Start(msg.sender, msg.value); | |
} | |
/// @notice an external function to bid on purchasing the vaults NFT. The msg.value is the bid amount | |
function bid() external payable { | |
require(auctionState == State.live, "bid:auction is not live"); | |
uint256 increase = ISettings(settings).minBidIncrease() + 1000; | |
require(msg.value * 1000 >= livePrice * increase, "bid:too low bid"); | |
require(block.timestamp < auctionEnd, "bid:auction ended"); | |
// If bid is within 15 minutes of auction end, extend auction | |
if (auctionEnd - block.timestamp <= 15 minutes) { | |
auctionEnd += 15 minutes; | |
} | |
_sendETHOrWETH(winning, livePrice); | |
livePrice = msg.value; | |
winning = payable(msg.sender); | |
emit Bid(msg.sender, msg.value); | |
} | |
/// @notice an external function to end an auction after the timer has run out | |
function end() external { | |
require(auctionState == State.live, "end:vault has already closed"); | |
require(block.timestamp >= auctionEnd, "end:auction live"); | |
_claimFees(); | |
// transfer erc721 to winner | |
IERC721(token).transferFrom(address(this), winning, id); | |
auctionState = State.ended; | |
emit Won(winning, livePrice); | |
} | |
/// @notice an external function to burn all ERC20 tokens to receive the ERC721 token | |
function redeem() external { | |
require(auctionState == State.inactive, "redeem:no redeeming"); | |
_burn(msg.sender, totalSupply()); | |
// transfer erc721 to redeemer | |
IERC721(token).transferFrom(address(this), msg.sender, id); | |
auctionState = State.redeemed; | |
emit Redeem(msg.sender); | |
} | |
/// @notice an external function to burn ERC20 tokens to receive ETH from ERC721 token purchase | |
function cash() external { | |
require(auctionState == State.ended, "cash:vault not closed yet"); | |
uint256 bal = balanceOf(msg.sender); | |
require(bal > 0, "cash:no tokens to cash out"); | |
uint256 share = bal * address(this).balance / totalSupply(); | |
_burn(msg.sender, bal); | |
_sendETHOrWETH(payable(msg.sender), share); | |
emit Cash(msg.sender, share); | |
} | |
// Will attempt to transfer ETH, but will transfer WETH instead if it fails. | |
function _sendETHOrWETH(address to, uint256 value) internal { | |
// Try to transfer ETH to the given recipient. | |
if (!_attemptETHTransfer(to, value)) { | |
// If the transfer fails, wrap and send as WETH, so that | |
// the auction is not impeded and the recipient still | |
// can claim ETH via the WETH contract (similar to escrow). | |
IWETH(weth).deposit{value: value}(); | |
IWETH(weth).transfer(to, value); | |
// At this point, the recipient can unwrap WETH. | |
} | |
} | |
// Sending ETH is not guaranteed complete, and the method used here will return false if | |
// it fails. For example, a contract can block ETH transfer, or might use | |
// an excessive amount of gas, thereby griefing a new bidder. | |
// We should limit the gas used in transfers, and handle failure cases. | |
function _attemptETHTransfer(address to, uint256 value) | |
internal | |
returns (bool) | |
{ | |
// Here increase the gas limit a reasonable amount above the default, and try | |
// to send ETH to the recipient. | |
// NOTE: This might allow the recipient to attempt a limited reentrancy attack. | |
(bool success, ) = to.call{value: value, gas: 30000}(""); | |
return success; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
interface ISettings { | |
function maxAuctionLength() external returns(uint256); | |
function minAuctionLength() external returns(uint256); | |
function maxCuratorFee() external returns(uint256); | |
function governanceFee() external returns(uint256); | |
function minBidIncrease() external returns(uint256); | |
function minVotePercentage() external returns(uint256); | |
function maxReserveFactor() external returns(uint256); | |
function minReserveFactor() external returns(uint256); | |
function feeReceiver() external returns(address payable); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
interface IWETH { | |
function deposit() external payable; | |
function withdraw(uint) external; | |
function approve(address, uint) external returns(bool); | |
function transfer(address, uint) external returns(bool); | |
function transferFrom(address, address, uint) external returns(bool); | |
function balanceOf(address) external view returns(uint); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
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 () { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view virtual returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(owner() == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = 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"); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./IERC165.sol"; | |
/** | |
* @dev Implementation of the {IERC165} interface. | |
* | |
* Contracts may inherit from this and call {_registerInterface} to declare | |
* their support of an interface. | |
*/ | |
abstract contract ERC165 is IERC165 { | |
/** | |
* @dev Mapping of interface ids to whether or not it's supported. | |
*/ | |
mapping(bytes4 => bool) private _supportedInterfaces; | |
constructor () { | |
// Derived contracts need only register support for their own interfaces, | |
// we register support for ERC165 itself here | |
_registerInterface(type(IERC165).interfaceId); | |
} | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
* | |
* Time complexity O(1), guaranteed to always use less than 30 000 gas. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return _supportedInterfaces[interfaceId]; | |
} | |
/** | |
* @dev Registers the contract as an implementer of the interface defined by | |
* `interfaceId`. Support of the actual ERC165 interface is automatic and | |
* registering its interface id is not required. | |
* | |
* See {IERC165-supportsInterface}. | |
* | |
* Requirements: | |
* | |
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). | |
*/ | |
function _registerInterface(bytes4 interfaceId) internal virtual { | |
require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); | |
_supportedInterfaces[interfaceId] = true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Standard math utilities missing in the Solidity language. | |
*/ | |
library Math { | |
/** | |
* @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, so we distribute | |
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../../utils/Context.sol"; | |
import "./IERC20.sol"; | |
/** | |
* @dev Implementation of the {IERC20} interface. | |
* | |
* This implementation is agnostic to the way tokens are created. This means | |
* that a supply mechanism has to be added in a derived contract using {_mint}. | |
* For a generic mechanism see {ERC20PresetMinterPauser}. | |
* | |
* TIP: For a detailed writeup see our guide | |
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How | |
* to implement supply mechanisms]. | |
* | |
* We have followed general OpenZeppelin guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of ERC20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IERC20-approve}. | |
*/ | |
contract ERC20 is Context, IERC20 { | |
mapping (address => uint256) private _balances; | |
mapping (address => mapping (address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
/** | |
* @dev Sets the values for {name} and {symbol}. | |
* | |
* The defaut value of {decimals} is 18. To select a different value for | |
* {decimals} you should overload it. | |
* | |
* All three of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
constructor (string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() public view virtual returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the symbol of the token, usually a shorter version of the | |
* name. | |
*/ | |
function symbol() public view virtual returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the number of decimals used to get its user representation. | |
* For example, if `decimals` equals `2`, a balance of `505` tokens should | |
* be displayed to a user as `5,05` (`505 / 10 ** 2`). | |
* | |
* Tokens usually opt for a value of 18, imitating the relationship between | |
* Ether and Wei. This is the value {ERC20} uses, unless this function is | |
* overloaded; | |
* | |
* NOTE: This information is only used for _display_ purposes: it in | |
* no way affects any of the arithmetic of the contract, including | |
* {IERC20-balanceOf} and {IERC20-transfer}. | |
*/ | |
function decimals() public view virtual returns (uint8) { | |
return 18; | |
} | |
/** | |
* @dev See {IERC20-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {IERC20-balanceOf}. | |
*/ | |
function balanceOf(address account) public view virtual override returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {IERC20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public view virtual override returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {IERC20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public virtual override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {ERC20}. | |
* | |
* Requirements: | |
* | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for ``sender``'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(sender, recipient, amount); | |
uint256 currentAllowance = _allowances[sender][_msgSender()]; | |
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); | |
_approve(sender, _msgSender(), currentAllowance - amount); | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { | |
uint256 currentAllowance = _allowances[_msgSender()][spender]; | |
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); | |
_approve(_msgSender(), spender, currentAllowance - subtractedValue); | |
return true; | |
} | |
/** | |
* @dev Moves tokens `amount` from `sender` to `recipient`. | |
* | |
* This is internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer(address sender, address recipient, uint256 amount) internal virtual { | |
require(sender != address(0), "ERC20: transfer from the zero address"); | |
require(recipient != address(0), "ERC20: transfer to the zero address"); | |
_beforeTokenTransfer(sender, recipient, amount); | |
uint256 senderBalance = _balances[sender]; | |
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); | |
_balances[sender] = senderBalance - amount; | |
_balances[recipient] += amount; | |
emit Transfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal virtual { | |
require(account != address(0), "ERC20: mint to the zero address"); | |
_beforeTokenTransfer(address(0), account, amount); | |
_totalSupply += amount; | |
_balances[account] += amount; | |
emit Transfer(address(0), account, amount); | |
} | |
/** | |
* @dev Destroys `amount` tokens from `account`, reducing the | |
* total supply. | |
* | |
* Emits a {Transfer} event with `to` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `account` cannot be the zero address. | |
* - `account` must have at least `amount` tokens. | |
*/ | |
function _burn(address account, uint256 amount) internal virtual { | |
require(account != address(0), "ERC20: burn from the zero address"); | |
_beforeTokenTransfer(account, address(0), amount); | |
uint256 accountBalance = _balances[account]; | |
require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); | |
_balances[account] = accountBalance - amount; | |
_totalSupply -= amount; | |
emit Transfer(account, address(0), amount); | |
} | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. | |
* | |
* This internal function is equivalent to `approve`, and can be used to | |
* e.g. set automatic allowances for certain subsystems, etc. | |
* | |
* Emits an {Approval} event. | |
* | |
* Requirements: | |
* | |
* - `owner` cannot be the zero address. | |
* - `spender` cannot be the zero address. | |
*/ | |
function _approve(address owner, address spender, uint256 amount) internal virtual { | |
require(owner != address(0), "ERC20: approve from the zero address"); | |
require(spender != address(0), "ERC20: approve to the zero address"); | |
_allowances[owner][spender] = amount; | |
emit Approval(owner, spender, amount); | |
} | |
/** | |
* @dev Hook that is called before any transfer of tokens. This includes | |
* minting and burning. | |
* | |
* Calling conditions: | |
* | |
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens | |
* will be to transferred to `to`. | |
* - when `from` is zero, `amount` tokens will be minted for `to`. | |
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount) internal virtual { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Interface of the ERC20 standard as defined in the EIP. | |
*/ | |
interface IERC20 { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../../utils/Context.sol"; | |
import "./IERC721.sol"; | |
import "./IERC721Metadata.sol"; | |
import "./IERC721Enumerable.sol"; | |
import "./IERC721Receiver.sol"; | |
import "../../introspection/ERC165.sol"; | |
import "../../utils/Address.sol"; | |
import "../../utils/EnumerableSet.sol"; | |
import "../../utils/EnumerableMap.sol"; | |
import "../../utils/Strings.sol"; | |
/** | |
* @title ERC721 Non-Fungible Token Standard basic implementation | |
* @dev see https://eips.ethereum.org/EIPS/eip-721 | |
*/ | |
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { | |
using Address for address; | |
using EnumerableSet for EnumerableSet.UintSet; | |
using EnumerableMap for EnumerableMap.UintToAddressMap; | |
using Strings for uint256; | |
// Mapping from holder address to their (enumerable) set of owned tokens | |
mapping (address => EnumerableSet.UintSet) private _holderTokens; | |
// Enumerable mapping from token ids to their owners | |
EnumerableMap.UintToAddressMap private _tokenOwners; | |
// 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; | |
// Token name | |
string private _name; | |
// Token symbol | |
string private _symbol; | |
// Optional mapping for token URIs | |
mapping (uint256 => string) private _tokenURIs; | |
// Base URI | |
string private _baseURI; | |
/** | |
* @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_; | |
// register the supported interfaces to conform to ERC721 via ERC165 | |
_registerInterface(type(IERC721).interfaceId); | |
_registerInterface(type(IERC721Metadata).interfaceId); | |
_registerInterface(type(IERC721Enumerable).interfaceId); | |
} | |
/** | |
* @dev See {IERC721-balanceOf}. | |
*/ | |
function balanceOf(address owner) public view virtual override returns (uint256) { | |
require(owner != address(0), "ERC721: balance query for the zero address"); | |
return _holderTokens[owner].length(); | |
} | |
/** | |
* @dev See {IERC721-ownerOf}. | |
*/ | |
function ownerOf(uint256 tokenId) public view virtual override returns (address) { | |
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); | |
} | |
/** | |
* @dev See {IERC721Metadata-name}. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev See {IERC721Metadata-symbol}. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev See {IERC721Metadata-tokenURI}. | |
*/ | |
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { | |
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); | |
string memory _tokenURI = _tokenURIs[tokenId]; | |
string memory base = baseURI(); | |
// If there is no base URI, return the token URI. | |
if (bytes(base).length == 0) { | |
return _tokenURI; | |
} | |
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). | |
if (bytes(_tokenURI).length > 0) { | |
return string(abi.encodePacked(base, _tokenURI)); | |
} | |
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. | |
return string(abi.encodePacked(base, tokenId.toString())); | |
} | |
/** | |
* @dev Returns the base URI set via {_setBaseURI}. This will be | |
* automatically added as a prefix in {tokenURI} to each token's URI, or | |
* to the token ID if no specific URI is set for that token ID. | |
*/ | |
function baseURI() public view virtual returns (string memory) { | |
return _baseURI; | |
} | |
/** | |
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. | |
*/ | |
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { | |
return _holderTokens[owner].at(index); | |
} | |
/** | |
* @dev See {IERC721Enumerable-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds | |
return _tokenOwners.length(); | |
} | |
/** | |
* @dev See {IERC721Enumerable-tokenByIndex}. | |
*/ | |
function tokenByIndex(uint256 index) public view virtual override returns (uint256) { | |
(uint256 tokenId, ) = _tokenOwners.at(index); | |
return tokenId; | |
} | |
/** | |
* @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 || ERC721.isApprovedForAll(owner, _msgSender()), | |
"ERC721: approve caller is not owner nor approved for all" | |
); | |
_approve(to, tokenId); | |
} | |
/** | |
* @dev See {IERC721-getApproved}. | |
*/ | |
function getApproved(uint256 tokenId) public view virtual override returns (address) { | |
require(_exists(tokenId), "ERC721: approved query for nonexistent token"); | |
return _tokenApprovals[tokenId]; | |
} | |
/** | |
* @dev See {IERC721-setApprovalForAll}. | |
*/ | |
function setApprovalForAll(address operator, bool approved) public virtual override { | |
require(operator != _msgSender(), "ERC721: approve to caller"); | |
_operatorApprovals[_msgSender()][operator] = approved; | |
emit ApprovalForAll(_msgSender(), operator, approved); | |
} | |
/** | |
* @dev See {IERC721-isApprovedForAll}. | |
*/ | |
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { | |
return _operatorApprovals[owner][operator]; | |
} | |
/** | |
* @dev See {IERC721-transferFrom}. | |
*/ | |
function transferFrom(address from, address to, uint256 tokenId) public virtual override { | |
//solhint-disable-next-line max-line-length | |
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); | |
_transfer(from, to, tokenId); | |
} | |
/** | |
* @dev See {IERC721-safeTransferFrom}. | |
*/ | |
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { | |
safeTransferFrom(from, to, tokenId, ""); | |
} | |
/** | |
* @dev See {IERC721-safeTransferFrom}. | |
*/ | |
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { | |
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); | |
_safeTransfer(from, to, tokenId, _data); | |
} | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients | |
* are aware of the ERC721 protocol to prevent tokens from being forever locked. | |
* | |
* `_data` is additional data, it has no specified format and it is sent in call to `to`. | |
* | |
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. | |
* implement alternative mechanisms to perform token transfer, such as signature-based. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { | |
_transfer(from, to, tokenId); | |
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); | |
} | |
/** | |
* @dev Returns whether `tokenId` exists. | |
* | |
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. | |
* | |
* Tokens start existing when they are minted (`_mint`), | |
* and stop existing when they are burned (`_burn`). | |
*/ | |
function _exists(uint256 tokenId) internal view virtual returns (bool) { | |
return _tokenOwners.contains(tokenId); | |
} | |
/** | |
* @dev Returns whether `spender` is allowed to manage `tokenId`. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { | |
require(_exists(tokenId), "ERC721: operator query for nonexistent token"); | |
address owner = ERC721.ownerOf(tokenId); | |
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); | |
} | |
/** | |
* @dev Safely mints `tokenId` and transfers it to `to`. | |
* | |
* Requirements: | |
d* | |
* - `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); | |
_holderTokens[to].add(tokenId); | |
_tokenOwners.set(tokenId, to); | |
emit Transfer(address(0), to, tokenId); | |
} | |
/** | |
* @dev Destroys `tokenId`. | |
* The approval is cleared when the token is burned. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _burn(uint256 tokenId) internal virtual { | |
address owner = ERC721.ownerOf(tokenId); // internal owner | |
_beforeTokenTransfer(owner, address(0), tokenId); | |
// Clear approvals | |
_approve(address(0), tokenId); | |
// Clear metadata (if any) | |
if (bytes(_tokenURIs[tokenId]).length != 0) { | |
delete _tokenURIs[tokenId]; | |
} | |
_holderTokens[owner].remove(tokenId); | |
_tokenOwners.remove(tokenId); | |
emit Transfer(owner, address(0), tokenId); | |
} | |
/** | |
* @dev Transfers `tokenId` from `from` to `to`. | |
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _transfer(address from, address to, uint256 tokenId) internal virtual { | |
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal 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); | |
_holderTokens[from].remove(tokenId); | |
_holderTokens[to].add(tokenId); | |
_tokenOwners.set(tokenId, to); | |
emit Transfer(from, to, tokenId); | |
} | |
/** | |
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { | |
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); | |
_tokenURIs[tokenId] = _tokenURI; | |
} | |
/** | |
* @dev Internal function to set the base URI for all token IDs. It is | |
* automatically added as a prefix to the value returned in {tokenURI}, | |
* or to the token ID if {tokenURI} is empty. | |
*/ | |
function _setBaseURI(string memory baseURI_) internal virtual { | |
_baseURI = baseURI_; | |
} | |
/** | |
* @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(to).onERC721Received.selector; | |
} catch (bytes memory reason) { | |
if (reason.length == 0) { | |
revert("ERC721: transfer to non ERC721Receiver implementer"); | |
} else { | |
// solhint-disable-next-line no-inline-assembly | |
assembly { | |
revert(add(32, reason), mload(reason)) | |
} | |
} | |
} | |
} else { | |
return true; | |
} | |
} | |
function _approve(address to, uint256 tokenId) private { | |
_tokenApprovals[tokenId] = to; | |
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner | |
} | |
/** | |
* @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` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* | |
* 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 { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./IERC721Receiver.sol"; | |
/** | |
* @dev Implementation of the {IERC721Receiver} interface. | |
* | |
* Accepts all token transfers. | |
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. | |
*/ | |
contract ERC721Holder is IERC721Receiver { | |
/** | |
* @dev See {IERC721Receiver-onERC721Received}. | |
* | |
* Always returns `IERC721Receiver.onERC721Received.selector`. | |
*/ | |
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { | |
return this.onERC721Received.selector; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../../introspection/IERC165.sol"; | |
/** | |
* @dev Required interface of an ERC721 compliant contract. | |
*/ | |
interface IERC721 is IERC165 { | |
/** | |
* @dev Emitted when `tokenId` token is transferred from `from` to `to`. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. | |
*/ | |
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. | |
*/ | |
event ApprovalForAll(address indexed owner, address indexed operator, bool approved); | |
/** | |
* @dev Returns the number of tokens in ``owner``'s account. | |
*/ | |
function balanceOf(address owner) external view returns (uint256 balance); | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) external view returns (address owner); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients | |
* are aware of the ERC721 protocol to prevent tokens from being forever locked. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom(address from, address to, uint256 tokenId) external; | |
/** | |
* @dev Transfers `tokenId` token from `from` to `to`. | |
* | |
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom(address from, address to, uint256 tokenId) external; | |
/** | |
* @dev Gives permission to `to` to transfer `tokenId` token to another account. | |
* The approval is cleared when the token is transferred. | |
* | |
* Only a single account can be approved at a time, so approving the zero address clears previous approvals. | |
* | |
* Requirements: | |
* | |
* - The caller must own the token or be an approved operator. | |
* - `tokenId` must exist. | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address to, uint256 tokenId) external; | |
/** | |
* @dev Returns the account approved for `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function getApproved(uint256 tokenId) external view returns (address operator); | |
/** | |
* @dev Approve or remove `operator` as an operator for the caller. | |
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. | |
* | |
* Requirements: | |
* | |
* - The `operator` cannot be the caller. | |
* | |
* Emits an {ApprovalForAll} event. | |
*/ | |
function setApprovalForAll(address operator, bool _approved) external; | |
/** | |
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. | |
* | |
* See {setApprovalForAll} | |
*/ | |
function isApprovedForAll(address owner, address operator) external view returns (bool); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./IERC721.sol"; | |
/** | |
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension | |
* @dev See https://eips.ethereum.org/EIPS/eip-721 | |
*/ | |
interface IERC721Enumerable is IERC721 { | |
/** | |
* @dev Returns the total amount of tokens stored by the contract. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns a token ID owned by `owner` at a given `index` of its token list. | |
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens. | |
*/ | |
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); | |
/** | |
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract. | |
* Use along with {totalSupply} to enumerate all tokens. | |
*/ | |
function tokenByIndex(uint256 index) external view returns (uint256); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC721 token receiver interface | |
* @dev Interface for any contract that wants to support safeTransfers | |
* from ERC721 asset contracts. | |
*/ | |
interface IERC721Receiver { | |
/** | |
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} | |
* by `operator` from `from`, this function is called. | |
* | |
* It must return its Solidity selector to confirm the token transfer. | |
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. | |
* | |
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. | |
*/ | |
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed | |
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an | |
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer | |
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. | |
* | |
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as | |
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. | |
* | |
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure | |
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. | |
*/ | |
abstract contract Initializable { | |
/** | |
* @dev Indicates that the contract has been initialized. | |
*/ | |
bool private _initialized; | |
/** | |
* @dev Indicates that the contract is in the process of being initialized. | |
*/ | |
bool private _initializing; | |
/** | |
* @dev Modifier to protect an initializer function from being invoked twice. | |
*/ | |
modifier initializer() { | |
require(_initializing || !_initialized, "Initializable: contract is already initialized"); | |
bool isTopLevelCall = !_initializing; | |
if (isTopLevelCall) { | |
_initializing = true; | |
_initialized = true; | |
} | |
_; | |
if (isTopLevelCall) { | |
_initializing = false; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./IERC20Upgradeable.sol"; | |
import "./extensions/IERC20MetadataUpgradeable.sol"; | |
import "../../utils/ContextUpgradeable.sol"; | |
import "../../proxy/utils/Initializable.sol"; | |
/** | |
* @dev Implementation of the {IERC20} interface. | |
* | |
* This implementation is agnostic to the way tokens are created. This means | |
* that a supply mechanism has to be added in a derived contract using {_mint}. | |
* For a generic mechanism see {ERC20PresetMinterPauser}. | |
* | |
* TIP: For a detailed writeup see our guide | |
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How | |
* to implement supply mechanisms]. | |
* | |
* We have followed general OpenZeppelin guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of ERC20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IERC20-approve}. | |
*/ | |
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { | |
mapping(address => uint256) private _balances; | |
mapping(address => mapping(address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
/** | |
* @dev Sets the values for {name} and {symbol}. | |
* | |
* The default value of {decimals} is 18. To select a different value for | |
* {decimals} you should overload it. | |
* | |
* All two of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
function __ERC20_init(string memory name_, string memory symbol_) internal initializer { | |
__Context_init_unchained(); | |
__ERC20_init_unchained(name_, symbol_); | |
} | |
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the symbol of the token, usually a shorter version of the | |
* name. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev Returns the number of decimals used to get its user representation. | |
* For example, if `decimals` equals `2`, a balance of `505` tokens should | |
* be displayed to a user as `5,05` (`505 / 10 ** 2`). | |
* | |
* Tokens usually opt for a value of 18, imitating the relationship between | |
* Ether and Wei. This is the value {ERC20} uses, unless this function is | |
* overridden; | |
* | |
* NOTE: This information is only used for _display_ purposes: it in | |
* no way affects any of the arithmetic of the contract, including | |
* {IERC20-balanceOf} and {IERC20-transfer}. | |
*/ | |
function decimals() public view virtual override returns (uint8) { | |
return 18; | |
} | |
/** | |
* @dev See {IERC20-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {IERC20-balanceOf}. | |
*/ | |
function balanceOf(address account) public view virtual override returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {IERC20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public view virtual override returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {IERC20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public virtual override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {IERC20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {ERC20}. | |
* | |
* Requirements: | |
* | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for ``sender``'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) public virtual override returns (bool) { | |
_transfer(sender, recipient, amount); | |
uint256 currentAllowance = _allowances[sender][_msgSender()]; | |
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); | |
unchecked { | |
_approve(sender, _msgSender(), currentAllowance - amount); | |
} | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {IERC20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { | |
uint256 currentAllowance = _allowances[_msgSender()][spender]; | |
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); | |
unchecked { | |
_approve(_msgSender(), spender, currentAllowance - subtractedValue); | |
} | |
return true; | |
} | |
/** | |
* @dev Moves `amount` of tokens from `sender` to `recipient`. | |
* | |
* This internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer( | |
address sender, | |
address recipient, | |
uint256 amount | |
) internal virtual { | |
require(sender != address(0), "ERC20: transfer from the zero address"); | |
require(recipient != address(0), "ERC20: transfer to the zero address"); | |
_beforeTokenTransfer(sender, recipient, amount); | |
uint256 senderBalance = _balances[sender]; | |
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); | |
unchecked { | |
_balances[sender] = senderBalance - amount; | |
} | |
_balances[recipient] += amount; | |
emit Transfer(sender, recipient, amount); | |
_afterTokenTransfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `account` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal virtual { | |
require(account != address(0), "ERC20: mint to the zero address"); | |
_beforeTokenTransfer(address(0), account, amount); | |
_totalSupply += amount; | |
_balances[account] += amount; | |
emit Transfer(address(0), account, amount); | |
_afterTokenTransfer(address(0), account, amount); | |
} | |
/** | |
* @dev Destroys `amount` tokens from `account`, reducing the | |
* total supply. | |
* | |
* Emits a {Transfer} event with `to` set to the zero address. | |
* | |
* Requirements: | |
* | |
* - `account` cannot be the zero address. | |
* - `account` must have at least `amount` tokens. | |
*/ | |
function _burn(address account, uint256 amount) internal virtual { | |
require(account != address(0), "ERC20: burn from the zero address"); | |
_beforeTokenTransfer(account, address(0), amount); | |
uint256 accountBalance = _balances[account]; | |
require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); | |
unchecked { | |
_balances[account] = accountBalance - amount; | |
} | |
_totalSupply -= amount; | |
emit Transfer(account, address(0), amount); | |
_afterTokenTransfer(account, address(0), amount); | |
} | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. | |
* | |
* This internal function is equivalent to `approve`, and can be used to | |
* e.g. set automatic allowances for certain subsystems, etc. | |
* | |
* Emits an {Approval} event. | |
* | |
* Requirements: | |
* | |
* - `owner` cannot be the zero address. | |
* - `spender` cannot be the zero address. | |
*/ | |
function _approve( | |
address owner, | |
address spender, | |
uint256 amount | |
) internal virtual { | |
require(owner != address(0), "ERC20: approve from the zero address"); | |
require(spender != address(0), "ERC20: approve to the zero address"); | |
_allowances[owner][spender] = amount; | |
emit Approval(owner, spender, amount); | |
} | |
/** | |
* @dev Hook that is called before any transfer of tokens. This includes | |
* minting and burning. | |
* | |
* Calling conditions: | |
* | |
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens | |
* will be transferred to `to`. | |
* - when `from` is zero, `amount` tokens will be minted for `to`. | |
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount | |
) 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, `amount` of ``from``'s tokens | |
* has been transferred to `to`. | |
* - when `from` is zero, `amount` tokens have been minted for `to`. | |
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( | |
address from, | |
address to, | |
uint256 amount | |
) internal virtual {} | |
uint256[45] private __gap; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../IERC20Upgradeable.sol"; | |
/** | |
* @dev Interface for the optional metadata functions from the ERC20 standard. | |
* | |
* _Available since v4.1._ | |
*/ | |
interface IERC20MetadataUpgradeable is IERC20Upgradeable { | |
/** | |
* @dev Returns the name of the token. | |
*/ | |
function name() external view returns (string memory); | |
/** | |
* @dev Returns the symbol of the token. | |
*/ | |
function symbol() external view returns (string memory); | |
/** | |
* @dev Returns the decimals places of the token. | |
*/ | |
function decimals() external view returns (uint8); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Interface of the ERC20 standard as defined in the EIP. | |
*/ | |
interface IERC20Upgradeable { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
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 IERC721ReceiverUpgradeable { | |
/** | |
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} | |
* by `operator` from `from`, this function is called. | |
* | |
* It must return its Solidity selector to confirm the token transfer. | |
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. | |
* | |
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. | |
*/ | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (bytes4); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../IERC721ReceiverUpgradeable.sol"; | |
import "../../../proxy/utils/Initializable.sol"; | |
/** | |
* @dev Implementation of the {IERC721Receiver} interface. | |
* | |
* Accepts all token transfers. | |
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. | |
*/ | |
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { | |
function __ERC721Holder_init() internal initializer { | |
__ERC721Holder_init_unchained(); | |
} | |
function __ERC721Holder_init_unchained() internal initializer { | |
} | |
/** | |
* @dev See {IERC721Receiver-onERC721Received}. | |
* | |
* Always returns `IERC721Receiver.onERC721Received.selector`. | |
*/ | |
function onERC721Received( | |
address, | |
address, | |
uint256, | |
bytes memory | |
) public virtual override returns (bytes4) { | |
return this.onERC721Received.selector; | |
} | |
uint256[50] private __gap; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "../proxy/utils/Initializable.sol"; | |
/* | |
* @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 ContextUpgradeable is Initializable { | |
function __Context_init() internal initializer { | |
__Context_init_unchained(); | |
} | |
function __Context_init_unchained() internal initializer { | |
} | |
function _msgSender() internal view virtual returns (address) { | |
return msg.sender; | |
} | |
function _msgData() internal view virtual returns (bytes calldata) { | |
return msg.data; | |
} | |
uint256[50] private __gap; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Collection of functions related to the address type | |
*/ | |
library Address { | |
/** | |
* @dev Returns true if `account` is a contract. | |
* | |
* [IMPORTANT] | |
* ==== | |
* It is unsafe to assume that an address for which this function returns | |
* false is an externally-owned account (EOA) and not a contract. | |
* | |
* Among others, `isContract` will return false for the following | |
* types of addresses: | |
* | |
* - an externally-owned account | |
* - a contract in construction | |
* - an address where a contract will be created | |
* - an address where a contract lived, but was destroyed | |
* ==== | |
*/ | |
function isContract(address account) internal view returns (bool) { | |
// This method relies on extcodesize, which returns 0 for contracts in | |
// construction, since the code is only stored at the end of the | |
// constructor execution. | |
uint256 size; | |
// solhint-disable-next-line no-inline-assembly | |
assembly { size := extcodesize(account) } | |
return size > 0; | |
} | |
/** | |
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to | |
* `recipient`, forwarding all available gas and reverting on errors. | |
* | |
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost | |
* of certain opcodes, possibly making contracts go over the 2300 gas limit | |
* imposed by `transfer`, making them unable to receive funds via | |
* `transfer`. {sendValue} removes this limitation. | |
* | |
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. | |
* | |
* IMPORTANT: because control is transferred to `recipient`, care must be | |
* taken to not create reentrancy vulnerabilities. Consider using | |
* {ReentrancyGuard} or the | |
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. | |
*/ | |
function sendValue(address payable recipient, uint256 amount) internal { | |
require(address(this).balance >= amount, "Address: insufficient balance"); | |
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value | |
(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"); | |
// solhint-disable-next-line avoid-low-level-calls | |
(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"); | |
// solhint-disable-next-line avoid-low-level-calls | |
(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"); | |
// solhint-disable-next-line avoid-low-level-calls | |
(bool success, bytes memory returndata) = target.delegatecall(data); | |
return _verifyCallResult(success, returndata, errorMessage); | |
} | |
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 | |
// solhint-disable-next-line no-inline-assembly | |
assembly { | |
let returndata_size := mload(returndata) | |
revert(add(32, returndata), returndata_size) | |
} | |
} else { | |
revert(errorMessage); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
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 GSN 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) { | |
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 | |
return msg.data; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing an enumerable variant of Solidity's | |
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] | |
* type. | |
* | |
* Maps have the following properties: | |
* | |
* - Entries are added, removed, and checked for existence in constant time | |
* (O(1)). | |
* - Entries are enumerated in O(n). No guarantees are made on the ordering. | |
* | |
* ``` | |
* contract Example { | |
* // Add the library methods | |
* using EnumerableMap for EnumerableMap.UintToAddressMap; | |
* | |
* // Declare a set state variable | |
* EnumerableMap.UintToAddressMap private myMap; | |
* } | |
* ``` | |
* | |
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are | |
* supported. | |
*/ | |
library EnumerableMap { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Map type with | |
// bytes32 keys and values. | |
// The Map implementation uses private functions, and user-facing | |
// implementations (such as Uint256ToAddressMap) are just wrappers around | |
// the underlying Map. | |
// This means that we can only create new EnumerableMaps for types that fit | |
// in bytes32. | |
struct MapEntry { | |
bytes32 _key; | |
bytes32 _value; | |
} | |
struct Map { | |
// Storage of map keys and values | |
MapEntry[] _entries; | |
// Position of the entry defined by a key in the `entries` array, plus 1 | |
// because index 0 means a key is not in the map. | |
mapping (bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Adds a key-value pair to a map, or updates the value for an existing | |
* key. O(1). | |
* | |
* Returns true if the key was added to the map, that is if it was not | |
* already present. | |
*/ | |
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { | |
// We read and store the key's index to prevent multiple reads from the same storage slot | |
uint256 keyIndex = map._indexes[key]; | |
if (keyIndex == 0) { // Equivalent to !contains(map, key) | |
map._entries.push(MapEntry({ _key: key, _value: value })); | |
// The entry is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
map._indexes[key] = map._entries.length; | |
return true; | |
} else { | |
map._entries[keyIndex - 1]._value = value; | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a key-value pair from a map. O(1). | |
* | |
* Returns true if the key was removed from the map, that is if it was present. | |
*/ | |
function _remove(Map storage map, bytes32 key) private returns (bool) { | |
// We read and store the key's index to prevent multiple reads from the same storage slot | |
uint256 keyIndex = map._indexes[key]; | |
if (keyIndex != 0) { // Equivalent to contains(map, key) | |
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one | |
// in the array, and then remove the last entry (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = keyIndex - 1; | |
uint256 lastIndex = map._entries.length - 1; | |
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
MapEntry storage lastEntry = map._entries[lastIndex]; | |
// Move the last entry to the index where the entry to delete is | |
map._entries[toDeleteIndex] = lastEntry; | |
// Update the index for the moved entry | |
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved entry was stored | |
map._entries.pop(); | |
// Delete the index for the deleted slot | |
delete map._indexes[key]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the key is in the map. O(1). | |
*/ | |
function _contains(Map storage map, bytes32 key) private view returns (bool) { | |
return map._indexes[key] != 0; | |
} | |
/** | |
* @dev Returns the number of key-value pairs in the map. O(1). | |
*/ | |
function _length(Map storage map) private view returns (uint256) { | |
return map._entries.length; | |
} | |
/** | |
* @dev Returns the key-value pair stored at position `index` in the map. O(1). | |
* | |
* Note that there are no guarantees on the ordering of entries inside the | |
* array, and it may change when more entries are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { | |
require(map._entries.length > index, "EnumerableMap: index out of bounds"); | |
MapEntry storage entry = map._entries[index]; | |
return (entry._key, entry._value); | |
} | |
/** | |
* @dev Tries to returns the value associated with `key`. O(1). | |
* Does not revert if `key` is not in the map. | |
*/ | |
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { | |
uint256 keyIndex = map._indexes[key]; | |
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) | |
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based | |
} | |
/** | |
* @dev Returns the value associated with `key`. O(1). | |
* | |
* Requirements: | |
* | |
* - `key` must be in the map. | |
*/ | |
function _get(Map storage map, bytes32 key) private view returns (bytes32) { | |
uint256 keyIndex = map._indexes[key]; | |
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) | |
return map._entries[keyIndex - 1]._value; // All indexes are 1-based | |
} | |
/** | |
* @dev Same as {_get}, with a custom error message when `key` is not in the map. | |
* | |
* CAUTION: This function is deprecated because it requires allocating memory for the error | |
* message unnecessarily. For custom revert reasons use {_tryGet}. | |
*/ | |
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { | |
uint256 keyIndex = map._indexes[key]; | |
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) | |
return map._entries[keyIndex - 1]._value; // All indexes are 1-based | |
} | |
// UintToAddressMap | |
struct UintToAddressMap { | |
Map _inner; | |
} | |
/** | |
* @dev Adds a key-value pair to a map, or updates the value for an existing | |
* key. O(1). | |
* | |
* Returns true if the key was added to the map, that is if it was not | |
* already present. | |
*/ | |
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { | |
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the key was removed from the map, that is if it was present. | |
*/ | |
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { | |
return _remove(map._inner, bytes32(key)); | |
} | |
/** | |
* @dev Returns true if the key is in the map. O(1). | |
*/ | |
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { | |
return _contains(map._inner, bytes32(key)); | |
} | |
/** | |
* @dev Returns the number of elements in the map. O(1). | |
*/ | |
function length(UintToAddressMap storage map) internal view returns (uint256) { | |
return _length(map._inner); | |
} | |
/** | |
* @dev Returns the element stored at position `index` in the set. O(1). | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { | |
(bytes32 key, bytes32 value) = _at(map._inner, index); | |
return (uint256(key), address(uint160(uint256(value)))); | |
} | |
/** | |
* @dev Tries to returns the value associated with `key`. O(1). | |
* Does not revert if `key` is not in the map. | |
* | |
* _Available since v3.4._ | |
*/ | |
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { | |
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); | |
return (success, address(uint160(uint256(value)))); | |
} | |
/** | |
* @dev Returns the value associated with `key`. O(1). | |
* | |
* Requirements: | |
* | |
* - `key` must be in the map. | |
*/ | |
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { | |
return address(uint160(uint256(_get(map._inner, bytes32(key))))); | |
} | |
/** | |
* @dev Same as {get}, with a custom error message when `key` is not in the map. | |
* | |
* CAUTION: This function is deprecated because it requires allocating memory for the error | |
* message unnecessarily. For custom revert reasons use {tryGet}. | |
*/ | |
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { | |
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Library for managing | |
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive | |
* types. | |
* | |
* Sets have the following properties: | |
* | |
* - Elements are added, removed, and checked for existence in constant time | |
* (O(1)). | |
* - Elements are enumerated in O(n). No guarantees are made on the ordering. | |
* | |
* ``` | |
* contract Example { | |
* // Add the library methods | |
* using EnumerableSet for EnumerableSet.AddressSet; | |
* | |
* // Declare a set state variable | |
* EnumerableSet.AddressSet private mySet; | |
* } | |
* ``` | |
* | |
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) | |
* and `uint256` (`UintSet`) are supported. | |
*/ | |
library EnumerableSet { | |
// To implement this library for multiple types with as little code | |
// repetition as possible, we write it in terms of a generic Set type with | |
// bytes32 values. | |
// The Set implementation uses private functions, and user-facing | |
// implementations (such as AddressSet) are just wrappers around the | |
// underlying Set. | |
// This means that we can only create new EnumerableSets for types that fit | |
// in bytes32. | |
struct Set { | |
// Storage of set values | |
bytes32[] _values; | |
// Position of the value in the `values` array, plus 1 because index 0 | |
// means a value is not in the set. | |
mapping (bytes32 => uint256) _indexes; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function _add(Set storage set, bytes32 value) private returns (bool) { | |
if (!_contains(set, value)) { | |
set._values.push(value); | |
// The value is stored at length-1, but we add 1 to all indexes | |
// and use 0 as a sentinel value | |
set._indexes[value] = set._values.length; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function _remove(Set storage set, bytes32 value) private returns (bool) { | |
// We read and store the value's index to prevent multiple reads from the same storage slot | |
uint256 valueIndex = set._indexes[value]; | |
if (valueIndex != 0) { // Equivalent to contains(set, value) | |
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in | |
// the array, and then remove the last element (sometimes called as 'swap and pop'). | |
// This modifies the order of the array, as noted in {at}. | |
uint256 toDeleteIndex = valueIndex - 1; | |
uint256 lastIndex = set._values.length - 1; | |
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs | |
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. | |
bytes32 lastvalue = set._values[lastIndex]; | |
// Move the last value to the index where the value to delete is | |
set._values[toDeleteIndex] = lastvalue; | |
// Update the index for the moved value | |
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based | |
// Delete the slot where the moved value was stored | |
set._values.pop(); | |
// Delete the index for the deleted slot | |
delete set._indexes[value]; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function _contains(Set storage set, bytes32 value) private view returns (bool) { | |
return set._indexes[value] != 0; | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function _length(Set storage set) private view returns (uint256) { | |
return set._values.length; | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function _at(Set storage set, uint256 index) private view returns (bytes32) { | |
require(set._values.length > index, "EnumerableSet: index out of bounds"); | |
return set._values[index]; | |
} | |
// Bytes32Set | |
struct Bytes32Set { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _add(set._inner, value); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { | |
return _remove(set._inner, value); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { | |
return _contains(set._inner, value); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(Bytes32Set storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { | |
return _at(set._inner, index); | |
} | |
// AddressSet | |
struct AddressSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(AddressSet storage set, address value) internal returns (bool) { | |
return _add(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(AddressSet storage set, address value) internal returns (bool) { | |
return _remove(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(AddressSet storage set, address value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(uint256(uint160(value)))); | |
} | |
/** | |
* @dev Returns the number of values in the set. O(1). | |
*/ | |
function length(AddressSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(AddressSet storage set, uint256 index) internal view returns (address) { | |
return address(uint160(uint256(_at(set._inner, index)))); | |
} | |
// UintSet | |
struct UintSet { | |
Set _inner; | |
} | |
/** | |
* @dev Add a value to a set. O(1). | |
* | |
* Returns true if the value was added to the set, that is if it was not | |
* already present. | |
*/ | |
function add(UintSet storage set, uint256 value) internal returns (bool) { | |
return _add(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Removes a value from a set. O(1). | |
* | |
* Returns true if the value was removed from the set, that is if it was | |
* present. | |
*/ | |
function remove(UintSet storage set, uint256 value) internal returns (bool) { | |
return _remove(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns true if the value is in the set. O(1). | |
*/ | |
function contains(UintSet storage set, uint256 value) internal view returns (bool) { | |
return _contains(set._inner, bytes32(value)); | |
} | |
/** | |
* @dev Returns the number of values on the set. O(1). | |
*/ | |
function length(UintSet storage set) internal view returns (uint256) { | |
return _length(set._inner); | |
} | |
/** | |
* @dev Returns the value stored at position `index` in the set. O(1). | |
* | |
* Note that there are no guarantees on the ordering of values inside the | |
* array, and it may change when more values are added or removed. | |
* | |
* Requirements: | |
* | |
* - `index` must be strictly less than {length}. | |
*/ | |
function at(UintSet storage set, uint256 index) internal view returns (uint256) { | |
return uint256(_at(set._inner, index)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
/** | |
* @dev String operations. | |
*/ | |
library Strings { | |
bytes16 private constant alphabet = "0123456789abcdef"; | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` decimal representation. | |
*/ | |
function toString(uint256 value) internal pure returns (string memory) { | |
// Inspired by OraclizeAPI's implementation - MIT licence | |
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol | |
if (value == 0) { | |
return "0"; | |
} | |
uint256 temp = value; | |
uint256 digits; | |
while (temp != 0) { | |
digits++; | |
temp /= 10; | |
} | |
bytes memory buffer = new bytes(digits); | |
while (value != 0) { | |
digits -= 1; | |
buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); | |
value /= 10; | |
} | |
return string(buffer); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. | |
*/ | |
function toHexString(uint256 value) internal pure returns (string memory) { | |
if (value == 0) { | |
return "0x00"; | |
} | |
uint256 temp = value; | |
uint256 length = 0; | |
while (temp != 0) { | |
length++; | |
temp >>= 8; | |
} | |
return toHexString(value, length); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. | |
*/ | |
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { | |
bytes memory buffer = new bytes(2 * length + 2); | |
buffer[0] = "0"; | |
buffer[1] = "x"; | |
for (uint256 i = 2 * length + 1; i > 1; --i) { | |
buffer[i] = alphabet[value & 0xf]; | |
value >>= 4; | |
} | |
require(value == 0, "Strings: hex length insufficient"); | |
return string(buffer); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "./OpenZeppelin/access/Ownable.sol"; | |
import "./Interfaces/ISettings.sol"; | |
contract Settings is Ownable, ISettings { | |
/// @notice the maximum auction length | |
uint256 public override maxAuctionLength; | |
/// @notice the longest an auction can ever be | |
uint256 public constant maxMaxAuctionLength = 8 weeks; | |
/// @notice the minimum auction length | |
uint256 public override minAuctionLength; | |
/// @notice the shortest an auction can ever be | |
uint256 public constant minMinAuctionLength = 0; | |
/// @notice governance fee max | |
uint256 public override governanceFee; | |
/// @notice 10% fee is max | |
uint256 public constant maxGovFee = 100; | |
/// @notice max curator fee | |
uint256 public override maxCuratorFee; | |
/// @notice the % bid increase required for a new bid | |
uint256 public override minBidIncrease; | |
/// @notice 10% bid increase is max | |
uint256 public constant maxMinBidIncrease = 100; | |
/// @notice 1% bid increase is min | |
uint256 public constant minMinBidIncrease = 10; | |
/// @notice the % of tokens required to be voting for an auction to start | |
uint256 public override minVotePercentage; | |
/// @notice the max % increase over the initial | |
uint256 public override maxReserveFactor; | |
/// @notice the max % decrease from the initial | |
uint256 public override minReserveFactor; | |
/// @notice the address who receives auction fees | |
address payable public override feeReceiver; | |
event UpdateMaxAuctionLength(uint256 _old, uint256 _new); | |
event UpdateMinAuctionLength(uint256 _old, uint256 _new); | |
event UpdateGovernanceFee(uint256 _old, uint256 _new); | |
event UpdateCuratorFee(uint256 _old, uint256 _new); | |
event UpdateMinBidIncrease(uint256 _old, uint256 _new); | |
event UpdateMinVotePercentage(uint256 _old, uint256 _new); | |
event UpdateMaxReserveFactor(uint256 _old, uint256 _new); | |
event UpdateMinReserveFactor(uint256 _old, uint256 _new); | |
event UpdateFeeReceiver(address _old, address _new); | |
constructor() { | |
maxAuctionLength = 2 weeks; | |
minAuctionLength = 1; | |
feeReceiver = payable(msg.sender); | |
minReserveFactor = 500; // 50% | |
maxReserveFactor = 2000; // 200% | |
minBidIncrease = 50; // 5% | |
maxCuratorFee = 100; | |
minVotePercentage = 500; // 50% | |
} | |
function setMaxAuctionLength(uint256 _length) external onlyOwner { | |
require(_length <= maxMaxAuctionLength, "max auction length too high"); | |
require(_length > minAuctionLength, "max auction length too low"); | |
emit UpdateMaxAuctionLength(maxAuctionLength, _length); | |
maxAuctionLength = _length; | |
} | |
function setMinAuctionLength(uint256 _length) external onlyOwner { | |
require(_length >= minMinAuctionLength, "min auction length too low"); | |
require(_length < maxAuctionLength, "min auction length too high"); | |
emit UpdateMinAuctionLength(minAuctionLength, _length); | |
minAuctionLength = _length; | |
} | |
function setGovernanceFee(uint256 _fee) external onlyOwner { | |
require(_fee <= maxGovFee, "fee too high"); | |
emit UpdateGovernanceFee(governanceFee, _fee); | |
governanceFee = _fee; | |
} | |
function setMaxCuratorFee(uint256 _fee) external onlyOwner { | |
emit UpdateCuratorFee(governanceFee, _fee); | |
maxCuratorFee = _fee; | |
} | |
function setMinBidIncrease(uint256 _min) external onlyOwner { | |
require(_min <= maxMinBidIncrease, "min bid increase too high"); | |
require(_min >= minMinBidIncrease, "min bid increase too low"); | |
emit UpdateMinBidIncrease(minBidIncrease, _min); | |
minBidIncrease = _min; | |
} | |
function setMinVotePercentage(uint256 _min) external onlyOwner { | |
// 1000 is 100% | |
require(_min <= 1000, "min vote percentage too high"); | |
emit UpdateMinVotePercentage(minVotePercentage, _min); | |
minVotePercentage = _min; | |
} | |
function setMaxReserveFactor(uint256 _factor) external onlyOwner { | |
require(_factor > minReserveFactor, "max reserve factor too low"); | |
emit UpdateMaxReserveFactor(maxReserveFactor, _factor); | |
maxReserveFactor = _factor; | |
} | |
function setMinReserveFactor(uint256 _factor) external onlyOwner { | |
require(_factor < maxReserveFactor, "min reserve factor too high"); | |
emit UpdateMinReserveFactor(minReserveFactor, _factor); | |
minReserveFactor = _factor; | |
} | |
function setFeeReceiver(address payable _receiver) external onlyOwner { | |
require(_receiver != address(0), "fees cannot go to 0 address"); | |
emit UpdateFeeReceiver(feeReceiver, _receiver); | |
feeReceiver = _receiver; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.9; | |
import "hardhat/console.sol"; | |
contract MemoryStorage { | |
struct Person { | |
uint age; | |
string name; | |
} | |
mapping(address => Person) public people; | |
function setPerson(uint _age, string calldata _name) external { | |
Person memory personMemory = Person({ | |
age: _age, | |
name: _name | |
}); | |
people[msg.sender] = personMemory; | |
// console.log(personMemory); | |
Person storage personStorage = people[msg.sender]; | |
personStorage.age = 111; | |
Person memory personMemory2 = people[msg.sender]; | |
personMemory2.age = 42000; | |
// console.log(personStorage); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.12; | |
/// @title Multicall3 | |
/// @notice Aggregate results from multiple function calls | |
/// @dev Multicall & Multicall2 backwards-compatible | |
/// @dev Aggregate methods are marked `payable` to save 24 gas per call | |
/// @author Michael Elliot <[email protected]> | |
/// @author Joshua Levine <[email protected]> | |
/// @author Nick Johnson <[email protected]> | |
/// @author Andreas Bigger <[email protected]> | |
/// @author Matt Solomon <[email protected]> | |
contract Multicall3 { | |
struct Call { | |
address target; | |
bytes callData; | |
} | |
struct Call3 { | |
address target; | |
bool allowFailure; | |
bytes callData; | |
} | |
struct Call3Value { | |
address target; | |
bool allowFailure; | |
uint256 value; | |
bytes callData; | |
} | |
struct Result { | |
bool success; | |
bytes returnData; | |
} | |
/// @notice Backwards-compatible call aggregation with Multicall | |
/// @param calls An array of Call structs | |
/// @return blockNumber The block number where the calls were executed | |
/// @return returnData An array of bytes containing the responses | |
function aggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes[] memory returnData) { | |
blockNumber = block.number; | |
uint256 length = calls.length; | |
returnData = new bytes[](length); | |
Call calldata call; | |
for (uint256 i = 0; i < length;) { | |
bool success; | |
call = calls[i]; | |
(success, returnData[i]) = call.target.call(call.callData); | |
require(success, "Multicall3: call failed"); | |
unchecked { ++i; } | |
} | |
} | |
/// @notice Backwards-compatible with Multicall2 | |
/// @notice Aggregate calls without requiring success | |
/// @param requireSuccess If true, require all calls to succeed | |
/// @param calls An array of Call structs | |
/// @return returnData An array of Result structs | |
function tryAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (Result[] memory returnData) { | |
uint256 length = calls.length; | |
returnData = new Result[](length); | |
Call calldata call; | |
for (uint256 i = 0; i < length;) { | |
Result memory result = returnData[i]; | |
call = calls[i]; | |
(result.success, result.returnData) = call.target.call(call.callData); | |
if (requireSuccess) require(result.success, "Multicall3: call failed"); | |
unchecked { ++i; } | |
} | |
} | |
/// @notice Backwards-compatible with Multicall2 | |
/// @notice Aggregate calls and allow failures using tryAggregate | |
/// @param calls An array of Call structs | |
/// @return blockNumber The block number where the calls were executed | |
/// @return blockHash The hash of the block where the calls were executed | |
/// @return returnData An array of Result structs | |
function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { | |
blockNumber = block.number; | |
blockHash = blockhash(block.number); | |
returnData = tryAggregate(requireSuccess, calls); | |
} | |
/// @notice Backwards-compatible with Multicall2 | |
/// @notice Aggregate calls and allow failures using tryAggregate | |
/// @param calls An array of Call structs | |
/// @return blockNumber The block number where the calls were executed | |
/// @return blockHash The hash of the block where the calls were executed | |
/// @return returnData An array of Result structs | |
function blockAndAggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { | |
(blockNumber, blockHash, returnData) = tryBlockAndAggregate(true, calls); | |
} | |
/// @notice Aggregate calls, ensuring each returns success if required | |
/// @param calls An array of Call3 structs | |
/// @return returnData An array of Result structs | |
function aggregate3(Call3[] calldata calls) public payable returns (Result[] memory returnData) { | |
uint256 length = calls.length; | |
returnData = new Result[](length); | |
Call3 calldata calli; | |
for (uint256 i = 0; i < length;) { | |
Result memory result = returnData[i]; | |
calli = calls[i]; | |
(result.success, result.returnData) = calli.target.call(calli.callData); | |
assembly { | |
// Revert if the call fails and failure is not allowed | |
// `allowFailure := calldataload(add(calli, 0x20))` and `success := mload(result)` | |
if iszero(or(calldataload(add(calli, 0x20)), mload(result))) { | |
// set "Error(string)" signature: bytes32(bytes4(keccak256("Error(string)"))) | |
mstore(0x00, 0x08c379a000000000000000000000000000000000000000000000000000000000) | |
// set data offset | |
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) | |
// set length of revert string | |
mstore(0x24, 0x0000000000000000000000000000000000000000000000000000000000000017) | |
// set revert string: bytes32(abi.encodePacked("Multicall3: call failed")) | |
mstore(0x44, 0x4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000) | |
revert(0x00, 0x64) | |
} | |
} | |
unchecked { ++i; } | |
} | |
} | |
/// @notice Aggregate calls with a msg value | |
/// @notice Reverts if msg.value is less than the sum of the call values | |
/// @param calls An array of Call3Value structs | |
/// @return returnData An array of Result structs | |
function aggregate3Value(Call3Value[] calldata calls) public payable returns (Result[] memory returnData) { | |
uint256 valAccumulator; | |
uint256 length = calls.length; | |
returnData = new Result[](length); | |
Call3Value calldata calli; | |
for (uint256 i = 0; i < length;) { | |
Result memory result = returnData[i]; | |
calli = calls[i]; | |
uint256 val = calli.value; | |
// Humanity will be a Type V Kardashev Civilization before this overflows - andreas | |
// ~ 10^25 Wei in existence << ~ 10^76 size uint fits in a uint256 | |
unchecked { valAccumulator += val; } | |
(result.success, result.returnData) = calli.target.call{value: val}(calli.callData); | |
assembly { | |
// Revert if the call fails and failure is not allowed | |
// `allowFailure := calldataload(add(calli, 0x20))` and `success := mload(result)` | |
if iszero(or(calldataload(add(calli, 0x20)), mload(result))) { | |
// set "Error(string)" signature: bytes32(bytes4(keccak256("Error(string)"))) | |
mstore(0x00, 0x08c379a000000000000000000000000000000000000000000000000000000000) | |
// set data offset | |
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) | |
// set length of revert string | |
mstore(0x24, 0x0000000000000000000000000000000000000000000000000000000000000017) | |
// set revert string: bytes32(abi.encodePacked("Multicall3: call failed")) | |
mstore(0x44, 0x4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000) | |
revert(0x00, 0x84) | |
} | |
} | |
unchecked { ++i; } | |
} | |
// Finally, make sure the msg.value = SUM(call[0...i].value) | |
require(msg.value == valAccumulator, "Multicall3: value mismatch"); | |
} | |
/// @notice Returns the block hash for the given block number | |
/// @param blockNumber The block number | |
function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) { | |
blockHash = blockhash(blockNumber); | |
} | |
/// @notice Returns the block number | |
function getBlockNumber() public view returns (uint256 blockNumber) { | |
blockNumber = block.number; | |
} | |
/// @notice Returns the block coinbase | |
function getCurrentBlockCoinbase() public view returns (address coinbase) { | |
coinbase = block.coinbase; | |
} | |
/// @notice Returns the block difficulty | |
function getCurrentBlockDifficulty() public view returns (uint256 difficulty) { | |
difficulty = block.difficulty; | |
} | |
/// @notice Returns the block gas limit | |
function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) { | |
gaslimit = block.gaslimit; | |
} | |
/// @notice Returns the block timestamp | |
function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { | |
timestamp = block.timestamp; | |
} | |
/// @notice Returns the (ETH) balance of a given address | |
function getEthBalance(address addr) public view returns (uint256 balance) { | |
balance = addr.balance; | |
} | |
/// @notice Returns the block hash of the last block | |
function getLastBlockHash() public view returns (bytes32 blockHash) { | |
unchecked { | |
blockHash = blockhash(block.number - 1); | |
} | |
} | |
/// @notice Gets the base fee of the given block | |
/// @notice Can revert if the BASEFEE opcode is not implemented by the given chain | |
function getBasefee() public view returns (uint256 basefee) { | |
basefee = block.basefee; | |
} | |
/// @notice Returns the chain id | |
function getChainId() public view returns (uint256 chainid) { | |
chainid = block.chainid; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.16; | |
/// @notice Multi-sig wallet where owners can submit and execute transactions given enough approvals | |
contract MultiSigWallet { | |
/// EVENTS /// | |
event Deposit(address indexed sender, uint amount); | |
event Submit(uint indexed txId); | |
event Approve(address indexed owner, uint indexed txId); | |
event Revoke(address indexed owner, uint indexed txId); | |
event Execute(uint indexed txId); | |
/// VARIABLES /// | |
struct Transaction { | |
address to; | |
uint value; | |
bytes data; | |
bool executed; | |
} | |
address[] public owners; | |
mapping(address => bool) public isOwner; | |
uint public requiredApprovals; | |
Transaction[] public transactions; | |
mapping(uint => mapping(address => bool)) public approved; | |
/// MODIFIERS /// | |
/// @notice Check if caller is one of the owners | |
modifier onlyOwner() { | |
require(isOwner[msg.sender], "Not an owner."); | |
_; | |
} | |
/// @notice Check if transaction exists | |
/// @param _txId Transaction ID | |
modifier txExists(uint _txId) { | |
require(_txId < transactions.length, "Transaction does not exist."); | |
_; | |
} | |
/// @notice Check if transaction not yet approved by a given message sender (owner) | |
/// @param _txId Transaction ID | |
modifier notApproved(uint _txId) { | |
require(!approved[_txId][msg.sender], "Transaction already approved."); | |
_; | |
} | |
/// @notice Check if transaction not yet executed | |
/// @param _txId Transaction ID | |
modifier notExecuted(uint _txId) { | |
require(!transactions[_txId].executed, "Transaction already executed."); | |
_; | |
} | |
/// @param _owners Addresses of wallet owners | |
/// @param _requiredApprovals Number of approvals needed for transaction to become executable | |
constructor(address[] memory _owners, uint _requiredApprovals) { | |
require(_owners.length > 0, "There must be at least 1 owner."); | |
require( | |
_requiredApprovals > 0 && _requiredApprovals <= _owners.length, | |
"Invalid required number of approvals." | |
); | |
for (uint i; i < _owners.length; i++) { | |
address owner = _owners[i]; | |
require(owner != address(0), "Invalid owner."); | |
require(!isOwner[owner], "Owner is not unique."); | |
isOwner[owner] = true; | |
owners.push(owner); | |
} | |
requiredApprovals = _requiredApprovals; | |
} | |
/// @notice Submit transaction for approvals | |
/// @param _to Address where to submit the transaction | |
/// @param _value How much Ether to send | |
/// @param _data Any additional data to add to transaction | |
function submit( | |
address _to, | |
uint _value, | |
bytes calldata _data | |
) external onlyOwner { | |
Transaction memory transaction = Transaction({ | |
to: _to, | |
value: _value, | |
data: _data, | |
executed: false | |
}); | |
transactions.push(transaction); | |
emit Submit(transactions.length - 1); | |
} | |
/// @notice Approve a given transaction, must be an owner. | |
/// @param _txId Transaction ID | |
function approve(uint _txId) | |
external | |
onlyOwner | |
txExists(_txId) | |
notApproved(_txId) | |
notExecuted(_txId) | |
{ | |
approved[_txId][msg.sender] = true; | |
emit Approve(msg.sender, _txId); | |
} | |
/// @notice Revoke approval from a given transaction. | |
/// @dev Only same address as the one that gave approval can revoke it. | |
/// @param _txId Transaction ID | |
function revoke(uint _txId) | |
external | |
onlyOwner | |
txExists(_txId) | |
notExecuted(_txId) | |
{ | |
require(approved[_txId][msg.sender], "Transaction not approved."); | |
approved[_txId][msg.sender] = false; | |
emit Revoke(msg.sender, _txId); | |
} | |
/// @notice Execute a given transaction given it has enough approvals | |
/// @param _txId Transaction ID | |
function execute(uint _txId) external txExists(_txId) notExecuted(_txId) { | |
require( | |
_getApprovalCount(_txId) >= requiredApprovals, | |
"Number of approvals is less than required." | |
); | |
Transaction storage transaction = transactions[_txId]; | |
transaction.executed = true; | |
(bool success, ) = transaction.to.call{value: transaction.value}( | |
transaction.data | |
); | |
require(success, "Transaction failed."); | |
emit Execute(_txId); | |
} | |
/// @notice Get how many owners have approved a transaction | |
/// @param _txId Transaction ID | |
function _getApprovalCount(uint _txId) private view returns (uint count) { | |
for (uint i = 0; i < owners.length; i++) { | |
if (approved[_txId][owners[i]]) { | |
count += 1; | |
} | |
} | |
} | |
/// @notice Deposit Ether to the wallet | |
receive() external payable { | |
emit Deposit(msg.sender, msg.value); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.9; | |
contract TestContract { | |
uint public i; | |
uint public x; | |
uint public y; | |
uint public z; | |
uint public d; | |
uint public a; | |
uint public b; | |
uint public c; | |
function jkjk(uint j) public { | |
i += j * 2; | |
} | |
function getData() public returns (bytes memory) { | |
return abi.encodeWithSignature("callMe(uint256)", 123); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment