Nonces.sol 1.5 KB

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