ERC1155.sol 17 KB

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