ERC20Permit.sol 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity >=0.6.5 <0.8.0;
  3. import "../token/ERC20/ERC20.sol";
  4. import "./IERC20Permit.sol";
  5. import "../cryptography/ECDSA.sol";
  6. import "../utils/Counters.sol";
  7. import "./EIP712.sol";
  8. /**
  9. * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
  10. * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
  11. *
  12. * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
  13. * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
  14. * need to send a transaction, and thus is not required to hold Ether at all.
  15. *
  16. * _Available since v3.4._
  17. */
  18. abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
  19. using Counters for Counters.Counter;
  20. mapping (address => Counters.Counter) private _nonces;
  21. // solhint-disable-next-line var-name-mixedcase
  22. bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
  23. /**
  24. * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
  25. *
  26. * It's a good idea to use the same `name` that is defined as the ERC20 token name.
  27. */
  28. constructor(string memory name) EIP712(name, "1") {
  29. }
  30. /**
  31. * @dev See {IERC20Permit-permit}.
  32. */
  33. function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
  34. // solhint-disable-next-line not-rely-on-time
  35. require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
  36. bytes32 structHash = keccak256(
  37. abi.encode(
  38. _PERMIT_TYPEHASH,
  39. owner,
  40. spender,
  41. value,
  42. _nonces[owner].current(),
  43. deadline
  44. )
  45. );
  46. bytes32 hash = _hashTypedDataV4(structHash);
  47. address signer = ECDSA.recover(hash, v, r, s);
  48. require(signer == owner, "ERC20Permit: invalid signature");
  49. _nonces[owner].increment();
  50. _approve(owner, spender, value);
  51. }
  52. /**
  53. * @dev See {IERC20Permit-nonces}.
  54. */
  55. function nonces(address owner) public view override returns (uint256) {
  56. return _nonces[owner].current();
  57. }
  58. /**
  59. * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
  60. */
  61. // solhint-disable-next-line func-name-mixedcase
  62. function DOMAIN_SEPARATOR() external view override returns (bytes32) {
  63. return _domainSeparatorV4();
  64. }
  65. }