ERC20Capped.sol 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. import "./ERC20.sol";
  4. /**
  5. * @dev Extension of {ERC20} that adds a cap to the supply of tokens.
  6. */
  7. abstract contract ERC20Capped is ERC20 {
  8. uint256 private _cap;
  9. /**
  10. * @dev Sets the value of the `cap`. This value is immutable, it can only be
  11. * set once during construction.
  12. */
  13. constructor (uint256 cap_) {
  14. require(cap_ > 0, "ERC20Capped: cap is 0");
  15. _cap = cap_;
  16. }
  17. /**
  18. * @dev Returns the cap on the token's total supply.
  19. */
  20. function cap() public view virtual returns (uint256) {
  21. return _cap;
  22. }
  23. /**
  24. * @dev See {ERC20-_beforeTokenTransfer}.
  25. *
  26. * Requirements:
  27. *
  28. * - minted tokens must not cause the total supply to go over the cap.
  29. */
  30. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
  31. super._beforeTokenTransfer(from, to, amount);
  32. if (from == address(0)) { // When minting tokens
  33. require(totalSupply() + amount <= _cap, "ERC20Capped: cap exceeded");
  34. }
  35. }
  36. }