ERC1155URIStorage.sol 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0-rc.1) (token/ERC1155/extensions/ERC1155URIStorage.sol)
  3. pragma solidity ^0.8.20;
  4. import {Strings} from "../../../utils/Strings.sol";
  5. import {ERC1155} from "../ERC1155.sol";
  6. /**
  7. * @dev ERC-1155 token with storage based token URI management.
  8. * Inspired by the {ERC721URIStorage} extension
  9. */
  10. abstract contract ERC1155URIStorage is ERC1155 {
  11. using Strings for uint256;
  12. // Optional base URI
  13. string private _baseURI = "";
  14. // Optional mapping for token URIs
  15. mapping(uint256 tokenId => string) private _tokenURIs;
  16. /**
  17. * @dev See {IERC1155MetadataURI-uri}.
  18. *
  19. * This implementation returns the concatenation of the `_baseURI`
  20. * and the token-specific uri if the latter is set
  21. *
  22. * This enables the following behaviors:
  23. *
  24. * - if `_tokenURIs[tokenId]` is set, then the result is the concatenation
  25. * of `_baseURI` and `_tokenURIs[tokenId]` (keep in mind that `_baseURI`
  26. * is empty per default);
  27. *
  28. * - if `_tokenURIs[tokenId]` is NOT set then we fallback to `super.uri()`
  29. * which in most cases will contain `ERC1155._uri`;
  30. *
  31. * - if `_tokenURIs[tokenId]` is NOT set, and if the parents do not have a
  32. * uri value set, then the result is empty.
  33. */
  34. function uri(uint256 tokenId) public view virtual override returns (string memory) {
  35. string memory tokenURI = _tokenURIs[tokenId];
  36. // If token URI is set, concatenate base URI and tokenURI (via string.concat).
  37. return bytes(tokenURI).length > 0 ? string.concat(_baseURI, tokenURI) : super.uri(tokenId);
  38. }
  39. /**
  40. * @dev Sets `tokenURI` as the tokenURI of `tokenId`.
  41. */
  42. function _setURI(uint256 tokenId, string memory tokenURI) internal virtual {
  43. _tokenURIs[tokenId] = tokenURI;
  44. emit URI(uri(tokenId), tokenId);
  45. }
  46. /**
  47. * @dev Sets `baseURI` as the `_baseURI` for all tokens
  48. */
  49. function _setBaseURI(string memory baseURI) internal virtual {
  50. _baseURI = baseURI;
  51. }
  52. }