contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 4807, 5184 ] }
5,307
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
balanceOf
function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); }
/** * @dev See {IERC721-balanceOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 5243, 5454 ] }
5,308
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
ownershipOf
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (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(); }
/** * 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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 6081, 7169 ] }
5,309
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
ownerOf
function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; }
/** * @dev See {IERC721-ownerOf}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 7226, 7355 ] }
5,310
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev See {IERC721Metadata-name}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 7417, 7522 ] }
5,311
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev See {IERC721Metadata-symbol}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 7586, 7695 ] }
5,312
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
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 See {IERC721Metadata-tokenURI}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 7761, 8084 ] }
5,313
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_baseURI
function _baseURI() internal view virtual returns (string memory) { return ''; }
/** * @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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 8327, 8426 ] }
5,314
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
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-approve}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 8483, 8859 ] }
5,315
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
getApproved
function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; }
/** * @dev See {IERC721-getApproved}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 8920, 9129 ] }
5,316
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
setApprovalForAll
function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
/** * @dev See {IERC721-setApprovalForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 9196, 9480 ] }
5,317
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; }
/** * @dev See {IERC721-isApprovedForAll}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 9546, 9715 ] }
5,318
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
transferFrom
function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); }
/** * @dev See {IERC721-transferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 9777, 9952 ] }
5,319
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 10018, 10208 ] }
5,320
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
safeTransferFrom
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
/** * @dev See {IERC721-safeTransferFrom}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 10274, 10621 ] }
5,321
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_exists
function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; }
/** * @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`), */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 10871, 11020 ] }
5,322
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_safeMint
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); }
/** * @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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 11490, 11658 ] }
5,323
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_mint
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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
/** * @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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 11912, 13339 ] }
5,324
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_transfer
function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); }
/** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 13588, 15705 ] }
5,325
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_burn
function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } }
/** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 15929, 17974 ] }
5,326
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_approve
function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
/** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 18087, 18288 ] }
5,327
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_checkOnERC721Received
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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } }
/** * @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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 18848, 19643 ] }
5,328
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_beforeTokenTransfers
function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {}
/** * @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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 20286, 20450 ] }
5,329
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
ERC721A
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 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; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).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); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * 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 (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 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 (!_checkOnERC721Received(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 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 > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 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; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 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**128 - 1 (max value of uint128). */
NatSpecMultiLine
_afterTokenTransfers
function _afterTokenTransfers( 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. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 21104, 21267 ] }
5,330
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
EscapeOfficial
contract EscapeOfficial is Ownable, ReentrancyGuard, ERC721A { using Strings for uint256; string private baseURI; string private baseExtension = ".json"; uint256 private cost = 0.025 ether; uint256 public maxSupply = 6577; uint256 public maxMintAmount = 5; bool public saleIsActive = true; bool public revealed = false; string private notRevealedUri; uint256 numberOfFreeNFTs = 1000; mapping(address => bool) private whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721A(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) external payable { require(saleIsActive, "Sale is not active!"); require(totalSupply() >= numberOfFreeNFTs, "Can not mint more than one until 1000 NFTs are minted!"); require(balanceOf(msg.sender) + _mintAmount <= maxMintAmount, "Maximum 5 NFTs minted per wallet!"); require(totalSupply() + _mintAmount <= maxSupply, "Not enough tokens left"); require(msg.value >= (cost * _mintAmount), "Not enough ether sent"); _safeMint(msg.sender, _mintAmount); payable(owner()).transfer(address(this).balance); } function mintOne() public payable { uint256 supply = totalSupply(); require(saleIsActive, "Sale is not active!"); require(balanceOf(msg.sender) < 1, "Can only mint once per wallet!"); require(supply < numberOfFreeNFTs, "Total supply must not exceed number of free NFTs"); _safeMint(msg.sender, 1); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return bytes(notRevealedUri).length > 0 ? string(abi.encodePacked(notRevealedUri, (tokenId + 1).toString(), baseExtension)) : ""; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId + 1).toString(), baseExtension)) : ""; } //only owner function setReveal(bool value) public onlyOwner { revealed = value; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setSaleIsActive(bool _state) public onlyOwner { saleIsActive = _state; } function whitelistUser(address _user) public onlyOwner { whitelisted[_user] = true; } function setNumberOfFreeNFTs(uint256 _number) public onlyOwner { numberOfFreeNFTs = _number; } function setMaxSupply(uint256 _number) public onlyOwner { maxSupply = _number; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
_baseURI
function _baseURI() internal view virtual override returns (string memory) { return baseURI; }
// internal
LineComment
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 739, 844 ] }
5,331
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
EscapeOfficial
contract EscapeOfficial is Ownable, ReentrancyGuard, ERC721A { using Strings for uint256; string private baseURI; string private baseExtension = ".json"; uint256 private cost = 0.025 ether; uint256 public maxSupply = 6577; uint256 public maxMintAmount = 5; bool public saleIsActive = true; bool public revealed = false; string private notRevealedUri; uint256 numberOfFreeNFTs = 1000; mapping(address => bool) private whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721A(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) external payable { require(saleIsActive, "Sale is not active!"); require(totalSupply() >= numberOfFreeNFTs, "Can not mint more than one until 1000 NFTs are minted!"); require(balanceOf(msg.sender) + _mintAmount <= maxMintAmount, "Maximum 5 NFTs minted per wallet!"); require(totalSupply() + _mintAmount <= maxSupply, "Not enough tokens left"); require(msg.value >= (cost * _mintAmount), "Not enough ether sent"); _safeMint(msg.sender, _mintAmount); payable(owner()).transfer(address(this).balance); } function mintOne() public payable { uint256 supply = totalSupply(); require(saleIsActive, "Sale is not active!"); require(balanceOf(msg.sender) < 1, "Can only mint once per wallet!"); require(supply < numberOfFreeNFTs, "Total supply must not exceed number of free NFTs"); _safeMint(msg.sender, 1); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return bytes(notRevealedUri).length > 0 ? string(abi.encodePacked(notRevealedUri, (tokenId + 1).toString(), baseExtension)) : ""; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId + 1).toString(), baseExtension)) : ""; } //only owner function setReveal(bool value) public onlyOwner { revealed = value; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setSaleIsActive(bool _state) public onlyOwner { saleIsActive = _state; } function whitelistUser(address _user) public onlyOwner { whitelisted[_user] = true; } function setNumberOfFreeNFTs(uint256 _number) public onlyOwner { numberOfFreeNFTs = _number; } function setMaxSupply(uint256 _number) public onlyOwner { maxSupply = _number; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
mint
function mint(uint256 _mintAmount) external payable { require(saleIsActive, "Sale is not active!"); require(totalSupply() >= numberOfFreeNFTs, "Can not mint more than one until 1000 NFTs are minted!"); require(balanceOf(msg.sender) + _mintAmount <= maxMintAmount, "Maximum 5 NFTs minted per wallet!"); require(totalSupply() + _mintAmount <= maxSupply, "Not enough tokens left"); require(msg.value >= (cost * _mintAmount), "Not enough ether sent"); _safeMint(msg.sender, _mintAmount); payable(owner()).transfer(address(this).balance); }
// public
LineComment
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 860, 1436 ] }
5,332
EscapeOfficial
@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
0x4ecc242248993edb5c0aa0337677d5851e36c213
Solidity
EscapeOfficial
contract EscapeOfficial is Ownable, ReentrancyGuard, ERC721A { using Strings for uint256; string private baseURI; string private baseExtension = ".json"; uint256 private cost = 0.025 ether; uint256 public maxSupply = 6577; uint256 public maxMintAmount = 5; bool public saleIsActive = true; bool public revealed = false; string private notRevealedUri; uint256 numberOfFreeNFTs = 1000; mapping(address => bool) private whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721A(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) external payable { require(saleIsActive, "Sale is not active!"); require(totalSupply() >= numberOfFreeNFTs, "Can not mint more than one until 1000 NFTs are minted!"); require(balanceOf(msg.sender) + _mintAmount <= maxMintAmount, "Maximum 5 NFTs minted per wallet!"); require(totalSupply() + _mintAmount <= maxSupply, "Not enough tokens left"); require(msg.value >= (cost * _mintAmount), "Not enough ether sent"); _safeMint(msg.sender, _mintAmount); payable(owner()).transfer(address(this).balance); } function mintOne() public payable { uint256 supply = totalSupply(); require(saleIsActive, "Sale is not active!"); require(balanceOf(msg.sender) < 1, "Can only mint once per wallet!"); require(supply < numberOfFreeNFTs, "Total supply must not exceed number of free NFTs"); _safeMint(msg.sender, 1); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return bytes(notRevealedUri).length > 0 ? string(abi.encodePacked(notRevealedUri, (tokenId + 1).toString(), baseExtension)) : ""; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId + 1).toString(), baseExtension)) : ""; } //only owner function setReveal(bool value) public onlyOwner { revealed = value; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setSaleIsActive(bool _state) public onlyOwner { saleIsActive = _state; } function whitelistUser(address _user) public onlyOwner { whitelisted[_user] = true; } function setNumberOfFreeNFTs(uint256 _number) public onlyOwner { numberOfFreeNFTs = _number; } function setMaxSupply(uint256 _number) public onlyOwner { maxSupply = _number; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = false; } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
setReveal
function setReveal(bool value) public onlyOwner { revealed = value; }
//only owner
LineComment
v0.8.7+commit.e28d00a7
GNU GPLv3
ipfs://cb01099678bee8c0f17e31bcbbc7a4a34709dd17835cecfd0304598570abde9a
{ "func_code_index": [ 2427, 2507 ] }
5,333
Staker
Staker.sol
0xbae235823d7255d9d48635ced4735227244cd583
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://b8bfc7ab980326a01601bc1a362edb3304460f6df43ea43abca6185209e5dcbf
{ "func_code_index": [ 585, 729 ] }
5,334
SquidArena
contracts/SquidArena.sol
0x0cc34f2ee846c97e6a2c31b8de8314781d779358
Solidity
SquidArena
contract SquidArena is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 8 * 10**16; // Price to mint a single token uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator (Kovan) 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Contract Token (Kovan) ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 2 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + _count <= MAX_ELEMENTS, 'Max limit'); require(total <= MAX_ELEMENTS, 'Sale end'); require(_count <= MAX_BY_MINT, 'Exceeds number'); require(msg.value >= price(_count), 'Value below price'); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
// ██████ █████ █ ██ ██▓▓█████▄ ▄▄▄ ██▀███ ▓█████ ███▄ █ ▄▄▄ // ▒██ ▒ ▒██▓ ██▒ ██ ▓██▒▓██▒▒██▀ ██▌ ▒████▄ ▓██ ▒ ██▒▓█ ▀ ██ ▀█ █ ▒████▄ // ░ ▓██▄ ▒██▒ ██░▓██ ▒██░▒██▒░██ █▌ ▒██ ▀█▄ ▓██ ░▄█ ▒▒███ ▓██ ▀█ ██▒▒██ ▀█▄ // ▒ ██▒░██ █▀ ░▓▓█ ░██░░██░░▓█▄ ▌ ░██▄▄▄▄██ ▒██▀▀█▄ ▒▓█ ▄ ▓██▒ ▐▌██▒░██▄▄▄▄██ // ▒██████▒▒░▒███▒█▄ ▒▒█████▓ ░██░░▒████▓ ▓█ ▓██▒░██▓ ▒██▒░▒████▒▒██░ ▓██░ ▓█ ▓██▒ // ▒ ▒▓▒ ▒ ░░░ ▒▒░ ▒ ░▒▓▒ ▒ ▒ ░▓ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░ ▒ ▒ ▒▒ ▓▒█░ // ░ ░▒ ░ ░ ░ ▒░ ░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░ ░ ░ ░░ ░░ ░ ▒░ ▒ ▒▒ ░ // ░ ░ ░ ░ ░ ░░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ▒ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ // Squid game is a smart contract that programs a deflationary NFT, implemented as a game. // In this game, there will be n rounds and 2**n tokens. // Each round, a random 50% of the tokens will be burned. // After the last round, there will be one token remaining, and the owner will be able to // claim the treasury, which consists of the mint price paid for each token.
LineComment
pullRug
function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); }
// This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters
LineComment
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4324, 4494 ] }
5,335
SquidArena
contracts/SquidArena.sol
0x0cc34f2ee846c97e6a2c31b8de8314781d779358
Solidity
SquidArena
contract SquidArena is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 8 * 10**16; // Price to mint a single token uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator (Kovan) 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Contract Token (Kovan) ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 2 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + _count <= MAX_ELEMENTS, 'Max limit'); require(total <= MAX_ELEMENTS, 'Sale end'); require(_count <= MAX_BY_MINT, 'Exceeds number'); require(msg.value >= price(_count), 'Value below price'); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
// ██████ █████ █ ██ ██▓▓█████▄ ▄▄▄ ██▀███ ▓█████ ███▄ █ ▄▄▄ // ▒██ ▒ ▒██▓ ██▒ ██ ▓██▒▓██▒▒██▀ ██▌ ▒████▄ ▓██ ▒ ██▒▓█ ▀ ██ ▀█ █ ▒████▄ // ░ ▓██▄ ▒██▒ ██░▓██ ▒██░▒██▒░██ █▌ ▒██ ▀█▄ ▓██ ░▄█ ▒▒███ ▓██ ▀█ ██▒▒██ ▀█▄ // ▒ ██▒░██ █▀ ░▓▓█ ░██░░██░░▓█▄ ▌ ░██▄▄▄▄██ ▒██▀▀█▄ ▒▓█ ▄ ▓██▒ ▐▌██▒░██▄▄▄▄██ // ▒██████▒▒░▒███▒█▄ ▒▒█████▓ ░██░░▒████▓ ▓█ ▓██▒░██▓ ▒██▒░▒████▒▒██░ ▓██░ ▓█ ▓██▒ // ▒ ▒▓▒ ▒ ░░░ ▒▒░ ▒ ░▒▓▒ ▒ ▒ ░▓ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░ ▒ ▒ ▒▒ ▓▒█░ // ░ ░▒ ░ ░ ░ ▒░ ░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░ ░ ░ ░░ ░░ ░ ▒░ ▒ ▒▒ ░ // ░ ░ ░ ░ ░ ░░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ▒ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ // Squid game is a smart contract that programs a deflationary NFT, implemented as a game. // In this game, there will be n rounds and 2**n tokens. // Each round, a random 50% of the tokens will be burned. // After the last round, there will be one token remaining, and the owner will be able to // claim the treasury, which consists of the mint price paid for each token.
LineComment
claimWinnerReward
function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); }
/** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 5681, 5960 ] }
5,336
SquidArena
contracts/SquidArena.sol
0x0cc34f2ee846c97e6a2c31b8de8314781d779358
Solidity
SquidArena
contract SquidArena is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 8 * 10**16; // Price to mint a single token uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator (Kovan) 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Contract Token (Kovan) ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 2 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + _count <= MAX_ELEMENTS, 'Max limit'); require(total <= MAX_ELEMENTS, 'Sale end'); require(_count <= MAX_BY_MINT, 'Exceeds number'); require(msg.value >= price(_count), 'Value below price'); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
// ██████ █████ █ ██ ██▓▓█████▄ ▄▄▄ ██▀███ ▓█████ ███▄ █ ▄▄▄ // ▒██ ▒ ▒██▓ ██▒ ██ ▓██▒▓██▒▒██▀ ██▌ ▒████▄ ▓██ ▒ ██▒▓█ ▀ ██ ▀█ █ ▒████▄ // ░ ▓██▄ ▒██▒ ██░▓██ ▒██░▒██▒░██ █▌ ▒██ ▀█▄ ▓██ ░▄█ ▒▒███ ▓██ ▀█ ██▒▒██ ▀█▄ // ▒ ██▒░██ █▀ ░▓▓█ ░██░░██░░▓█▄ ▌ ░██▄▄▄▄██ ▒██▀▀█▄ ▒▓█ ▄ ▓██▒ ▐▌██▒░██▄▄▄▄██ // ▒██████▒▒░▒███▒█▄ ▒▒█████▓ ░██░░▒████▓ ▓█ ▓██▒░██▓ ▒██▒░▒████▒▒██░ ▓██░ ▓█ ▓██▒ // ▒ ▒▓▒ ▒ ░░░ ▒▒░ ▒ ░▒▓▒ ▒ ▒ ░▓ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░ ▒ ▒ ▒▒ ▓▒█░ // ░ ░▒ ░ ░ ░ ▒░ ░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░ ░ ░ ░░ ░░ ░ ▒░ ▒ ▒▒ ░ // ░ ░ ░ ░ ░ ░░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ▒ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ // Squid game is a smart contract that programs a deflationary NFT, implemented as a game. // In this game, there will be n rounds and 2**n tokens. // Each round, a random 50% of the tokens will be burned. // After the last round, there will be one token remaining, and the owner will be able to // claim the treasury, which consists of the mint price paid for each token.
LineComment
claimCreatorReward
function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; }
/** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 6144, 6470 ] }
5,337
SquidArena
contracts/SquidArena.sol
0x0cc34f2ee846c97e6a2c31b8de8314781d779358
Solidity
SquidArena
contract SquidArena is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 8 * 10**16; // Price to mint a single token uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator (Kovan) 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Contract Token (Kovan) ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 2 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + _count <= MAX_ELEMENTS, 'Max limit'); require(total <= MAX_ELEMENTS, 'Sale end'); require(_count <= MAX_BY_MINT, 'Exceeds number'); require(msg.value >= price(_count), 'Value below price'); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
// ██████ █████ █ ██ ██▓▓█████▄ ▄▄▄ ██▀███ ▓█████ ███▄ █ ▄▄▄ // ▒██ ▒ ▒██▓ ██▒ ██ ▓██▒▓██▒▒██▀ ██▌ ▒████▄ ▓██ ▒ ██▒▓█ ▀ ██ ▀█ █ ▒████▄ // ░ ▓██▄ ▒██▒ ██░▓██ ▒██░▒██▒░██ █▌ ▒██ ▀█▄ ▓██ ░▄█ ▒▒███ ▓██ ▀█ ██▒▒██ ▀█▄ // ▒ ██▒░██ █▀ ░▓▓█ ░██░░██░░▓█▄ ▌ ░██▄▄▄▄██ ▒██▀▀█▄ ▒▓█ ▄ ▓██▒ ▐▌██▒░██▄▄▄▄██ // ▒██████▒▒░▒███▒█▄ ▒▒█████▓ ░██░░▒████▓ ▓█ ▓██▒░██▓ ▒██▒░▒████▒▒██░ ▓██░ ▓█ ▓██▒ // ▒ ▒▓▒ ▒ ░░░ ▒▒░ ▒ ░▒▓▒ ▒ ▒ ░▓ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░ ▒ ▒ ▒▒ ▓▒█░ // ░ ░▒ ░ ░ ░ ▒░ ░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░ ░ ░ ░░ ░░ ░ ▒░ ▒ ▒▒ ░ // ░ ░ ░ ░ ░ ░░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ▒ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ // Squid game is a smart contract that programs a deflationary NFT, implemented as a game. // In this game, there will be n rounds and 2**n tokens. // Each round, a random 50% of the tokens will be burned. // After the last round, there will be one token remaining, and the owner will be able to // claim the treasury, which consists of the mint price paid for each token.
LineComment
_getRandomNumber
function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); }
/** * Requests randomness */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 6509, 6751 ] }
5,338
SquidArena
contracts/SquidArena.sol
0x0cc34f2ee846c97e6a2c31b8de8314781d779358
Solidity
SquidArena
contract SquidArena is ERC721, ERC721Enumerable, Ownable, ERC721Pausable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; // Defines the different stages of the game enum GameState { PREMINT, // Before the game, when minting is not available yet. MINTING, // Before the game, when minting is available to the public. STARTED, // During one of the rounds of the game. FINISHED // After the game, when there is a winner. } // Global vars bool private _isAdminBurnEnabled = false; // Flag to indicate whether the admin should be able to burn the supply bool private creatorHasClaimed = false; // Flag to indicate whether the creator has claimed reward uint256 public currentRound = 0; // Tracks the current round uint256 public currentBurn = 0; // Tracks the number of burns that have been requested so far string public baseTokenURI; // Base token URI address public winnerAddress; // The address of the winner of the game GameState public gameState; // The current state of the game // Constants uint256 public constant NUM_ROUNDS = 7; // Number of rounds this game will last uint256 public constant MAX_ELEMENTS = 2**NUM_ROUNDS; // Max number of tokens minted uint256 public constant PRICE = 8 * 10**16; // Price to mint a single token uint256 public constant MAX_BY_MINT = 5; // Max number of tokens to be minted in a single transaction uint256 public constant CREATOR_PERCENTAGE = 20; // Percentage given to creators constructor(string memory baseURI) ERC721('Squid Arena', 'SQUID') VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator (Kovan) 0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Contract Token (Kovan) ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 2 LINK (Varies by network) setBaseURI(baseURI); pause(true); gameState = GameState.PREMINT; } modifier saleIsOpen() { require(_totalSupply() <= MAX_ELEMENTS, 'Sale end'); if (_msgSender() != owner()) { require(!paused(), 'Pausable: paused'); } _; } function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } function totalMint() public view returns (uint256) { return _totalSupply(); } function mint(address _to, uint256 _count) public payable saleIsOpen { uint256 total = _totalSupply(); require(total + _count <= MAX_ELEMENTS, 'Max limit'); require(total <= MAX_ELEMENTS, 'Sale end'); require(_count <= MAX_BY_MINT, 'Exceeds number'); require(msg.value >= price(_count), 'Value below price'); for (uint256 i = 0; i < _count; i++) { _mintAnElement(_to); } } function _mintAnElement(address _to) private { uint256 id = _totalSupply(); _tokenIdTracker.increment(); _safeMint(_to, id); } function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function pause(bool val) public onlyOwner { if (val == true) { _pause(); gameState = GameState.PREMINT; } else { _unpause(); gameState = GameState.MINTING; } } // This is a last resort fail safe function. // If for any reason the contract doesn't sell out // or needs to be shutdown. This allows the administrators // to be able to to withdraw all funds from the contract // so that it can be disbursed back to the original minters function pullRug() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(''); require(success, 'Transfer failed'); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { /* While the burn is happening, disable token transfers for all users * other than the admin. The admin needs transfer privilages during * the burn because burning is *technically* a transfer between owner * of the NFT -> the NULL Address. **/ if (_msgSender() != owner()) { require(currentRound == currentBurn, 'disabled'); } super._beforeTokenTransfer(from, to, tokenId); } function startBurn() public onlyOwner { if (currentRound == 0) { require(totalSupply() == MAX_ELEMENTS, 'Not all tokens minted'); } require(totalSupply() > 1, 'Game finished'); _getRandomNumber(); } /** * Claim winner: * - Requires creatorHasClaimed to be true * - Requires 1 token to be left * - Requires creator to have * - Withdraws the rest of the balance to contract owner */ function claimWinnerReward() public { require(creatorHasClaimed == true, 'Creator reward not claimed'); require(totalSupply() == 1, 'Game not finished'); require(_msgSender() == winnerAddress, 'Not winner'); _widthdraw(winnerAddress, address(this).balance); } /** * Claim creator: * - Requires creatorHasClaimed to be false * - Withdraws CREATOR_PERCENTAGE / 100 * POT to contract owner * - Sets creatorHasClaimed to true */ function claimCreatorReward() public onlyOwner { require(creatorHasClaimed == false, 'Creator reward claimed'); uint256 balance = address(this).balance; uint256 creatorReward = SafeMath.mul(SafeMath.div(balance, 100), CREATOR_PERCENTAGE); _widthdraw(owner(), creatorReward); creatorHasClaimed = true; } /** * Requests randomness */ function _getRandomNumber() internal returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, 'Not enough LINK'); // Increment the current burn currentBurn += 1; return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; } uint256[] tokensToBurn; function burnSupply() public onlyOwner { require(_isAdminBurnEnabled, 'Burn disabled'); require(totalSupply() > 1, 'Game is over'); uint256 startingIndex = randomResult % 2; // The first burn should turn the game state to started. gameState = GameState.STARTED; uint256 currentSupplyLength = totalSupply(); // Create an array of tokens to burn // (skipping every other item starting from startingIndex) for (uint256 index = startingIndex; index < currentSupplyLength; index += 2) { tokensToBurn.push(tokenByIndex(index)); } // Burns all tokens in array for (uint256 i = 0; i < tokensToBurn.length; i++) { _burn(tokensToBurn[i]); } // Increment to the next round currentRound += 1; // If we have a winner, set the current winner field to the address // of the owner that owns the last remaining NFT. if (totalSupply() == 1) { winnerAddress = ownerOf(tokenByIndex(0)); // Turn the game state to finished. gameState = GameState.FINISHED; } // clean up after yourself delete tokensToBurn; // After a burn is completed, disable the admin from // triggering another burn _isAdminBurnEnabled = false; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
// ██████ █████ █ ██ ██▓▓█████▄ ▄▄▄ ██▀███ ▓█████ ███▄ █ ▄▄▄ // ▒██ ▒ ▒██▓ ██▒ ██ ▓██▒▓██▒▒██▀ ██▌ ▒████▄ ▓██ ▒ ██▒▓█ ▀ ██ ▀█ █ ▒████▄ // ░ ▓██▄ ▒██▒ ██░▓██ ▒██░▒██▒░██ █▌ ▒██ ▀█▄ ▓██ ░▄█ ▒▒███ ▓██ ▀█ ██▒▒██ ▀█▄ // ▒ ██▒░██ █▀ ░▓▓█ ░██░░██░░▓█▄ ▌ ░██▄▄▄▄██ ▒██▀▀█▄ ▒▓█ ▄ ▓██▒ ▐▌██▒░██▄▄▄▄██ // ▒██████▒▒░▒███▒█▄ ▒▒█████▓ ░██░░▒████▓ ▓█ ▓██▒░██▓ ▒██▒░▒████▒▒██░ ▓██░ ▓█ ▓██▒ // ▒ ▒▓▒ ▒ ░░░ ▒▒░ ▒ ░▒▓▒ ▒ ▒ ░▓ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░ ▒ ▒ ▒▒ ▓▒█░ // ░ ░▒ ░ ░ ░ ▒░ ░ ░░▒░ ░ ░ ▒ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░ ░ ░ ░░ ░░ ░ ▒░ ▒ ▒▒ ░ // ░ ░ ░ ░ ░ ░░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░ ░ ▒ // ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ // ░ // Squid game is a smart contract that programs a deflationary NFT, implemented as a game. // In this game, there will be n rounds and 2**n tokens. // Each round, a random 50% of the tokens will be burned. // After the last round, there will be one token remaining, and the owner will be able to // claim the treasury, which consists of the mint price paid for each token.
LineComment
fulfillRandomness
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; // Since Chainlink has provided a verifiably random value, // that can be used for the burn, let the admin burn the supply. _isAdminBurnEnabled = true; }
/** * Callback function used by VRF Coordinator */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 6812, 7099 ] }
5,339
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
doesEntityExist
function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); }
// // Entity functions //
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 1304, 1508 ] }
5,340
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
getIssuerAddressList
function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; }
// // Issuer functions // // Return all tracked issuer addresses
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 3161, 3283 ] }
5,341
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
addIssuer
function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); }
// Add an issuer and set active value to true
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 3335, 3604 ] }
5,342
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
removeIssuer
function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); }
// Remove an issuer
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 3630, 4080 ] }
5,343
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
listIssuer
function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); }
// Set previously delisted issuer to listed
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 4130, 4402 ] }
5,344
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
delistIssuer
function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); }
// Set previously listed issuer to delisted
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 4452, 4728 ] }
5,345
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
getTokenAddressList
function getTokenAddressList() public view returns (address[]) { return tokenAddressList; }
// // Token functions // // Return all tracked token addresses
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 5218, 5338 ] }
5,346
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
addNewToken
function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; }
/** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 6285, 7374 ] }
5,347
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
addExistingToken
function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); }
/** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 7792, 8305 ] }
5,348
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
removeToken
function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); }
// Remove a token
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 8329, 8766 ] }
5,349
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
listToken
function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); }
// Set previously delisted token to listed
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 8815, 9078 ] }
5,350
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
delistToken
function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); }
// Set previously listed token to delisted
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 9127, 9394 ] }
5,351
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
pauseToken
function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); }
// // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 9921, 10042 ] }
5,352
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
unpauseToken
function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); }
// Allow unpausing a listed PoaToken
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 10085, 10201 ] }
5,353
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
terminateToken
function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); }
// Allow terminating a listed PoaToken
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 10246, 10366 ] }
5,354
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
upgradeToken
function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; }
// upgrade an existing PoaToken proxy to what is stored in ContractRegistry
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 10448, 10675 ] }
5,355
PoaManager
contracts/PoaManager.sol
0x9b97d864543f0e755228b27a552ed145f3d1e964
Solidity
PoaManager
contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _totalSupply ); IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
upgradeCrowdsale
function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; }
// upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry
LineComment
v0.4.24+commit.e67f0147
bzzr://68fb153aab6ea446eb7f0a299aec399928ed8d899dc798bc3cd6c9d99c5193e3
{ "func_code_index": [ 10761, 11000 ] }
5,356
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
distribute
function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); }
/** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 838, 1017 ] }
5,357
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
burn
function burn(address _from, uint256 _amount) public { _burn(_from, _amount); }
/** * @dev Burning token */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 1069, 1167 ] }
5,358
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
changeTaxRatio
function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; }
/** * @dev Tokenomic decition from governance */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 1240, 1342 ] }
5,359
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
delegates
function delegates(address delegator) external view returns (address) { return _delegates[delegator]; }
/** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 2793, 2947 ] }
5,360
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
delegate
function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); }
/** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 3086, 3195 ] }
5,361
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
delegateBySig
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
/** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 3624, 4831 ] }
5,362
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
getCurrentVotes
function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
/** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 5027, 5287 ] }
5,363
VOTEpoolchef
contracts/VOTEpoolToken.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolToken
contract VOTEpoolToken is ERC20("VOTEpool.org", "VOT"), Ownable { using SafeMath for uint256; uint8 public taxRatio = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(msg.sender, taxAmount); return super.transfer(recipient, amount.sub(taxAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 taxAmount = amount.mul(taxRatio).div(100); _burn(sender, taxAmount); return super.transferFrom(sender, recipient, amount.sub(taxAmount)); } /** * @dev Chef distributes newly generated VOTEpoolToken to each farmmers * "onlyOwner" = "Only Chef" */ function distribute(address _to, uint256 _amount) public onlyOwner { _distribute(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "VOTEpool.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VOTEpool.org::delegateBySig: invalid nonce"); require(now <= expiry, "VOTEpool.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "VOTEpool.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
getPriorVotes
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "VOTEpool.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; }
/** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 5713, 6886 ] }
5,364
HashStore
HashStore.sol
0x6a9633ac967c6da43bca00a601d9cd8c74d4c099
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @return the address of the owner. */
NatSpecMultiLine
v0.5.0+commit.1d4f565a
bzzr://032b5bad7acee1dbf72a7cd9aa01c54e0cf632d0f6ba33b031bb3d609ccf5487
{ "func_code_index": [ 457, 541 ] }
5,365
HashStore
HashStore.sol
0x6a9633ac967c6da43bca00a601d9cd8c74d4c099
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
isOwner
function isOwner() public view returns (bool) { return msg.sender == _owner; }
/** * @return true if `msg.sender` is the owner of the contract. */
NatSpecMultiLine
v0.5.0+commit.1d4f565a
bzzr://032b5bad7acee1dbf72a7cd9aa01c54e0cf632d0f6ba33b031bb3d609ccf5487
{ "func_code_index": [ 792, 889 ] }
5,366
HashStore
HashStore.sol
0x6a9633ac967c6da43bca00a601d9cd8c74d4c099
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.5.0+commit.1d4f565a
bzzr://032b5bad7acee1dbf72a7cd9aa01c54e0cf632d0f6ba33b031bb3d609ccf5487
{ "func_code_index": [ 1061, 1175 ] }
5,367
HashStore
HashStore.sol
0x6a9633ac967c6da43bca00a601d9cd8c74d4c099
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.5.0+commit.1d4f565a
bzzr://032b5bad7acee1dbf72a7cd9aa01c54e0cf632d0f6ba33b031bb3d609ccf5487
{ "func_code_index": [ 1320, 1512 ] }
5,368
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
mint
function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; }
/** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 2201, 2830 ] }
5,369
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
minterAllowance
function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; }
/** * @dev Get minter allowance for an account * minter The address of the minter */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 3124, 3247 ] }
5,370
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
isMinter
function isMinter(address _account) public view returns (bool) { return minters[_account]; }
/** * @dev Checks ifis a minter * The address to check */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 3334, 3445 ] }
5,371
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev Get totalSupply of token */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 3637, 3733 ] }
5,372
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; }
/** * @dev Get token balance of an account * address The account */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 3826, 3930 ] }
5,373
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 4051, 4328 ] }
5,374
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 4752, 4901 ] }
5,375
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
transfer
function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 5095, 5233 ] }
5,376
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
configureMinter
function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; }
/** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 5471, 5777 ] }
5,377
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
removeMinter
function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; }
/** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 5944, 6163 ] }
5,378
FiatTokenV1
openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
0x75baa52804ddffea0e442ee90231d7fa2612faa0
Solidity
FiatTokenV1
contract FiatTokenV1 is Ownable, ERC20, Pausable, Blacklistable { using SafeMath for uint256; uint constant MAX_UINT = 2**256 - 1; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string _name, string _symbol, string _currency, uint8 _decimals, address _masterMinter, address _pauser, address _blacklister, address _owner, address _account, address account ) public { require(!initialized); require(_masterMinter != address(0)); require(_pauser != address(0)); require(_blacklister != address(0)); require(_owner != address(0)); name = _name; symbol = _symbol; currency = _currency; decimals = _decimals; masterMinter = _masterMinter; pauser = _pauser; blacklister = _blacklister; setOwner(_owner); initialized = true; } /** * @dev Throws if called by anyother than a minter */ modifier onlyMinters() { require(minters[msg.sender] == true); _; } /** * @dev Function to mint tokens * _to The address that will receive the minted tokens. * _amount The amount of tokens to mint. Must be less than or equal to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Throws if called by anyother than the masterMinter */ modifier onlyMasterMinter() { require(msg.sender == masterMinter); _; } /** * @dev Get minter allowance for an account * minter The address of the minter */ function minterAllowance(address minter) public view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks ifis a minter * The address to check */ function isMinter(address _account) public view returns (bool) { return minters[_account]; } /** * @dev Get allowed amount for an account * owner address Theowner * spender address Thespender */ /** * @dev Get totalSupply of token */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * address The account */ function balanceOf(address _owner) public view returns (uint256 balance) { return MAX_UINT; } /** * @dev Adds blacklisted check to approve * @return True if the operation was successful. */ function approve(address _spender, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_spender) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return MAX_UINT; } /** * @dev Transfer tokens from one address to another. * _from address The address which you want to send tokens from * _to address The address which you want to transfer to * _value uint256 the amount of tokens to be transferred * @return bool success */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { Transfer(_from, _to, _value); return true; } /** * @dev transfer token for a specified address * _to The address to transfer to. * _value The amount to be transferred. * @return bool success */ function transfer(address _to, uint _value) public returns (bool) { Transfer(msg.sender, _to, _value); return true; } /** * @dev Function to add/update a new minter * minter The address of the minter * minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) whenNotPaused onlyMasterMinter public returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) onlyMasterMinter public returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) onlyOwner public { require(_newMasterMinter != address(0)); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } }
/** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */
NatSpecMultiLine
burn
function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); }
/** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter'sbalance * _amount uint256 the amount of tokens to be burned */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
MIT
bzzr://0c44e375130918edc27bee9d9115d6033f62ae57b85032b68873a251c4c8500f
{ "func_code_index": [ 6439, 6866 ] }
5,379
CaptureTheFlag
CaptureTheFlag.sol
0x4d955895c61d6a7a2dc85f2feedbda6489c6f67d
Solidity
CaptureTheFlag
contract CaptureTheFlag is Ownable { address owner; event WhereAmI(address, string); Log TransferLog; uint256 public jackpot = 0; uint256 MinDeposit = 1 ether; uint256 minInvestment = 1 ether; uint public sumInvested; uint public sumDividend; bool inProgress = false; mapping(address => uint256) public balances; struct Osakako { address me; } struct investor { uint256 investment; string username; } event Transfer( uint amount, bytes32 message, address target, address currentOwner ); mapping(address => investor) public investors; function CaptureTheFlag(address _log) public { TransferLog = Log(_log); owner = msg.sender; } // Payday!! function() public payable { if( msg.value >= jackpot ){ owner = msg.sender; } jackpot += msg.value; // add to our jackpot } modifier onlyUsers() { require(users[msg.sender] != false); _; } mapping(address => bool) users; function registerAllPlayers(address[] players) public onlyOwner { require(inProgress == false); for (uint32 i = 0; i < players.length; i++) { users[players[i]] = true; } inProgress = true; } function takeAll() external onlyOwner { msg.sender.transfer(this.balance); // payout jackpot = 0; // reset the jackpot } // Payday!! // Bank function Deposit() public payable { if ( msg.value >= MinDeposit ){ balances[msg.sender] += msg.value; TransferLog.addMessage(" Deposit "); } } function CashOut(uint amount) public onlyUsers { if( amount <= balances[msg.sender] ){ if(msg.sender.call.value(amount)()){ balances[msg.sender] -= amount; TransferLog.addMessage(" CashOut "); } } } // Bank //--- Hmmm function invest() public payable { if ( msg.value >= minInvestment ){ investors[msg.sender].investment += msg.value; } } function divest(uint amount) public onlyUsers { if ( investors[msg.sender].investment == 0 || amount == 0) { revert(); } // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) public protected onlyUsers { if(!target.call.value(amount)()){ revert(); } Transfer(amount, message, target, currentOwner); } //--- Empty String Literal function osaka(string message) public onlyUsers { Osakako osakako; osakako.me = msg.sender; WhereAmI(osakako.me, message); } function tryMeLast() public payable onlyUsers { if ( msg.value >= 0.1 ether ) { uint256 multi = 0; uint256 amountToTransfer = 0; for (var i = 0; i < 2 * msg.value; i++) { multi = i * 2; if (multi < amountToTransfer) { break; } amountToTransfer = multi; } msg.sender.transfer(amountToTransfer); } } function easyMode( address addr ) external payable onlyUsers { if ( msg.value >= this.balance ){ addr.transfer(this.balance + msg.value); } } }
function() public payable { if( msg.value >= jackpot ){ owner = msg.sender; } jackpot += msg.value; // add to our jackpot }
// Payday!!
LineComment
v0.4.12+commit.194ff033
Unlicense
bzzr://9b8db614363f971c49440d4d498b8c0b653688f10fdeacb9a9d722b11172bc63
{ "func_code_index": [ 754, 905 ] }
5,380
CaptureTheFlag
CaptureTheFlag.sol
0x4d955895c61d6a7a2dc85f2feedbda6489c6f67d
Solidity
CaptureTheFlag
contract CaptureTheFlag is Ownable { address owner; event WhereAmI(address, string); Log TransferLog; uint256 public jackpot = 0; uint256 MinDeposit = 1 ether; uint256 minInvestment = 1 ether; uint public sumInvested; uint public sumDividend; bool inProgress = false; mapping(address => uint256) public balances; struct Osakako { address me; } struct investor { uint256 investment; string username; } event Transfer( uint amount, bytes32 message, address target, address currentOwner ); mapping(address => investor) public investors; function CaptureTheFlag(address _log) public { TransferLog = Log(_log); owner = msg.sender; } // Payday!! function() public payable { if( msg.value >= jackpot ){ owner = msg.sender; } jackpot += msg.value; // add to our jackpot } modifier onlyUsers() { require(users[msg.sender] != false); _; } mapping(address => bool) users; function registerAllPlayers(address[] players) public onlyOwner { require(inProgress == false); for (uint32 i = 0; i < players.length; i++) { users[players[i]] = true; } inProgress = true; } function takeAll() external onlyOwner { msg.sender.transfer(this.balance); // payout jackpot = 0; // reset the jackpot } // Payday!! // Bank function Deposit() public payable { if ( msg.value >= MinDeposit ){ balances[msg.sender] += msg.value; TransferLog.addMessage(" Deposit "); } } function CashOut(uint amount) public onlyUsers { if( amount <= balances[msg.sender] ){ if(msg.sender.call.value(amount)()){ balances[msg.sender] -= amount; TransferLog.addMessage(" CashOut "); } } } // Bank //--- Hmmm function invest() public payable { if ( msg.value >= minInvestment ){ investors[msg.sender].investment += msg.value; } } function divest(uint amount) public onlyUsers { if ( investors[msg.sender].investment == 0 || amount == 0) { revert(); } // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) public protected onlyUsers { if(!target.call.value(amount)()){ revert(); } Transfer(amount, message, target, currentOwner); } //--- Empty String Literal function osaka(string message) public onlyUsers { Osakako osakako; osakako.me = msg.sender; WhereAmI(osakako.me, message); } function tryMeLast() public payable onlyUsers { if ( msg.value >= 0.1 ether ) { uint256 multi = 0; uint256 amountToTransfer = 0; for (var i = 0; i < 2 * msg.value; i++) { multi = i * 2; if (multi < amountToTransfer) { break; } amountToTransfer = multi; } msg.sender.transfer(amountToTransfer); } } function easyMode( address addr ) external payable onlyUsers { if ( msg.value >= this.balance ){ addr.transfer(this.balance + msg.value); } } }
Deposit
function Deposit() public payable { if ( msg.value >= MinDeposit ){ balances[msg.sender] += msg.value; TransferLog.addMessage(" Deposit "); } }
// Payday!! // Bank
LineComment
v0.4.12+commit.194ff033
Unlicense
bzzr://9b8db614363f971c49440d4d498b8c0b653688f10fdeacb9a9d722b11172bc63
{ "func_code_index": [ 1421, 1594 ] }
5,381
CaptureTheFlag
CaptureTheFlag.sol
0x4d955895c61d6a7a2dc85f2feedbda6489c6f67d
Solidity
CaptureTheFlag
contract CaptureTheFlag is Ownable { address owner; event WhereAmI(address, string); Log TransferLog; uint256 public jackpot = 0; uint256 MinDeposit = 1 ether; uint256 minInvestment = 1 ether; uint public sumInvested; uint public sumDividend; bool inProgress = false; mapping(address => uint256) public balances; struct Osakako { address me; } struct investor { uint256 investment; string username; } event Transfer( uint amount, bytes32 message, address target, address currentOwner ); mapping(address => investor) public investors; function CaptureTheFlag(address _log) public { TransferLog = Log(_log); owner = msg.sender; } // Payday!! function() public payable { if( msg.value >= jackpot ){ owner = msg.sender; } jackpot += msg.value; // add to our jackpot } modifier onlyUsers() { require(users[msg.sender] != false); _; } mapping(address => bool) users; function registerAllPlayers(address[] players) public onlyOwner { require(inProgress == false); for (uint32 i = 0; i < players.length; i++) { users[players[i]] = true; } inProgress = true; } function takeAll() external onlyOwner { msg.sender.transfer(this.balance); // payout jackpot = 0; // reset the jackpot } // Payday!! // Bank function Deposit() public payable { if ( msg.value >= MinDeposit ){ balances[msg.sender] += msg.value; TransferLog.addMessage(" Deposit "); } } function CashOut(uint amount) public onlyUsers { if( amount <= balances[msg.sender] ){ if(msg.sender.call.value(amount)()){ balances[msg.sender] -= amount; TransferLog.addMessage(" CashOut "); } } } // Bank //--- Hmmm function invest() public payable { if ( msg.value >= minInvestment ){ investors[msg.sender].investment += msg.value; } } function divest(uint amount) public onlyUsers { if ( investors[msg.sender].investment == 0 || amount == 0) { revert(); } // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) public protected onlyUsers { if(!target.call.value(amount)()){ revert(); } Transfer(amount, message, target, currentOwner); } //--- Empty String Literal function osaka(string message) public onlyUsers { Osakako osakako; osakako.me = msg.sender; WhereAmI(osakako.me, message); } function tryMeLast() public payable onlyUsers { if ( msg.value >= 0.1 ether ) { uint256 multi = 0; uint256 amountToTransfer = 0; for (var i = 0; i < 2 * msg.value; i++) { multi = i * 2; if (multi < amountToTransfer) { break; } amountToTransfer = multi; } msg.sender.transfer(amountToTransfer); } } function easyMode( address addr ) external payable onlyUsers { if ( msg.value >= this.balance ){ addr.transfer(this.balance + msg.value); } } }
invest
function invest() public payable { if ( msg.value >= minInvestment ){ investors[msg.sender].investment += msg.value; } }
// Bank //--- Hmmm
LineComment
v0.4.12+commit.194ff033
Unlicense
bzzr://9b8db614363f971c49440d4d498b8c0b653688f10fdeacb9a9d722b11172bc63
{ "func_code_index": [ 1871, 2014 ] }
5,382
CaptureTheFlag
CaptureTheFlag.sol
0x4d955895c61d6a7a2dc85f2feedbda6489c6f67d
Solidity
CaptureTheFlag
contract CaptureTheFlag is Ownable { address owner; event WhereAmI(address, string); Log TransferLog; uint256 public jackpot = 0; uint256 MinDeposit = 1 ether; uint256 minInvestment = 1 ether; uint public sumInvested; uint public sumDividend; bool inProgress = false; mapping(address => uint256) public balances; struct Osakako { address me; } struct investor { uint256 investment; string username; } event Transfer( uint amount, bytes32 message, address target, address currentOwner ); mapping(address => investor) public investors; function CaptureTheFlag(address _log) public { TransferLog = Log(_log); owner = msg.sender; } // Payday!! function() public payable { if( msg.value >= jackpot ){ owner = msg.sender; } jackpot += msg.value; // add to our jackpot } modifier onlyUsers() { require(users[msg.sender] != false); _; } mapping(address => bool) users; function registerAllPlayers(address[] players) public onlyOwner { require(inProgress == false); for (uint32 i = 0; i < players.length; i++) { users[players[i]] = true; } inProgress = true; } function takeAll() external onlyOwner { msg.sender.transfer(this.balance); // payout jackpot = 0; // reset the jackpot } // Payday!! // Bank function Deposit() public payable { if ( msg.value >= MinDeposit ){ balances[msg.sender] += msg.value; TransferLog.addMessage(" Deposit "); } } function CashOut(uint amount) public onlyUsers { if( amount <= balances[msg.sender] ){ if(msg.sender.call.value(amount)()){ balances[msg.sender] -= amount; TransferLog.addMessage(" CashOut "); } } } // Bank //--- Hmmm function invest() public payable { if ( msg.value >= minInvestment ){ investors[msg.sender].investment += msg.value; } } function divest(uint amount) public onlyUsers { if ( investors[msg.sender].investment == 0 || amount == 0) { revert(); } // no need to test, this will throw if amount > investment investors[msg.sender].investment -= amount; sumInvested -= amount; this.loggedTransfer(amount, "", msg.sender, owner); } function loggedTransfer(uint amount, bytes32 message, address target, address currentOwner) public protected onlyUsers { if(!target.call.value(amount)()){ revert(); } Transfer(amount, message, target, currentOwner); } //--- Empty String Literal function osaka(string message) public onlyUsers { Osakako osakako; osakako.me = msg.sender; WhereAmI(osakako.me, message); } function tryMeLast() public payable onlyUsers { if ( msg.value >= 0.1 ether ) { uint256 multi = 0; uint256 amountToTransfer = 0; for (var i = 0; i < 2 * msg.value; i++) { multi = i * 2; if (multi < amountToTransfer) { break; } amountToTransfer = multi; } msg.sender.transfer(amountToTransfer); } } function easyMode( address addr ) external payable onlyUsers { if ( msg.value >= this.balance ){ addr.transfer(this.balance + msg.value); } } }
osaka
function osaka(string message) public onlyUsers { Osakako osakako; osakako.me = msg.sender; WhereAmI(osakako.me, message); }
//--- Empty String Literal
LineComment
v0.4.12+commit.194ff033
Unlicense
bzzr://9b8db614363f971c49440d4d498b8c0b653688f10fdeacb9a9d722b11172bc63
{ "func_code_index": [ 2643, 2788 ] }
5,383
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
totalSupply
function totalSupply() constant returns (uint256 supply) {}
/// @return total amount of tokens
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 60, 124 ] }
5,384
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @param _owner The address from which the balance will be retrieved /// @return The balance
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 232, 309 ] }
5,385
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transfer
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 546, 623 ] }
5,386
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 946, 1042 ] }
5,387
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
approve
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 1326, 1407 ] }
5,388
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
Token
contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
/// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent
NatSpecSingleLine
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 1615, 1712 ] }
5,389
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
BTSCoin
contract BTSCoin is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function BTSCoin( ) { balances[msg.sender] = 6122013; // Give the creator all initial tokens (100000 for example) totalSupply = 6122013; // Update total supply (100000 for example) name = "BTS Coin"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "BANG"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
BTSCoin
function BTSCoin( ) { balances[msg.sender] = 6122013; // Give the creator all initial tokens (100000 for example) totalSupply = 6122013; // Update total supply (100000 for example) name = "BTS Coin"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "BANG"; // Set the symbol for display purposes }
//human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
LineComment
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 1156, 1699 ] }
5,390
BTSCoin
BTSCoin.sol
0x6c897d1edbcf3948352dcab3d86c51692b46be32
Solidity
BTSCoin
contract BTSCoin is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function BTSCoin( ) { balances[msg.sender] = 6122013; // Give the creator all initial tokens (100000 for example) totalSupply = 6122013; // Update total supply (100000 for example) name = "BTS Coin"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "BANG"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
//name this contract whatever you'd like
LineComment
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; }
/* Approves and then calls the receiving contract */
Comment
v0.4.20+commit.3155dd80
bzzr://dd12743b3fbb960aa3a5b17cbfe63e9a7cc1dd2643eac942dca0a24b0d8d3963
{ "func_code_index": [ 1760, 2565 ] }
5,391
crad
crad_cash_latest.sol
0x608f006b6813f97097372d0d31fb0f11d1ca3e4e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
/** * @dev Multiplies two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.7+commit.6da8b019
bzzr://38e23b29c8b912151aa05543e9da91e2e4ca49c62a8872ddf63998a2116fc6b2
{ "func_code_index": [ 106, 544 ] }
5,392
crad
crad_cash_latest.sol
0x608f006b6813f97097372d0d31fb0f11d1ca3e4e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */
NatSpecMultiLine
v0.5.7+commit.6da8b019
bzzr://38e23b29c8b912151aa05543e9da91e2e4ca49c62a8872ddf63998a2116fc6b2
{ "func_code_index": [ 674, 982 ] }
5,393
crad
crad_cash_latest.sol
0x608f006b6813f97097372d0d31fb0f11d1ca3e4e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; }
/** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.5.7+commit.6da8b019
bzzr://38e23b29c8b912151aa05543e9da91e2e4ca49c62a8872ddf63998a2116fc6b2
{ "func_code_index": [ 1115, 1270 ] }
5,394
crad
crad_cash_latest.sol
0x608f006b6813f97097372d0d31fb0f11d1ca3e4e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
/** * @dev Adds two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.7+commit.6da8b019
bzzr://38e23b29c8b912151aa05543e9da91e2e4ca49c62a8872ddf63998a2116fc6b2
{ "func_code_index": [ 1353, 1508 ] }
5,395
crad
crad_cash_latest.sol
0x608f006b6813f97097372d0d31fb0f11d1ca3e4e
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
/** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */
NatSpecMultiLine
v0.5.7+commit.6da8b019
bzzr://38e23b29c8b912151aa05543e9da91e2e4ca49c62a8872ddf63998a2116fc6b2
{ "func_code_index": [ 1664, 1793 ] }
5,396
Tokenizator
contracts/Tokenizator.sol
0x6a190eef45f589373a463afb3b90493e696c45e2
Solidity
Tokenizator
contract Tokenizator is ERC721Token { using SafeMath for uint256; struct TokenMetadata { bytes32 name; uint256 creationTimestamp; address creator; string description; string base64Image; } uint256 public lockTimestamp; mapping(uint256 => TokenMetadata) public tokenMetadata; function Tokenizator() { lockTimestamp = now; } /** * @dev Public fuction to create a token, it creates only 1 token per hour * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function createToken( bytes32 _name, string _description, string _base64Image ) public { require(now > lockTimestamp); lockTimestamp = lockTimestamp.add(1 days); uint256 _tokenId = totalSupply().add(1); _mint(msg.sender, _tokenId); addTokenMetadata(_tokenId, _name, _description, _base64Image); } /** * @dev Internal function to add a the metadata of a token * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function addTokenMetadata( uint256 _tokenId, bytes32 _name, string _description, string _base64Image ) private { tokenMetadata[_tokenId] = TokenMetadata( _name, now, msg.sender, _description, _base64Image ); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { delete tokenMetadata[_tokenId]; super._burn(_tokenId); } }
/** * @title Tokenizator * @dev A ERC721 contract with token metadata, allows the creation of one token per day by any address. */
NatSpecMultiLine
createToken
function createToken( bytes32 _name, string _description, string _base64Image ) public { require(now > lockTimestamp); lockTimestamp = lockTimestamp.add(1 days); uint256 _tokenId = totalSupply().add(1); _mint(msg.sender, _tokenId); addTokenMetadata(_tokenId, _name, _description, _base64Image); }
/** * @dev Public fuction to create a token, it creates only 1 token per hour * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://7bc9ac8ad50c2cfea6455356e61ce63e1f57da274d9bf1ea07ba9080e6d4ea56
{ "func_code_index": [ 624, 959 ] }
5,397
Tokenizator
contracts/Tokenizator.sol
0x6a190eef45f589373a463afb3b90493e696c45e2
Solidity
Tokenizator
contract Tokenizator is ERC721Token { using SafeMath for uint256; struct TokenMetadata { bytes32 name; uint256 creationTimestamp; address creator; string description; string base64Image; } uint256 public lockTimestamp; mapping(uint256 => TokenMetadata) public tokenMetadata; function Tokenizator() { lockTimestamp = now; } /** * @dev Public fuction to create a token, it creates only 1 token per hour * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function createToken( bytes32 _name, string _description, string _base64Image ) public { require(now > lockTimestamp); lockTimestamp = lockTimestamp.add(1 days); uint256 _tokenId = totalSupply().add(1); _mint(msg.sender, _tokenId); addTokenMetadata(_tokenId, _name, _description, _base64Image); } /** * @dev Internal function to add a the metadata of a token * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function addTokenMetadata( uint256 _tokenId, bytes32 _name, string _description, string _base64Image ) private { tokenMetadata[_tokenId] = TokenMetadata( _name, now, msg.sender, _description, _base64Image ); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { delete tokenMetadata[_tokenId]; super._burn(_tokenId); } }
/** * @title Tokenizator * @dev A ERC721 contract with token metadata, allows the creation of one token per day by any address. */
NatSpecMultiLine
addTokenMetadata
function addTokenMetadata( uint256 _tokenId, bytes32 _name, string _description, string _base64Image ) private { tokenMetadata[_tokenId] = TokenMetadata( _name, now, msg.sender, _description, _base64Image ); }
/** * @dev Internal function to add a the metadata of a token * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://7bc9ac8ad50c2cfea6455356e61ce63e1f57da274d9bf1ea07ba9080e6d4ea56
{ "func_code_index": [ 1282, 1522 ] }
5,398
Tokenizator
contracts/Tokenizator.sol
0x6a190eef45f589373a463afb3b90493e696c45e2
Solidity
Tokenizator
contract Tokenizator is ERC721Token { using SafeMath for uint256; struct TokenMetadata { bytes32 name; uint256 creationTimestamp; address creator; string description; string base64Image; } uint256 public lockTimestamp; mapping(uint256 => TokenMetadata) public tokenMetadata; function Tokenizator() { lockTimestamp = now; } /** * @dev Public fuction to create a token, it creates only 1 token per hour * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function createToken( bytes32 _name, string _description, string _base64Image ) public { require(now > lockTimestamp); lockTimestamp = lockTimestamp.add(1 days); uint256 _tokenId = totalSupply().add(1); _mint(msg.sender, _tokenId); addTokenMetadata(_tokenId, _name, _description, _base64Image); } /** * @dev Internal function to add a the metadata of a token * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address * @param _name bytes32 Name of the token * @param _description string Description of the token * @param _base64Image string image in base64 */ function addTokenMetadata( uint256 _tokenId, bytes32 _name, string _description, string _base64Image ) private { tokenMetadata[_tokenId] = TokenMetadata( _name, now, msg.sender, _description, _base64Image ); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { delete tokenMetadata[_tokenId]; super._burn(_tokenId); } }
/** * @title Tokenizator * @dev A ERC721 contract with token metadata, allows the creation of one token per day by any address. */
NatSpecMultiLine
_burn
function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { delete tokenMetadata[_tokenId]; super._burn(_tokenId); }
/** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://7bc9ac8ad50c2cfea6455356e61ce63e1f57da274d9bf1ea07ba9080e6d4ea56
{ "func_code_index": [ 1647, 1785 ] }
5,399
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
getMultiplier
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } }
// Return reward multiplier over the given _from to _to block.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 3693, 4121 ] }
5,400
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
pendingVOTEpool
function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); }
// View function
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 4146, 4921 ] }
5,401
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
massUpdatePools
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
// Update reward variables for all pools. Be careful of gas spending!
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 5003, 5188 ] }
5,402
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
updatePool
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 5259, 6083 ] }
5,403
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
// Deposit
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 6102, 7407 ] }
5,404
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
withdraw
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
// Withdraw
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 7431, 8231 ] }
5,405
VOTEpoolchef
contracts/VOTEpoolchef.sol
0xc08455c084921285059658e73e7dd12dca655cae
Solidity
VOTEpoolchef
contract VOTEpoolchef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // allocation points uint256 lastRewardBlock; // Last block number uint256 accVOTPerShare; // Accumulated token per share } // VOTEpoolToken VOTEpoolToken public votepool; // Dev, event, and Buyback address. address public devaddr; address public eventaddr; address public buybackaddr; address public burnaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public votepoolPerBlock; uint256 public BONUS_MULTIPLIER = 2; uint256 public vaultratio = 5; uint8 public lptaxRatio = 15; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( VOTEpoolToken _votepool, address _devaddr, address _buybackaddr, address _burnaddr, address _eventaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { votepool = _votepool; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; eventaddr = _eventaddr; votepoolPerBlock = 100000000000000000; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _votepoolPerBlock) public onlyOwner { votepoolPerBlock = _votepoolPerBlock; } function changeVaultratio(uint256 _vaultratio) public onlyOwner { vaultratio = _vaultratio; } function changelpTaxRatio(uint8 _lptaxRatio) public onlyOwner { lptaxRatio = _lptaxRatio; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accVOTPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function function pendingVOTEpool(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVOTPerShare = pool.accVOTPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVOTPerShare = accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVOTPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votepoolReward = multiplier.mul(votepoolPerBlock).mul(pool.allocPoint).div(totalAllocPoint); votepool.distribute(devaddr, votepoolReward.div(20)); votepool.distribute(address(this), votepoolReward); pool.accVOTPerShare = pool.accVOTPerShare.add(votepoolReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 taxamount = 0; uint256 finalamount = 0; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } } if(_amount > 0) { vaultamount = _amount.div(1000).mul(vaultratio); finalamount = _amount.sub(vaultamount); taxamount = _amount.div(100).mul(lptaxRatio); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), finalamount.sub(taxamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); pool.lpToken.safeTransferFrom(address(msg.sender), burnaddr, taxamount); user.amount = user.amount.add(finalamount.sub(taxamount)); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVOTPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeVOTTransfer(msg.sender, pending); safeVOTTransfer(eventaddr, pending.div(20)); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accVOTPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // buyback address function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; } function burna(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } // dev address by the previous dev function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Eventpool address function eventa(address _eventaddr) public { require(msg.sender == devaddr, "ERROR"); eventaddr = _eventaddr; } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe VOTEpool transfer function safeVOTTransfer(address _to, uint256 _amount) internal { uint256 votepoolBal = votepool.balanceOf(address(this)); if (_amount > votepoolBal) { votepool.transfer(_to, votepoolBal); } else { votepool.transfer(_to, _amount); } } }
buybacka
function buybacka(address _buybackaddr) public { require(msg.sender == buybackaddr, "ERROR"); buybackaddr = _buybackaddr; }
// buyback address
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://1ce0ee090b1a8e321f03b68647dab77faed29fae35a235e657356d3ffc7bc914
{ "func_code_index": [ 8262, 8413 ] }
5,406