Nonces.sol 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.19;
  3. /**
  4. * @dev Provides tracking nonces for addresses. Nonces will only increment.
  5. */
  6. abstract contract Nonces {
  7. /**
  8. * @dev The nonce used for an `account` is not the expected current nonce.
  9. */
  10. error InvalidAccountNonce(address account, uint256 currentNonce);
  11. mapping(address => uint256) private _nonces;
  12. /**
  13. * @dev Returns an address nonce.
  14. */
  15. function nonces(address owner) public view virtual returns (uint256) {
  16. return _nonces[owner];
  17. }
  18. /**
  19. * @dev Consumes a nonce.
  20. *
  21. * Returns the current value and increments nonce.
  22. */
  23. function _useNonce(address owner) internal virtual returns (uint256) {
  24. // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
  25. // decremented or reset. This guarantees that the nonce never overflows.
  26. unchecked {
  27. // It is important to do x++ and not ++x here.
  28. return _nonces[owner]++;
  29. }
  30. }
  31. /**
  32. * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
  33. */
  34. function _useCheckedNonce(address owner, uint256 nonce) internal virtual returns (uint256) {
  35. uint256 current = _useNonce(owner);
  36. if (nonce != current) {
  37. revert InvalidAccountNonce(owner, current);
  38. }
  39. return current;
  40. }
  41. }