forked from OpenZeppelin/openzeppelin-contracts
/
ERC1155URIStorage.sol
70 lines (60 loc) · 2.15 KB
/
ERC1155URIStorage.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155URIStorage.sol)
pragma solidity ^0.8.0;
import "../../../utils/Strings.sol";
import "../ERC1155.sol";
/**
* @dev ERC1155 token with storage based token URI management.
* Inspired by the ERC721URIStorage extension
*/
abstract contract ERC1155URIStorage is ERC1155 {
using Strings for uint256;
// optional base URI
string private _baseURI = "";
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the concatenation of the `_baseURI`
* and the token-specific uri if the latter is set
*
* This allowes for the following behavior:
*
* the `ERC1155URIStorage._tokenURIs[tokenId]` is set
* → the result is the concatenation of `_baseURI` and `ERC1155URIStorage._tokenURIs[tokenId]`
* (keep in mind that `_baseURI` is empty per default)
*
* the `ERC1155URIStorage._tokenURIs[tokenId]` is NOT set
* → the result is `ERC1155._uri`
*
* neither `ERC1155URIStorage._tokenURIs[tokenId]` nor `ERC1155._uri` are set
* → the result is empty
*/
function uri(uint256 tokenId) public view virtual override returns (string memory) {
string memory _tokenURI = _tokenURIs[tokenId];
// If token URI is set, concatenate base URI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is no tokenURI, return the ERC1155.uri
return super.uri(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setURI(uint256 tokenId, string memory _tokenURI) internal virtual {
_tokenURIs[tokenId] = _tokenURI;
emit URI(uri(tokenId), tokenId);
}
/**
* @dev Sets `baseURI` as the `_baseURI` for all tokens
*/
function _setBaseURI(string memory baseURI) internal virtual {
_baseURI = baseURI;
}
}