ERC721URIStorage.sol 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.3.0) (token/ERC721/extensions/ERC721URIStorage.sol)
  3. pragma solidity ^0.8.20;
  4. import {ERC721} from "../ERC721.sol";
  5. import {IERC721Metadata} from "./IERC721Metadata.sol";
  6. import {Strings} from "../../../utils/Strings.sol";
  7. import {IERC4906} from "../../../interfaces/IERC4906.sol";
  8. import {IERC165} from "../../../interfaces/IERC165.sol";
  9. /**
  10. * @dev ERC-721 token with storage based token URI management.
  11. */
  12. abstract contract ERC721URIStorage is IERC4906, ERC721 {
  13. using Strings for uint256;
  14. // Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only
  15. // defines events and does not include any external function.
  16. bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);
  17. // Optional mapping for token URIs
  18. mapping(uint256 tokenId => string) private _tokenURIs;
  19. /// @inheritdoc IERC165
  20. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
  21. return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);
  22. }
  23. /// @inheritdoc IERC721Metadata
  24. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
  25. _requireOwned(tokenId);
  26. string memory _tokenURI = _tokenURIs[tokenId];
  27. string memory base = _baseURI();
  28. // If there is no base URI, return the token URI.
  29. if (bytes(base).length == 0) {
  30. return _tokenURI;
  31. }
  32. // If both are set, concatenate the baseURI and tokenURI (via string.concat).
  33. if (bytes(_tokenURI).length > 0) {
  34. return string.concat(base, _tokenURI);
  35. }
  36. return super.tokenURI(tokenId);
  37. }
  38. /**
  39. * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
  40. *
  41. * Emits {IERC4906-MetadataUpdate}.
  42. */
  43. function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
  44. _tokenURIs[tokenId] = _tokenURI;
  45. emit MetadataUpdate(tokenId);
  46. }
  47. }