ERC1155URIStorage.sol 1.9 KB

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