ERC1155Supply.sol 1.6 KB

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