ERC1155Supply.sol 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)
  3. pragma solidity ^0.8.19;
  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. * NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens
  14. * that can be minted.
  15. */
  16. abstract contract ERC1155Supply is ERC1155 {
  17. mapping(uint256 => uint256) private _totalSupply;
  18. uint256 private _totalSupplyAll;
  19. /**
  20. * @dev Total amount of tokens in with a given id.
  21. */
  22. function totalSupply(uint256 id) public view virtual returns (uint256) {
  23. return _totalSupply[id];
  24. }
  25. /**
  26. * @dev Total amount of tokens.
  27. */
  28. function totalSupply() public view virtual returns (uint256) {
  29. return _totalSupplyAll;
  30. }
  31. /**
  32. * @dev Indicates whether any token exist with a given id, or not.
  33. */
  34. function exists(uint256 id) public view virtual returns (bool) {
  35. return totalSupply(id) > 0;
  36. }
  37. /**
  38. * @dev See {ERC1155-_update}.
  39. */
  40. function _update(
  41. address from,
  42. address to,
  43. uint256[] memory ids,
  44. uint256[] memory amounts,
  45. bytes memory data
  46. ) internal virtual override {
  47. if (from == address(0)) {
  48. uint256 totalMintAmount = 0;
  49. for (uint256 i = 0; i < ids.length; ++i) {
  50. uint256 amount = amounts[i];
  51. _totalSupply[ids[i]] += amount;
  52. totalMintAmount += amount;
  53. }
  54. _totalSupplyAll += totalMintAmount;
  55. }
  56. if (to == address(0)) {
  57. uint256 totalBurnAmount = 0;
  58. for (uint256 i = 0; i < ids.length; ++i) {
  59. uint256 id = ids[i];
  60. uint256 amount = amounts[i];
  61. _totalSupply[id] -= amount;
  62. unchecked {
  63. // Overflow not possible: sum(amounts[i]) <= sum(totalSupply(i)) <= totalSupplyAll
  64. totalBurnAmount += amount;
  65. }
  66. }
  67. unchecked {
  68. // Overflow not possible: totalBurnAmount = sum(amounts[i]) <= sum(totalSupply(i)) <= totalSupplyAll
  69. _totalSupplyAll -= totalBurnAmount;
  70. }
  71. }
  72. super._update(from, to, ids, amounts, data);
  73. }
  74. }