ERC1155Supply.sol 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC1155.sol";
  5. /**
  6. * @dev Extension of ERC1155 that adds tracking of total supply per id.
  7. *
  8. * Useful for scenarios where Fungible and Non-fungible tokens have to be
  9. * clearly identified. Note: While a totalSupply of 1 might mean the
  10. * corresponding is an NFT, there is no guarantees that no other token with the
  11. * same id are not going to be minted.
  12. */
  13. abstract contract ERC1155Supply is ERC1155 {
  14. mapping(uint256 => uint256) private _totalSupply;
  15. /**
  16. * @dev Total amount of tokens in with a given id.
  17. */
  18. function totalSupply(uint256 id) public view virtual returns (uint256) {
  19. return _totalSupply[id];
  20. }
  21. /**
  22. * @dev Indicates whether any token exist with a given id, or not.
  23. */
  24. function exists(uint256 id) public view virtual returns (bool) {
  25. return ERC1155Supply.totalSupply(id) > 0;
  26. }
  27. /**
  28. * @dev See {ERC1155-_beforeTokenTransfer}.
  29. */
  30. function _beforeTokenTransfer(
  31. address operator,
  32. address from,
  33. address to,
  34. uint256[] memory ids,
  35. uint256[] memory amounts,
  36. bytes memory data
  37. ) internal virtual override {
  38. super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
  39. if (from == address(0)) {
  40. for (uint256 i = 0; i < ids.length; ++i) {
  41. _totalSupply[ids[i]] += amounts[i];
  42. }
  43. }
  44. if (to == address(0)) {
  45. for (uint256 i = 0; i < ids.length; ++i) {
  46. uint256 id = ids[i];
  47. uint256 amount = amounts[i];
  48. uint256 supply = _totalSupply[id];
  49. require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
  50. unchecked {
  51. _totalSupply[id] = supply - amount;
  52. }
  53. }
  54. }
  55. }
  56. }