ERC1155Supply.sol 2.7 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.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. uint256 private _totalSupplyAll;
  16. /**
  17. * @dev Total amount of tokens in with a given id.
  18. */
  19. function totalSupply(uint256 id) public view virtual returns (uint256) {
  20. return _totalSupply[id];
  21. }
  22. /**
  23. * @dev Total amount of tokens.
  24. */
  25. function totalSupply() public view virtual returns (uint256) {
  26. return _totalSupplyAll;
  27. }
  28. /**
  29. * @dev Indicates whether any token exist with a given id, or not.
  30. */
  31. function exists(uint256 id) public view virtual returns (bool) {
  32. return ERC1155Supply.totalSupply(id) > 0;
  33. }
  34. /**
  35. * @dev See {ERC1155-_update}.
  36. */
  37. function _update(
  38. address from,
  39. address to,
  40. uint256[] memory ids,
  41. uint256[] memory amounts,
  42. bytes memory data
  43. ) internal virtual override {
  44. if (from == address(0)) {
  45. uint256 totalMintAmount = 0;
  46. for (uint256 i = 0; i < ids.length; ++i) {
  47. uint256 amount = amounts[i];
  48. _totalSupply[ids[i]] += amount;
  49. totalMintAmount += amount;
  50. }
  51. _totalSupplyAll += totalMintAmount;
  52. }
  53. if (to == address(0)) {
  54. uint256 totalBurnAmount = 0;
  55. for (uint256 i = 0; i < ids.length; ++i) {
  56. uint256 id = ids[i];
  57. uint256 amount = amounts[i];
  58. uint256 supply = _totalSupply[id];
  59. require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
  60. unchecked {
  61. // Overflow not possible: amounts[i] <= totalSupply(i)
  62. _totalSupply[id] = supply - amount;
  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. }