ERC721.sol 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.6.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: balance query for the zero address");
  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: owner query for nonexistent token");
  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. require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
  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 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. require(_exists(tokenId), "ERC721: approved query for nonexistent token");
  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: transfer caller is not 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: transfer caller is not 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. require(_exists(tokenId), "ERC721: operator query for nonexistent token");
  202. address owner = ERC721.ownerOf(tokenId);
  203. return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
  204. }
  205. /**
  206. * @dev Safely mints `tokenId` and transfers it to `to`.
  207. *
  208. * Requirements:
  209. *
  210. * - `tokenId` must not exist.
  211. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
  212. *
  213. * Emits a {Transfer} event.
  214. */
  215. function _safeMint(address to, uint256 tokenId) internal virtual {
  216. _safeMint(to, tokenId, "");
  217. }
  218. /**
  219. * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
  220. * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
  221. */
  222. function _safeMint(
  223. address to,
  224. uint256 tokenId,
  225. bytes memory data
  226. ) internal virtual {
  227. _mint(to, tokenId);
  228. require(
  229. _checkOnERC721Received(address(0), to, tokenId, data),
  230. "ERC721: transfer to non ERC721Receiver implementer"
  231. );
  232. }
  233. /**
  234. * @dev Mints `tokenId` and transfers it to `to`.
  235. *
  236. * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
  237. *
  238. * Requirements:
  239. *
  240. * - `tokenId` must not exist.
  241. * - `to` cannot be the zero address.
  242. *
  243. * Emits a {Transfer} event.
  244. */
  245. function _mint(address to, uint256 tokenId) internal virtual {
  246. require(to != address(0), "ERC721: mint to the zero address");
  247. require(!_exists(tokenId), "ERC721: token already minted");
  248. _beforeTokenTransfer(address(0), to, tokenId);
  249. _balances[to] += 1;
  250. _owners[tokenId] = to;
  251. emit Transfer(address(0), to, tokenId);
  252. _afterTokenTransfer(address(0), to, tokenId);
  253. }
  254. /**
  255. * @dev Destroys `tokenId`.
  256. * The approval is cleared when the token is burned.
  257. *
  258. * Requirements:
  259. *
  260. * - `tokenId` must exist.
  261. *
  262. * Emits a {Transfer} event.
  263. */
  264. function _burn(uint256 tokenId) internal virtual {
  265. address owner = ERC721.ownerOf(tokenId);
  266. _beforeTokenTransfer(owner, address(0), tokenId);
  267. // Clear approvals
  268. _approve(address(0), tokenId);
  269. _balances[owner] -= 1;
  270. delete _owners[tokenId];
  271. emit Transfer(owner, address(0), tokenId);
  272. _afterTokenTransfer(owner, address(0), tokenId);
  273. }
  274. /**
  275. * @dev Transfers `tokenId` from `from` to `to`.
  276. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
  277. *
  278. * Requirements:
  279. *
  280. * - `to` cannot be the zero address.
  281. * - `tokenId` token must be owned by `from`.
  282. *
  283. * Emits a {Transfer} event.
  284. */
  285. function _transfer(
  286. address from,
  287. address to,
  288. uint256 tokenId
  289. ) internal virtual {
  290. require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
  291. require(to != address(0), "ERC721: transfer to the zero address");
  292. _beforeTokenTransfer(from, to, tokenId);
  293. // Clear approvals from the previous owner
  294. _approve(address(0), tokenId);
  295. _balances[from] -= 1;
  296. _balances[to] += 1;
  297. _owners[tokenId] = to;
  298. emit Transfer(from, to, tokenId);
  299. _afterTokenTransfer(from, to, tokenId);
  300. }
  301. /**
  302. * @dev Approve `to` to operate on `tokenId`
  303. *
  304. * Emits an {Approval} event.
  305. */
  306. function _approve(address to, uint256 tokenId) internal virtual {
  307. _tokenApprovals[tokenId] = to;
  308. emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
  309. }
  310. /**
  311. * @dev Approve `operator` to operate on all of `owner` tokens
  312. *
  313. * Emits an {ApprovalForAll} event.
  314. */
  315. function _setApprovalForAll(
  316. address owner,
  317. address operator,
  318. bool approved
  319. ) internal virtual {
  320. require(owner != operator, "ERC721: approve to caller");
  321. _operatorApprovals[owner][operator] = approved;
  322. emit ApprovalForAll(owner, operator, approved);
  323. }
  324. /**
  325. * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
  326. * The call is not executed if the target address is not a contract.
  327. *
  328. * @param from address representing the previous owner of the given token ID
  329. * @param to target address that will receive the tokens
  330. * @param tokenId uint256 ID of the token to be transferred
  331. * @param data bytes optional data to send along with the call
  332. * @return bool whether the call correctly returned the expected magic value
  333. */
  334. function _checkOnERC721Received(
  335. address from,
  336. address to,
  337. uint256 tokenId,
  338. bytes memory data
  339. ) private returns (bool) {
  340. if (to.isContract()) {
  341. try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
  342. return retval == IERC721Receiver.onERC721Received.selector;
  343. } catch (bytes memory reason) {
  344. if (reason.length == 0) {
  345. revert("ERC721: transfer to non ERC721Receiver implementer");
  346. } else {
  347. assembly {
  348. revert(add(32, reason), mload(reason))
  349. }
  350. }
  351. }
  352. } else {
  353. return true;
  354. }
  355. }
  356. /**
  357. * @dev Hook that is called before any token transfer. This includes minting
  358. * and burning.
  359. *
  360. * Calling conditions:
  361. *
  362. * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
  363. * transferred to `to`.
  364. * - When `from` is zero, `tokenId` will be minted for `to`.
  365. * - When `to` is zero, ``from``'s `tokenId` will be burned.
  366. * - `from` and `to` are never both zero.
  367. *
  368. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  369. */
  370. function _beforeTokenTransfer(
  371. address from,
  372. address to,
  373. uint256 tokenId
  374. ) internal virtual {}
  375. /**
  376. * @dev Hook that is called after any transfer of tokens. This includes
  377. * minting and burning.
  378. *
  379. * Calling conditions:
  380. *
  381. * - when `from` and `to` are both non-zero.
  382. * - `from` and `to` are never both zero.
  383. *
  384. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  385. */
  386. function _afterTokenTransfer(
  387. address from,
  388. address to,
  389. uint256 tokenId
  390. ) internal virtual {}
  391. }