ERC721URIStorage.sol 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/extensions/ERC721URIStorage.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC721.sol";
  5. import "../../../interfaces/IERC4906.sol";
  6. /**
  7. * @dev ERC721 token with storage based token URI management.
  8. */
  9. abstract contract ERC721URIStorage is IERC4906, ERC721 {
  10. using Strings for uint256;
  11. // Optional mapping for token URIs
  12. mapping(uint256 => string) private _tokenURIs;
  13. /**
  14. * @dev See {IERC721Metadata-tokenURI}.
  15. */
  16. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
  17. _requireMinted(tokenId);
  18. string memory _tokenURI = _tokenURIs[tokenId];
  19. string memory base = _baseURI();
  20. // If there is no base URI, return the token URI.
  21. if (bytes(base).length == 0) {
  22. return _tokenURI;
  23. }
  24. // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
  25. if (bytes(_tokenURI).length > 0) {
  26. return string(abi.encodePacked(base, _tokenURI));
  27. }
  28. return super.tokenURI(tokenId);
  29. }
  30. /**
  31. * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
  32. *
  33. * Emits {MetadataUpdate}.
  34. *
  35. * Requirements:
  36. *
  37. * - `tokenId` must exist.
  38. */
  39. function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
  40. require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
  41. _tokenURIs[tokenId] = _tokenURI;
  42. emit MetadataUpdate(tokenId);
  43. }
  44. /**
  45. * @dev See {ERC721-_burn}. This override additionally checks to see if a
  46. * token-specific URI was set for the token, and if so, it deletes the token URI from
  47. * the storage mapping.
  48. */
  49. function _burn(uint256 tokenId) internal virtual override {
  50. super._burn(tokenId);
  51. if (bytes(_tokenURIs[tokenId]).length != 0) {
  52. delete _tokenURIs[tokenId];
  53. }
  54. }
  55. }