2023-01-10 14:16:32 +01:00
|
|
|
// SPDX-License-Identifier: MIT
|
2025-01-13 11:24:26 +01:00
|
|
|
pragma solidity 0.8.28;
|
2023-01-10 14:16:32 +01:00
|
|
|
|
|
|
|
|
contract Periods {
|
2025-01-24 09:22:21 +01:00
|
|
|
error Periods_InvalidSecondsPerPeriod();
|
|
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
type Period is uint64;
|
2023-01-10 14:16:32 +01:00
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
uint64 internal immutable _secondsPerPeriod;
|
2023-01-10 14:16:32 +01:00
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
constructor(uint64 secondsPerPeriod) {
|
2025-01-24 09:22:21 +01:00
|
|
|
if (secondsPerPeriod == 0) {
|
|
|
|
|
revert Periods_InvalidSecondsPerPeriod();
|
|
|
|
|
}
|
2023-01-23 11:57:10 +01:00
|
|
|
_secondsPerPeriod = secondsPerPeriod;
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
function _periodOf(uint64 timestamp) internal view returns (Period) {
|
2023-01-23 11:57:10 +01:00
|
|
|
return Period.wrap(timestamp / _secondsPerPeriod);
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
|
2023-01-19 16:47:29 +01:00
|
|
|
function _blockPeriod() internal view returns (Period) {
|
2025-02-20 06:54:41 +01:00
|
|
|
return _periodOf(uint64(block.timestamp));
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
|
2023-01-19 16:47:29 +01:00
|
|
|
function _nextPeriod(Period period) internal pure returns (Period) {
|
2023-01-10 14:16:32 +01:00
|
|
|
return Period.wrap(Period.unwrap(period) + 1);
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
function _periodStart(Period period) internal view returns (uint64) {
|
2023-01-23 11:57:10 +01:00
|
|
|
return Period.unwrap(period) * _secondsPerPeriod;
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
|
2025-02-20 06:54:41 +01:00
|
|
|
function _periodEnd(Period period) internal view returns (uint64) {
|
2023-01-19 16:47:29 +01:00
|
|
|
return _periodStart(_nextPeriod(period));
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
|
2023-01-19 16:47:29 +01:00
|
|
|
function _isBefore(Period a, Period b) internal pure returns (bool) {
|
2023-01-10 14:16:32 +01:00
|
|
|
return Period.unwrap(a) < Period.unwrap(b);
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-19 16:47:29 +01:00
|
|
|
function _isAfter(Period a, Period b) internal pure returns (bool) {
|
|
|
|
|
return _isBefore(b, a);
|
2023-01-10 14:16:32 +01:00
|
|
|
}
|
|
|
|
|
}
|