ERC1155.sol 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/ERC1155.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC1155} from "./IERC1155.sol";
  5. import {IERC1155Receiver} from "./IERC1155Receiver.sol";
  6. import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
  7. import {Context} from "../../utils/Context.sol";
  8. import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
  9. import {Arrays} from "../../utils/Arrays.sol";
  10. import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";
  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. abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
  17. using Arrays for uint256[];
  18. using Arrays for address[];
  19. mapping(uint256 id => mapping(address account => uint256)) private _balances;
  20. mapping(address account => mapping(address operator => bool)) private _operatorApprovals;
  21. // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
  22. string private _uri;
  23. /**
  24. * @dev See {_setURI}.
  25. */
  26. constructor(string memory uri_) {
  27. _setURI(uri_);
  28. }
  29. /**
  30. * @dev See {IERC165-supportsInterface}.
  31. */
  32. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
  33. return
  34. interfaceId == type(IERC1155).interfaceId ||
  35. interfaceId == type(IERC1155MetadataURI).interfaceId ||
  36. super.supportsInterface(interfaceId);
  37. }
  38. /**
  39. * @dev See {IERC1155MetadataURI-uri}.
  40. *
  41. * This implementation returns the same URI for *all* token types. It relies
  42. * on the token type ID substitution mechanism
  43. * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
  44. *
  45. * Clients calling this function must replace the `\{id\}` substring with the
  46. * actual token type ID.
  47. */
  48. function uri(uint256 /* id */) public view virtual returns (string memory) {
  49. return _uri;
  50. }
  51. /**
  52. * @dev See {IERC1155-balanceOf}.
  53. */
  54. function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
  55. return _balances[id][account];
  56. }
  57. /**
  58. * @dev See {IERC1155-balanceOfBatch}.
  59. *
  60. * Requirements:
  61. *
  62. * - `accounts` and `ids` must have the same length.
  63. */
  64. function balanceOfBatch(
  65. address[] memory accounts,
  66. uint256[] memory ids
  67. ) public view virtual returns (uint256[] memory) {
  68. if (accounts.length != ids.length) {
  69. revert ERC1155InvalidArrayLength(ids.length, accounts.length);
  70. }
  71. uint256[] memory batchBalances = new uint256[](accounts.length);
  72. for (uint256 i = 0; i < accounts.length; ++i) {
  73. batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
  74. }
  75. return batchBalances;
  76. }
  77. /**
  78. * @dev See {IERC1155-setApprovalForAll}.
  79. */
  80. function setApprovalForAll(address operator, bool approved) public virtual {
  81. _setApprovalForAll(_msgSender(), operator, approved);
  82. }
  83. /**
  84. * @dev See {IERC1155-isApprovedForAll}.
  85. */
  86. function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
  87. return _operatorApprovals[account][operator];
  88. }
  89. /**
  90. * @dev See {IERC1155-safeTransferFrom}.
  91. */
  92. function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
  93. address sender = _msgSender();
  94. if (from != sender && !isApprovedForAll(from, sender)) {
  95. revert ERC1155MissingApprovalForAll(sender, from);
  96. }
  97. _safeTransferFrom(from, to, id, value, data);
  98. }
  99. /**
  100. * @dev See {IERC1155-safeBatchTransferFrom}.
  101. */
  102. function safeBatchTransferFrom(
  103. address from,
  104. address to,
  105. uint256[] memory ids,
  106. uint256[] memory values,
  107. bytes memory data
  108. ) public virtual {
  109. address sender = _msgSender();
  110. if (from != sender && !isApprovedForAll(from, sender)) {
  111. revert ERC1155MissingApprovalForAll(sender, from);
  112. }
  113. _safeBatchTransferFrom(from, to, ids, values, data);
  114. }
  115. /**
  116. * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from` (or `to`) is the zero address.
  117. *
  118. * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
  119. *
  120. * Requirements:
  121. *
  122. * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
  123. * or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
  124. * - `ids` and `values` must have the same length.
  125. *
  126. * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
  127. */
  128. function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
  129. if (ids.length != values.length) {
  130. revert ERC1155InvalidArrayLength(ids.length, values.length);
  131. }
  132. address operator = _msgSender();
  133. for (uint256 i = 0; i < ids.length; ++i) {
  134. uint256 id = ids.unsafeMemoryAccess(i);
  135. uint256 value = values.unsafeMemoryAccess(i);
  136. if (from != address(0)) {
  137. uint256 fromBalance = _balances[id][from];
  138. if (fromBalance < value) {
  139. revert ERC1155InsufficientBalance(from, fromBalance, value, id);
  140. }
  141. unchecked {
  142. // Overflow not possible: value <= fromBalance
  143. _balances[id][from] = fromBalance - value;
  144. }
  145. }
  146. if (to != address(0)) {
  147. _balances[id][to] += value;
  148. }
  149. }
  150. if (ids.length == 1) {
  151. uint256 id = ids.unsafeMemoryAccess(0);
  152. uint256 value = values.unsafeMemoryAccess(0);
  153. emit TransferSingle(operator, from, to, id, value);
  154. } else {
  155. emit TransferBatch(operator, from, to, ids, values);
  156. }
  157. }
  158. /**
  159. * @dev Version of {_update} that performs the token acceptance check by calling {IERC1155Receiver-onERC1155Received}
  160. * or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it contains code (eg. is a smart contract
  161. * at the moment of execution).
  162. *
  163. * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
  164. * update to the contract state after this function would break the check-effect-interaction pattern. Consider
  165. * overriding {_update} instead.
  166. */
  167. function _updateWithAcceptanceCheck(
  168. address from,
  169. address to,
  170. uint256[] memory ids,
  171. uint256[] memory values,
  172. bytes memory data
  173. ) internal virtual {
  174. _update(from, to, ids, values);
  175. if (to != address(0)) {
  176. address operator = _msgSender();
  177. if (ids.length == 1) {
  178. uint256 id = ids.unsafeMemoryAccess(0);
  179. uint256 value = values.unsafeMemoryAccess(0);
  180. _doSafeTransferAcceptanceCheck(operator, from, to, id, value, data);
  181. } else {
  182. _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, values, data);
  183. }
  184. }
  185. }
  186. /**
  187. * @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
  188. *
  189. * Emits a {TransferSingle} event.
  190. *
  191. * Requirements:
  192. *
  193. * - `to` cannot be the zero address.
  194. * - `from` must have a balance of tokens of type `id` of at least `value` amount.
  195. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
  196. * acceptance magic value.
  197. */
  198. function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
  199. if (to == address(0)) {
  200. revert ERC1155InvalidReceiver(address(0));
  201. }
  202. if (from == address(0)) {
  203. revert ERC1155InvalidSender(address(0));
  204. }
  205. (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
  206. _updateWithAcceptanceCheck(from, to, ids, values, data);
  207. }
  208. /**
  209. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
  210. *
  211. * Emits a {TransferBatch} event.
  212. *
  213. * Requirements:
  214. *
  215. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
  216. * acceptance magic value.
  217. * - `ids` and `values` must have the same length.
  218. */
  219. function _safeBatchTransferFrom(
  220. address from,
  221. address to,
  222. uint256[] memory ids,
  223. uint256[] memory values,
  224. bytes memory data
  225. ) internal {
  226. if (to == address(0)) {
  227. revert ERC1155InvalidReceiver(address(0));
  228. }
  229. if (from == address(0)) {
  230. revert ERC1155InvalidSender(address(0));
  231. }
  232. _updateWithAcceptanceCheck(from, to, ids, values, data);
  233. }
  234. /**
  235. * @dev Sets a new URI for all token types, by relying on the token type ID
  236. * substitution mechanism
  237. * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
  238. *
  239. * By this mechanism, any occurrence of the `\{id\}` substring in either the
  240. * URI or any of the values in the JSON file at said URI will be replaced by
  241. * clients with the token type ID.
  242. *
  243. * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
  244. * interpreted by clients as
  245. * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
  246. * for token type ID 0x4cce0.
  247. *
  248. * See {uri}.
  249. *
  250. * Because these URIs cannot be meaningfully represented by the {URI} event,
  251. * this function emits no events.
  252. */
  253. function _setURI(string memory newuri) internal virtual {
  254. _uri = newuri;
  255. }
  256. /**
  257. * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
  258. *
  259. * Emits a {TransferSingle} event.
  260. *
  261. * Requirements:
  262. *
  263. * - `to` cannot be the zero address.
  264. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
  265. * acceptance magic value.
  266. */
  267. function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
  268. if (to == address(0)) {
  269. revert ERC1155InvalidReceiver(address(0));
  270. }
  271. (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
  272. _updateWithAcceptanceCheck(address(0), to, ids, values, data);
  273. }
  274. /**
  275. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
  276. *
  277. * Emits a {TransferBatch} event.
  278. *
  279. * Requirements:
  280. *
  281. * - `ids` and `values` must have the same length.
  282. * - `to` cannot be the zero address.
  283. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
  284. * acceptance magic value.
  285. */
  286. function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
  287. if (to == address(0)) {
  288. revert ERC1155InvalidReceiver(address(0));
  289. }
  290. _updateWithAcceptanceCheck(address(0), to, ids, values, data);
  291. }
  292. /**
  293. * @dev Destroys a `value` amount of tokens of type `id` from `from`
  294. *
  295. * Emits a {TransferSingle} event.
  296. *
  297. * Requirements:
  298. *
  299. * - `from` cannot be the zero address.
  300. * - `from` must have at least `value` amount of tokens of type `id`.
  301. */
  302. function _burn(address from, uint256 id, uint256 value) internal {
  303. if (from == address(0)) {
  304. revert ERC1155InvalidSender(address(0));
  305. }
  306. (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
  307. _updateWithAcceptanceCheck(from, address(0), ids, values, "");
  308. }
  309. /**
  310. * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
  311. *
  312. * Emits a {TransferBatch} event.
  313. *
  314. * Requirements:
  315. *
  316. * - `from` cannot be the zero address.
  317. * - `from` must have at least `value` amount of tokens of type `id`.
  318. * - `ids` and `values` must have the same length.
  319. */
  320. function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
  321. if (from == address(0)) {
  322. revert ERC1155InvalidSender(address(0));
  323. }
  324. _updateWithAcceptanceCheck(from, address(0), ids, values, "");
  325. }
  326. /**
  327. * @dev Approve `operator` to operate on all of `owner` tokens
  328. *
  329. * Emits an {ApprovalForAll} event.
  330. *
  331. * Requirements:
  332. *
  333. * - `operator` cannot be the zero address.
  334. */
  335. function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
  336. if (operator == address(0)) {
  337. revert ERC1155InvalidOperator(address(0));
  338. }
  339. _operatorApprovals[owner][operator] = approved;
  340. emit ApprovalForAll(owner, operator, approved);
  341. }
  342. /**
  343. * @dev Performs an acceptance check by calling {IERC1155-onERC1155Received} on the `to` address
  344. * if it contains code at the moment of execution.
  345. */
  346. function _doSafeTransferAcceptanceCheck(
  347. address operator,
  348. address from,
  349. address to,
  350. uint256 id,
  351. uint256 value,
  352. bytes memory data
  353. ) private {
  354. if (to.code.length > 0) {
  355. try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
  356. if (response != IERC1155Receiver.onERC1155Received.selector) {
  357. // Tokens rejected
  358. revert ERC1155InvalidReceiver(to);
  359. }
  360. } catch (bytes memory reason) {
  361. if (reason.length == 0) {
  362. // non-ERC1155Receiver implementer
  363. revert ERC1155InvalidReceiver(to);
  364. } else {
  365. /// @solidity memory-safe-assembly
  366. assembly {
  367. revert(add(32, reason), mload(reason))
  368. }
  369. }
  370. }
  371. }
  372. }
  373. /**
  374. * @dev Performs a batch acceptance check by calling {IERC1155-onERC1155BatchReceived} on the `to` address
  375. * if it contains code at the moment of execution.
  376. */
  377. function _doSafeBatchTransferAcceptanceCheck(
  378. address operator,
  379. address from,
  380. address to,
  381. uint256[] memory ids,
  382. uint256[] memory values,
  383. bytes memory data
  384. ) private {
  385. if (to.code.length > 0) {
  386. try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
  387. bytes4 response
  388. ) {
  389. if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
  390. // Tokens rejected
  391. revert ERC1155InvalidReceiver(to);
  392. }
  393. } catch (bytes memory reason) {
  394. if (reason.length == 0) {
  395. // non-ERC1155Receiver implementer
  396. revert ERC1155InvalidReceiver(to);
  397. } else {
  398. /// @solidity memory-safe-assembly
  399. assembly {
  400. revert(add(32, reason), mload(reason))
  401. }
  402. }
  403. }
  404. }
  405. }
  406. /**
  407. * @dev Creates an array in memory with only one value for each of the elements provided.
  408. */
  409. function _asSingletonArrays(
  410. uint256 element1,
  411. uint256 element2
  412. ) private pure returns (uint256[] memory array1, uint256[] memory array2) {
  413. /// @solidity memory-safe-assembly
  414. assembly {
  415. // Load the free memory pointer
  416. array1 := mload(0x40)
  417. // Set array length to 1
  418. mstore(array1, 1)
  419. // Store the single element at the next word after the length (where content starts)
  420. mstore(add(array1, 0x20), element1)
  421. // Repeat for next array locating it right after the first array
  422. array2 := add(array1, 0x40)
  423. mstore(array2, 1)
  424. mstore(add(array2, 0x20), element2)
  425. // Update the free memory pointer by pointing after the second array
  426. mstore(0x40, add(array2, 0x40))
  427. }
  428. }
  429. }