ERC1155.sol 17 KB

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