ERC1155URIStorage.sol 2.0 KB

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