ERC20Capped.sol 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/ERC20Capped.sol)
  3. pragma solidity ^0.8.20;
  4. import {ERC20} from "../ERC20.sol";
  5. /**
  6. * @dev Extension of {ERC20} that adds a cap to the supply of tokens.
  7. */
  8. abstract contract ERC20Capped is ERC20 {
  9. uint256 private immutable _cap;
  10. /**
  11. * @dev Total supply cap has been exceeded.
  12. */
  13. error ERC20ExceededCap(uint256 increasedSupply, uint256 cap);
  14. /**
  15. * @dev The supplied cap is not a valid cap.
  16. */
  17. error ERC20InvalidCap(uint256 cap);
  18. /**
  19. * @dev Sets the value of the `cap`. This value is immutable, it can only be
  20. * set once during construction.
  21. */
  22. constructor(uint256 cap_) {
  23. if (cap_ == 0) {
  24. revert ERC20InvalidCap(0);
  25. }
  26. _cap = cap_;
  27. }
  28. /**
  29. * @dev Returns the cap on the token's total supply.
  30. */
  31. function cap() public view virtual returns (uint256) {
  32. return _cap;
  33. }
  34. /// @inheritdoc ERC20
  35. function _update(address from, address to, uint256 value) internal virtual override {
  36. super._update(from, to, value);
  37. if (from == address(0)) {
  38. uint256 maxSupply = cap();
  39. uint256 supply = totalSupply();
  40. if (supply > maxSupply) {
  41. revert ERC20ExceededCap(supply, maxSupply);
  42. }
  43. }
  44. }
  45. }