NoncesKeyed.sol 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {Nonces} from "./Nonces.sol";
  4. /**
  5. * @dev Alternative to {Nonces}, that supports key-ed nonces.
  6. *
  7. * Follows the https://eips.ethereum.org/EIPS/eip-4337#semi-abstracted-nonce-support[ERC-4337's semi-abstracted nonce system].
  8. */
  9. abstract contract NoncesKeyed is Nonces {
  10. mapping(address owner => mapping(uint192 key => uint64)) private _nonces;
  11. /// @dev Returns the next unused nonce for an address and key. Result contains the key prefix.
  12. function nonces(address owner, uint192 key) public view virtual returns (uint256) {
  13. return key == 0 ? nonces(owner) : ((uint256(key) << 64) | _nonces[owner][key]);
  14. }
  15. /**
  16. * @dev Consumes the next unused nonce for an address and key.
  17. *
  18. * Returns the current value without the key prefix. Consumed nonce is increased, so calling this function twice
  19. * with the same arguments will return different (sequential) results.
  20. */
  21. function _useNonce(address owner, uint192 key) internal virtual returns (uint256) {
  22. // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
  23. // decremented or reset. This guarantees that the nonce never overflows.
  24. unchecked {
  25. // It is important to do x++ and not ++x here.
  26. return key == 0 ? _useNonce(owner) : _nonces[owner][key]++;
  27. }
  28. }
  29. /**
  30. * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
  31. *
  32. * This version takes the key and the nonce in a single uint256 parameter:
  33. * - use the first 8 bytes for the key
  34. * - use the last 24 bytes for the nonce
  35. */
  36. function _useCheckedNonce(address owner, uint256 keyNonce) internal virtual override {
  37. _useCheckedNonce(owner, uint192(keyNonce >> 64), uint64(keyNonce));
  38. }
  39. /**
  40. * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
  41. *
  42. * This version takes the key and the nonce as two different parameters.
  43. */
  44. function _useCheckedNonce(address owner, uint192 key, uint64 nonce) internal virtual {
  45. if (key == 0) {
  46. super._useCheckedNonce(owner, nonce);
  47. } else {
  48. uint256 current = _useNonce(owner, key);
  49. if (nonce != current) {
  50. revert InvalidAccountNonce(owner, current);
  51. }
  52. }
  53. }
  54. }