ERC721.sol 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)
  3. pragma solidity ^0.8.0;
  4. import "./IERC721.sol";
  5. import "./IERC721Receiver.sol";
  6. import "./extensions/IERC721Metadata.sol";
  7. import "../../utils/Address.sol";
  8. import "../../utils/Context.sol";
  9. import "../../utils/Strings.sol";
  10. import "../../utils/introspection/ERC165.sol";
  11. /**
  12. * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
  13. * the Metadata extension, but not including the Enumerable extension, which is available separately as
  14. * {ERC721Enumerable}.
  15. */
  16. contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
  17. using Address for address;
  18. using Strings for uint256;
  19. // Token name
  20. string private _name;
  21. // Token symbol
  22. string private _symbol;
  23. // Mapping from token ID to owner address
  24. mapping(uint256 => address) private _owners;
  25. // Mapping owner address to token count
  26. mapping(address => uint256) private _balances;
  27. // Mapping from token ID to approved address
  28. mapping(uint256 => address) private _tokenApprovals;
  29. // Mapping from owner to operator approvals
  30. mapping(address => mapping(address => bool)) private _operatorApprovals;
  31. /**
  32. * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
  33. */
  34. constructor(string memory name_, string memory symbol_) {
  35. _name = name_;
  36. _symbol = symbol_;
  37. }
  38. /**
  39. * @dev See {IERC165-supportsInterface}.
  40. */
  41. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
  42. return
  43. interfaceId == type(IERC721).interfaceId ||
  44. interfaceId == type(IERC721Metadata).interfaceId ||
  45. super.supportsInterface(interfaceId);
  46. }
  47. /**
  48. * @dev See {IERC721-balanceOf}.
  49. */
  50. function balanceOf(address owner) public view virtual override returns (uint256) {
  51. require(owner != address(0), "ERC721: address zero is not a valid owner");
  52. return _balances[owner];
  53. }
  54. /**
  55. * @dev See {IERC721-ownerOf}.
  56. */
  57. function ownerOf(uint256 tokenId) public view virtual override returns (address) {
  58. address owner = _owners[tokenId];
  59. require(owner != address(0), "ERC721: invalid token ID");
  60. return owner;
  61. }
  62. /**
  63. * @dev See {IERC721Metadata-name}.
  64. */
  65. function name() public view virtual override returns (string memory) {
  66. return _name;
  67. }
  68. /**
  69. * @dev See {IERC721Metadata-symbol}.
  70. */
  71. function symbol() public view virtual override returns (string memory) {
  72. return _symbol;
  73. }
  74. /**
  75. * @dev See {IERC721Metadata-tokenURI}.
  76. */
  77. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
  78. _requireMinted(tokenId);
  79. string memory baseURI = _baseURI();
  80. return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
  81. }
  82. /**
  83. * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
  84. * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
  85. * by default, can be overridden in child contracts.
  86. */
  87. function _baseURI() internal view virtual returns (string memory) {
  88. return "";
  89. }
  90. /**
  91. * @dev See {IERC721-approve}.
  92. */
  93. function approve(address to, uint256 tokenId) public virtual override {
  94. address owner = ERC721.ownerOf(tokenId);
  95. require(to != owner, "ERC721: approval to current owner");
  96. require(
  97. _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
  98. "ERC721: approve caller is not token owner nor approved for all"
  99. );
  100. _approve(to, tokenId);
  101. }
  102. /**
  103. * @dev See {IERC721-getApproved}.
  104. */
  105. function getApproved(uint256 tokenId) public view virtual override returns (address) {
  106. _requireMinted(tokenId);
  107. return _tokenApprovals[tokenId];
  108. }
  109. /**
  110. * @dev See {IERC721-setApprovalForAll}.
  111. */
  112. function setApprovalForAll(address operator, bool approved) public virtual override {
  113. _setApprovalForAll(_msgSender(), operator, approved);
  114. }
  115. /**
  116. * @dev See {IERC721-isApprovedForAll}.
  117. */
  118. function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
  119. return _operatorApprovals[owner][operator];
  120. }
  121. /**
  122. * @dev See {IERC721-transferFrom}.
  123. */
  124. function transferFrom(
  125. address from,
  126. address to,
  127. uint256 tokenId
  128. ) public virtual override {
  129. //solhint-disable-next-line max-line-length
  130. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
  131. _transfer(from, to, tokenId);
  132. }
  133. /**
  134. * @dev See {IERC721-safeTransferFrom}.
  135. */
  136. function safeTransferFrom(
  137. address from,
  138. address to,
  139. uint256 tokenId
  140. ) public virtual override {
  141. safeTransferFrom(from, to, tokenId, "");
  142. }
  143. /**
  144. * @dev See {IERC721-safeTransferFrom}.
  145. */
  146. function safeTransferFrom(
  147. address from,
  148. address to,
  149. uint256 tokenId,
  150. bytes memory data
  151. ) public virtual override {
  152. require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
  153. _safeTransfer(from, to, tokenId, data);
  154. }
  155. /**
  156. * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
  157. * are aware of the ERC721 protocol to prevent tokens from being forever locked.
  158. *
  159. * `data` is additional data, it has no specified format and it is sent in call to `to`.
  160. *
  161. * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
  162. * implement alternative mechanisms to perform token transfer, such as signature-based.
  163. *
  164. * Requirements:
  165. *
  166. * - `from` cannot be the zero address.
  167. * - `to` cannot be the zero address.
  168. * - `tokenId` token must exist and be owned by `from`.
  169. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  170. *
  171. * Emits a {Transfer} event.
  172. */
  173. function _safeTransfer(
  174. address from,
  175. address to,
  176. uint256 tokenId,
  177. bytes memory data
  178. ) internal virtual {
  179. _transfer(from, to, tokenId);
  180. require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
  181. }
  182. /**
  183. * @dev Returns whether `tokenId` exists.
  184. *
  185. * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
  186. *
  187. * Tokens start existing when they are minted (`_mint`),
  188. * and stop existing when they are burned (`_burn`).
  189. */
  190. function _exists(uint256 tokenId) internal view virtual returns (bool) {
  191. return _owners[tokenId] != address(0);
  192. }
  193. /**
  194. * @dev Returns whether `spender` is allowed to manage `tokenId`.
  195. *
  196. * Requirements:
  197. *
  198. * - `tokenId` must exist.
  199. */
  200. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
  201. address owner = ERC721.ownerOf(tokenId);
  202. return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
  203. }
  204. /**
  205. * @dev Safely mints `tokenId` and transfers it to `to`.
  206. *
  207. * Requirements:
  208. *
  209. * - `tokenId` must not exist.
  210. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  211. *
  212. * Emits a {Transfer} event.
  213. */
  214. function _safeMint(address to, uint256 tokenId) internal virtual {
  215. _safeMint(to, tokenId, "");
  216. }
  217. /**
  218. * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
  219. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  220. */
  221. function _safeMint(
  222. address to,
  223. uint256 tokenId,
  224. bytes memory data
  225. ) internal virtual {
  226. _mint(to, tokenId);
  227. require(
  228. _checkOnERC721Received(address(0), to, tokenId, data),
  229. "ERC721: transfer to non ERC721Receiver implementer"
  230. );
  231. }
  232. /**
  233. * @dev Mints `tokenId` and transfers it to `to`.
  234. *
  235. * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
  236. *
  237. * Requirements:
  238. *
  239. * - `tokenId` must not exist.
  240. * - `to` cannot be the zero address.
  241. *
  242. * Emits a {Transfer} event.
  243. */
  244. function _mint(address to, uint256 tokenId) internal virtual {
  245. require(to != address(0), "ERC721: mint to the zero address");
  246. require(!_exists(tokenId), "ERC721: token already minted");
  247. _beforeTokenTransfer(address(0), to, tokenId);
  248. _balances[to] += 1;
  249. _owners[tokenId] = to;
  250. emit Transfer(address(0), to, tokenId);
  251. _afterTokenTransfer(address(0), to, tokenId);
  252. }
  253. /**
  254. * @dev Destroys `tokenId`.
  255. * The approval is cleared when the token is burned.
  256. *
  257. * Requirements:
  258. *
  259. * - `tokenId` must exist.
  260. *
  261. * Emits a {Transfer} event.
  262. */
  263. function _burn(uint256 tokenId) internal virtual {
  264. address owner = ERC721.ownerOf(tokenId);
  265. _beforeTokenTransfer(owner, address(0), tokenId);
  266. // Clear approvals
  267. _approve(address(0), tokenId);
  268. _balances[owner] -= 1;
  269. delete _owners[tokenId];
  270. emit Transfer(owner, address(0), tokenId);
  271. _afterTokenTransfer(owner, address(0), tokenId);
  272. }
  273. /**
  274. * @dev Transfers `tokenId` from `from` to `to`.
  275. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  276. *
  277. * Requirements:
  278. *
  279. * - `to` cannot be the zero address.
  280. * - `tokenId` token must be owned by `from`.
  281. *
  282. * Emits a {Transfer} event.
  283. */
  284. function _transfer(
  285. address from,
  286. address to,
  287. uint256 tokenId
  288. ) internal virtual {
  289. require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
  290. require(to != address(0), "ERC721: transfer to the zero address");
  291. _beforeTokenTransfer(from, to, tokenId);
  292. // Clear approvals from the previous owner
  293. _approve(address(0), tokenId);
  294. _balances[from] -= 1;
  295. _balances[to] += 1;
  296. _owners[tokenId] = to;
  297. emit Transfer(from, to, tokenId);
  298. _afterTokenTransfer(from, to, tokenId);
  299. }
  300. /**
  301. * @dev Approve `to` to operate on `tokenId`
  302. *
  303. * Emits an {Approval} event.
  304. */
  305. function _approve(address to, uint256 tokenId) internal virtual {
  306. _tokenApprovals[tokenId] = to;
  307. emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
  308. }
  309. /**
  310. * @dev Approve `operator` to operate on all of `owner` tokens
  311. *
  312. * Emits an {ApprovalForAll} event.
  313. */
  314. function _setApprovalForAll(
  315. address owner,
  316. address operator,
  317. bool approved
  318. ) internal virtual {
  319. require(owner != operator, "ERC721: approve to caller");
  320. _operatorApprovals[owner][operator] = approved;
  321. emit ApprovalForAll(owner, operator, approved);
  322. }
  323. /**
  324. * @dev Reverts if the `tokenId` has not been minted yet.
  325. */
  326. function _requireMinted(uint256 tokenId) internal view virtual {
  327. require(_exists(tokenId), "ERC721: invalid token ID");
  328. }
  329. /**
  330. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  331. * The call is not executed if the target address is not a contract.
  332. *
  333. * @param from address representing the previous owner of the given token ID
  334. * @param to target address that will receive the tokens
  335. * @param tokenId uint256 ID of the token to be transferred
  336. * @param data bytes optional data to send along with the call
  337. * @return bool whether the call correctly returned the expected magic value
  338. */
  339. function _checkOnERC721Received(
  340. address from,
  341. address to,
  342. uint256 tokenId,
  343. bytes memory data
  344. ) private returns (bool) {
  345. if (to.isContract()) {
  346. try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
  347. return retval == IERC721Receiver.onERC721Received.selector;
  348. } catch (bytes memory reason) {
  349. if (reason.length == 0) {
  350. revert("ERC721: transfer to non ERC721Receiver implementer");
  351. } else {
  352. /// @solidity memory-safe-assembly
  353. assembly {
  354. revert(add(32, reason), mload(reason))
  355. }
  356. }
  357. }
  358. } else {
  359. return true;
  360. }
  361. }
  362. /**
  363. * @dev Hook that is called before any token transfer. This includes minting
  364. * and burning.
  365. *
  366. * Calling conditions:
  367. *
  368. * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  369. * transferred to `to`.
  370. * - When `from` is zero, `tokenId` will be minted for `to`.
  371. * - When `to` is zero, ``from``'s `tokenId` will be burned.
  372. * - `from` and `to` are never both zero.
  373. *
  374. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  375. */
  376. function _beforeTokenTransfer(
  377. address from,
  378. address to,
  379. uint256 tokenId
  380. ) internal virtual {}
  381. /**
  382. * @dev Hook that is called after any transfer of tokens. This includes
  383. * minting and burning.
  384. *
  385. * Calling conditions:
  386. *
  387. * - when `from` and `to` are both non-zero.
  388. * - `from` and `to` are never both zero.
  389. *
  390. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  391. */
  392. function _afterTokenTransfer(
  393. address from,
  394. address to,
  395. uint256 tokenId
  396. ) internal virtual {}
  397. }