You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.4 KiB
46 lines
1.4 KiB
// SPDX-License-Identifier: MIT
|
|
pragma solidity ^0.8.20;
|
|
|
|
/**
|
|
* @dev Provides tracking nonces for addresses. Nonces will only increment.
|
|
*/
|
|
abstract contract Nonces {
|
|
/**
|
|
* @dev The nonce used for an `account` is not the expected current nonce.
|
|
*/
|
|
error InvalidAccountNonce(address account, uint256 currentNonce);
|
|
|
|
mapping(address => uint256) private _nonces;
|
|
|
|
/**
|
|
* @dev Returns an the next unused nonce for an address.
|
|
*/
|
|
function nonces(address owner) public view virtual returns (uint256) {
|
|
return _nonces[owner];
|
|
}
|
|
|
|
/**
|
|
* @dev Consumes a nonce.
|
|
*
|
|
* Returns the current value and increments nonce.
|
|
*/
|
|
function _useNonce(address owner) internal virtual returns (uint256) {
|
|
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
|
|
// decremented or reset. This guarantees that the nonce never overflows.
|
|
unchecked {
|
|
// It is important to do x++ and not ++x here.
|
|
return _nonces[owner]++;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
|
|
*/
|
|
function _useCheckedNonce(address owner, uint256 nonce) internal virtual returns (uint256) {
|
|
uint256 current = _useNonce(owner);
|
|
if (nonce != current) {
|
|
revert InvalidAccountNonce(owner, current);
|
|
}
|
|
return current;
|
|
}
|
|
}
|
|
|