ERC20Capped.sol 1.1 KB

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