ERC1155.sol 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.6.0 <0.8.0;
  3. import "./IERC1155.sol";
  4. import "./IERC1155MetadataURI.sol";
  5. import "./IERC1155Receiver.sol";
  6. import "../../utils/Context.sol";
  7. import "../../introspection/ERC165.sol";
  8. import "../../math/SafeMath.sol";
  9. import "../../utils/Address.sol";
  10. /**
  11. *
  12. * @dev Implementation of the basic standard multi-token.
  13. * See https://eips.ethereum.org/EIPS/eip-1155
  14. * Originally based on code by Enjin: https://github.com/enjin/erc-1155
  15. *
  16. * _Available since v3.1._
  17. */
  18. contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
  19. using SafeMath for uint256;
  20. using Address for address;
  21. // Mapping from token ID to account balances
  22. mapping (uint256 => mapping(address => uint256)) private _balances;
  23. // Mapping from account to operator approvals
  24. mapping (address => mapping(address => bool)) private _operatorApprovals;
  25. // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
  26. string private _uri;
  27. /*
  28. * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
  29. * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
  30. * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
  31. * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
  32. * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
  33. * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
  34. *
  35. * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
  36. * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
  37. */
  38. bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
  39. /*
  40. * bytes4(keccak256('uri(uint256)')) == 0x0e89341c
  41. */
  42. bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
  43. /**
  44. * @dev See {_setURI}.
  45. */
  46. constructor (string memory uri_) public {
  47. _setURI(uri_);
  48. // register the supported interfaces to conform to ERC1155 via ERC165
  49. _registerInterface(_INTERFACE_ID_ERC1155);
  50. // register the supported interfaces to conform to ERC1155MetadataURI via ERC165
  51. _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
  52. }
  53. /**
  54. * @dev See {IERC1155MetadataURI-uri}.
  55. *
  56. * This implementation returns the same URI for *all* token types. It relies
  57. * on the token type ID substitution mechanism
  58. * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
  59. *
  60. * Clients calling this function must replace the `\{id\}` substring with the
  61. * actual token type ID.
  62. */
  63. function uri(uint256) external view virtual override returns (string memory) {
  64. return _uri;
  65. }
  66. /**
  67. * @dev See {IERC1155-balanceOf}.
  68. *
  69. * Requirements:
  70. *
  71. * - `account` cannot be the zero address.
  72. */
  73. function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
  74. require(account != address(0), "ERC1155: balance query for the zero address");
  75. return _balances[id][account];
  76. }
  77. /**
  78. * @dev See {IERC1155-balanceOfBatch}.
  79. *
  80. * Requirements:
  81. *
  82. * - `accounts` and `ids` must have the same length.
  83. */
  84. function balanceOfBatch(
  85. address[] memory accounts,
  86. uint256[] memory ids
  87. )
  88. public
  89. view
  90. virtual
  91. override
  92. returns (uint256[] memory)
  93. {
  94. require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
  95. uint256[] memory batchBalances = new uint256[](accounts.length);
  96. for (uint256 i = 0; i < accounts.length; ++i) {
  97. batchBalances[i] = balanceOf(accounts[i], ids[i]);
  98. }
  99. return batchBalances;
  100. }
  101. /**
  102. * @dev See {IERC1155-setApprovalForAll}.
  103. */
  104. function setApprovalForAll(address operator, bool approved) public virtual override {
  105. require(_msgSender() != operator, "ERC1155: setting approval status for self");
  106. _operatorApprovals[_msgSender()][operator] = approved;
  107. emit ApprovalForAll(_msgSender(), operator, approved);
  108. }
  109. /**
  110. * @dev See {IERC1155-isApprovedForAll}.
  111. */
  112. function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
  113. return _operatorApprovals[account][operator];
  114. }
  115. /**
  116. * @dev See {IERC1155-safeTransferFrom}.
  117. */
  118. function safeTransferFrom(
  119. address from,
  120. address to,
  121. uint256 id,
  122. uint256 amount,
  123. bytes memory data
  124. )
  125. public
  126. virtual
  127. override
  128. {
  129. require(to != address(0), "ERC1155: transfer to the zero address");
  130. require(
  131. from == _msgSender() || isApprovedForAll(from, _msgSender()),
  132. "ERC1155: caller is not owner nor approved"
  133. );
  134. address operator = _msgSender();
  135. _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
  136. _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
  137. _balances[id][to] = _balances[id][to].add(amount);
  138. emit TransferSingle(operator, from, to, id, amount);
  139. _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
  140. }
  141. /**
  142. * @dev See {IERC1155-safeBatchTransferFrom}.
  143. */
  144. function safeBatchTransferFrom(
  145. address from,
  146. address to,
  147. uint256[] memory ids,
  148. uint256[] memory amounts,
  149. bytes memory data
  150. )
  151. public
  152. virtual
  153. override
  154. {
  155. require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
  156. require(to != address(0), "ERC1155: transfer to the zero address");
  157. require(
  158. from == _msgSender() || isApprovedForAll(from, _msgSender()),
  159. "ERC1155: transfer caller is not owner nor approved"
  160. );
  161. address operator = _msgSender();
  162. _beforeTokenTransfer(operator, from, to, ids, amounts, data);
  163. for (uint256 i = 0; i < ids.length; ++i) {
  164. uint256 id = ids[i];
  165. uint256 amount = amounts[i];
  166. _balances[id][from] = _balances[id][from].sub(
  167. amount,
  168. "ERC1155: insufficient balance for transfer"
  169. );
  170. _balances[id][to] = _balances[id][to].add(amount);
  171. }
  172. emit TransferBatch(operator, from, to, ids, amounts);
  173. _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
  174. }
  175. /**
  176. * @dev Sets a new URI for all token types, by relying on the token type ID
  177. * substitution mechanism
  178. * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
  179. *
  180. * By this mechanism, any occurrence of the `\{id\}` substring in either the
  181. * URI or any of the amounts in the JSON file at said URI will be replaced by
  182. * clients with the token type ID.
  183. *
  184. * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
  185. * interpreted by clients as
  186. * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
  187. * for token type ID 0x4cce0.
  188. *
  189. * See {uri}.
  190. *
  191. * Because these URIs cannot be meaningfully represented by the {URI} event,
  192. * this function emits no events.
  193. */
  194. function _setURI(string memory newuri) internal virtual {
  195. _uri = newuri;
  196. }
  197. /**
  198. * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
  199. *
  200. * Emits a {TransferSingle} event.
  201. *
  202. * Requirements:
  203. *
  204. * - `account` cannot be the zero address.
  205. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
  206. * acceptance magic value.
  207. */
  208. function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
  209. require(account != address(0), "ERC1155: mint to the zero address");
  210. address operator = _msgSender();
  211. _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
  212. _balances[id][account] = _balances[id][account].add(amount);
  213. emit TransferSingle(operator, address(0), account, id, amount);
  214. _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
  215. }
  216. /**
  217. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
  218. *
  219. * Requirements:
  220. *
  221. * - `ids` and `amounts` must have the same length.
  222. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
  223. * acceptance magic value.
  224. */
  225. function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
  226. require(to != address(0), "ERC1155: mint to the zero address");
  227. require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
  228. address operator = _msgSender();
  229. _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
  230. for (uint i = 0; i < ids.length; i++) {
  231. _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
  232. }
  233. emit TransferBatch(operator, address(0), to, ids, amounts);
  234. _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
  235. }
  236. /**
  237. * @dev Destroys `amount` tokens of token type `id` from `account`
  238. *
  239. * Requirements:
  240. *
  241. * - `account` cannot be the zero address.
  242. * - `account` must have at least `amount` tokens of token type `id`.
  243. */
  244. function _burn(address account, uint256 id, uint256 amount) internal virtual {
  245. require(account != address(0), "ERC1155: burn from the zero address");
  246. address operator = _msgSender();
  247. _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
  248. _balances[id][account] = _balances[id][account].sub(
  249. amount,
  250. "ERC1155: burn amount exceeds balance"
  251. );
  252. emit TransferSingle(operator, account, address(0), id, amount);
  253. }
  254. /**
  255. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
  256. *
  257. * Requirements:
  258. *
  259. * - `ids` and `amounts` must have the same length.
  260. */
  261. function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
  262. require(account != address(0), "ERC1155: burn from the zero address");
  263. require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
  264. address operator = _msgSender();
  265. _beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
  266. for (uint i = 0; i < ids.length; i++) {
  267. _balances[ids[i]][account] = _balances[ids[i]][account].sub(
  268. amounts[i],
  269. "ERC1155: burn amount exceeds balance"
  270. );
  271. }
  272. emit TransferBatch(operator, account, address(0), ids, amounts);
  273. }
  274. /**
  275. * @dev Hook that is called before any token transfer. This includes minting
  276. * and burning, as well as batched variants.
  277. *
  278. * The same hook is called on both single and batched variants. For single
  279. * transfers, the length of the `id` and `amount` arrays will be 1.
  280. *
  281. * Calling conditions (for each `id` and `amount` pair):
  282. *
  283. * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
  284. * of token type `id` will be transferred to `to`.
  285. * - When `from` is zero, `amount` tokens of token type `id` will be minted
  286. * for `to`.
  287. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
  288. * will be burned.
  289. * - `from` and `to` are never both zero.
  290. * - `ids` and `amounts` have the same, non-zero length.
  291. *
  292. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  293. */
  294. function _beforeTokenTransfer(
  295. address operator,
  296. address from,
  297. address to,
  298. uint256[] memory ids,
  299. uint256[] memory amounts,
  300. bytes memory data
  301. )
  302. internal
  303. virtual
  304. { }
  305. function _doSafeTransferAcceptanceCheck(
  306. address operator,
  307. address from,
  308. address to,
  309. uint256 id,
  310. uint256 amount,
  311. bytes memory data
  312. )
  313. private
  314. {
  315. if (to.isContract()) {
  316. try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
  317. if (response != IERC1155Receiver(to).onERC1155Received.selector) {
  318. revert("ERC1155: ERC1155Receiver rejected tokens");
  319. }
  320. } catch Error(string memory reason) {
  321. revert(reason);
  322. } catch {
  323. revert("ERC1155: transfer to non ERC1155Receiver implementer");
  324. }
  325. }
  326. }
  327. function _doSafeBatchTransferAcceptanceCheck(
  328. address operator,
  329. address from,
  330. address to,
  331. uint256[] memory ids,
  332. uint256[] memory amounts,
  333. bytes memory data
  334. )
  335. private
  336. {
  337. if (to.isContract()) {
  338. try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
  339. if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
  340. revert("ERC1155: ERC1155Receiver rejected tokens");
  341. }
  342. } catch Error(string memory reason) {
  343. revert(reason);
  344. } catch {
  345. revert("ERC1155: transfer to non ERC1155Receiver implementer");
  346. }
  347. }
  348. }
  349. function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
  350. uint256[] memory array = new uint256[](1);
  351. array[0] = element;
  352. return array;
  353. }
  354. }