Skip to content
Verified contractPartialBUSL-1.1

RiskRateOracle

Address0x241e9162b196e2dd9ef608cd2f016cd9be4f38ad
Balance

0 ETH

 

Transactions

2,170

 

Compiler

solc 0.8.34

 

Same code

4 more contracts

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,042,748
Creation transaction
0x15182179d2…06880bf6b5
Main copy (most transactions)
0x4789dc31…526c7955

contracts/oracles/RiskRateOracle.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import {BaseTimelockedOracle} from "./BaseTimelockedOracle.sol";
import {IDualSidedPremiumOracle, IOracleMetadata, ITenorRateOracle} from "../interfaces/External.sol";

/**
 * @title RiskRateOracle
 * @notice Oracle that stores tenor-bucketed LP risk premiums posted by the pricing engine.
 *         Each tenor stores **two** rates per post: an upper premium (charged on the
 *         BUY_FIXED side of a market pair) and a lower premium (charged on the
 *         BUY_FLOATING side). Both come from the same Monte Carlo TWAR distribution and
 *         must be co-posted to keep symmetric-quantile coherence.
 *
 *         Updates require EIP-712 signatures from N-of-M authorized signers.
 *         Admin and circuit breaker config inherits from BaseTimelockedOracle.
 *
 * @dev Two thin side-flagged wrappers (`UpgradableSidedPremiumOracle`) read either the up
 *      or lo rate via `getUpRateByTenor` / `getLoRateByTenor`. SwapCore points each
 *      market side at the appropriate wrapper. The inherited `ITenorRateOracle` surface
 *      (`getRateByTenor` / `getRates`) returns the up rate for back-compat.
 */
contract RiskRateOracle is BaseTimelockedOracle, IDualSidedPremiumOracle {

    // ============ Constants ============

    // H-02: the signed digest binds to `observedAt`, NOT to the on-chain
    // `forecastNonce`. A confirmation-dependent nonce let an untrusted relayer
    // holding two same-nonce quorum packets land the stale one and burn the
    // fresher correction (the nonce advances on whichever confirms first).
    // Replay/ordering is now enforced solely by strictly-increasing `observedAt`.
    bytes32 public constant RISK_PREMIUM_UPDATE_TYPEHASH = keccak256(
        "RiskPremiumUpdate(uint256 deadline,uint256 observedAt,bytes32 tenorsHash,bytes32 upRatesHash,bytes32 loRatesHash)"
    );

    // ============ Structs ============

    struct RiskPremium {
        int256 upRate;      // BUY_FIXED side premium (WAD)
        int256 loRate;      // BUY_FLOATING side premium (WAD)
        uint256 updatedAt;
    }

    // ============ State ============

    /// @notice Risk premiums keyed by tenor in seconds
    mapping(uint256 => RiskPremium) public riskPremiums;

    // ============ Events ============

    event RiskPremiumPosted(uint256 indexed tenorSeconds, int256 upRate, int256 loRate);

    // ============ Errors ============

    /// @notice A posted premium was negative on the up or lo side. The consumer
    ///         (Utils.getRiskPremiumOracleRate) reverts on a negative rate, so the
    ///         non-negativity it assumes is enforced here at the source.
    error NegativeRiskPremium(uint256 tenorSeconds, int256 rate);

    // ============ Constructor ============

    constructor(
        string memory _description,
        uint256 _maxAgeSec,
        uint256 _maxRateChangeWad,
        int256 _maxRateBoundWad,
        int256 _minRateBoundWad,
        int256 _absoluteMaxRate,
        int256 _absoluteMinRate,
        uint256 _minUpdateIntervalSec,
        uint256[] memory _tenorBuckets,
        address[] memory _initialSigners,
        uint256 _requiredSignatures,
        bool _isPausable
    )
        BaseTimelockedOracle(
            _description,
            _maxAgeSec,
            _maxRateChangeWad,
            _maxRateBoundWad,
            _minRateBoundWad,
            _absoluteMaxRate,
            _absoluteMinRate,
            _minUpdateIntervalSec,
            _tenorBuckets,
            _initialSigners,
            _requiredSignatures,
            _isPausable,
            "KairosRiskPremiumOracle",
            "1"
        )
    {}

    // ============ Storage Hooks ============

    /// @inheritdoc BaseTimelockedOracle
    /// @dev Default surface returns the up (BUY_FIXED side) rate. The lo side is read
    ///      via `getLoRateByTenor` / `getLoRates`; both wrappers route through the
    ///      side-specific accessors regardless.
    function _getStoredRate(uint256 tenorSeconds) internal view override returns (int256 rate, uint256 updatedAt) {
        RiskPremium storage r = riskPremiums[tenorSeconds];
        return (r.upRate, r.updatedAt);
    }

    function _getStoredUpRate(uint256 tenorSeconds) internal view returns (int256 rate, uint256 updatedAt) {
        RiskPremium storage r = riskPremiums[tenorSeconds];
        return (r.upRate, r.updatedAt);
    }

    function _getStoredLoRate(uint256 tenorSeconds) internal view returns (int256 rate, uint256 updatedAt) {
        RiskPremium storage r = riskPremiums[tenorSeconds];
        return (r.loRate, r.updatedAt);
    }

    /// @inheritdoc BaseTimelockedOracle
    /// @dev Both rate vectors share `updatedAt`, but we still check each side's value
    ///      against the new bounds — the up and lo rates can diverge enough that one
    ///      passes the new bounds while the other does not.
    function _allStoredRatesWithinBounds(int256 minBound, int256 maxBound)
        internal
        view
        override
        returns (bool ok, uint256 violatingTenor, int256 violatingRate)
    {
        uint256 len = tenorBuckets.length;
        for (uint256 i = 0; i < len; i++) {
            uint256 tenor = tenorBuckets[i];
            RiskPremium storage r = riskPremiums[tenor];
            if (r.updatedAt == 0) continue;
            if (r.upRate < minBound || r.upRate > maxBound) {
                return (false, tenor, r.upRate);
            }
            if (r.loRate < minBound || r.loRate > maxBound) {
                return (false, tenor, r.loRate);
            }
        }
        return (true, 0, 0);
    }

    /// @inheritdoc BaseTimelockedOracle
    /// @dev Wipe every tenor bucket so a forced bound activation leaves the oracle
    ///      in a "no-prior-post" state for both the up and lo sides. The next
    ///      `postRiskPremiums` will skip the delta check (prevUpdatedAt == 0) and
    ///      land any in-bounds curve in a single transaction.
    function _resetStoredRates() internal override {
        uint256 len = tenorBuckets.length;
        for (uint256 i = 0; i < len; i++) {
            delete riskPremiums[tenorBuckets[i]];
        }
    }

    // ============ Side-Specific Read Surface ============

    /// @inheritdoc IDualSidedPremiumOracle
    function getUpRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid) {
        uint256[] memory tenors = new uint256[](1);
        tenors[0] = tenorSeconds;
        (int256[] memory rates, bool valid) = _getRatesInternalWith(tenors, _getStoredUpRate);
        return (rates[0], valid);
    }

    /// @inheritdoc IDualSidedPremiumOracle
    function getLoRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid) {
        uint256[] memory tenors = new uint256[](1);
        tenors[0] = tenorSeconds;
        (int256[] memory rates, bool valid) = _getRatesInternalWith(tenors, _getStoredLoRate);
        return (rates[0], valid);
    }

    /// @inheritdoc IDualSidedPremiumOracle
    function getUpRates(uint256[] calldata tenorListSeconds) external view returns (int256[] memory rates, bool isValid) {
        uint256[] memory tenors = _toMemory(tenorListSeconds);
        return _getRatesInternalWith(tenors, _getStoredUpRate);
    }

    /// @inheritdoc IDualSidedPremiumOracle
    function getLoRates(uint256[] calldata tenorListSeconds) external view returns (int256[] memory rates, bool isValid) {
        uint256[] memory tenors = _toMemory(tenorListSeconds);
        return _getRatesInternalWith(tenors, _getStoredLoRate);
    }

    function _toMemory(uint256[] calldata tenors) private pure returns (uint256[] memory out) {
        out = new uint256[](tenors.length);
        for (uint256 i = 0; i < tenors.length; i++) out[i] = tenors[i];
    }

    // ============ Risk Premium Posting ============

    /**
     * @notice Post upper and lower risk premiums for every tenor bucket in a single tx.
     *         The two rate vectors are validated independently (bounds, rate-change delta
     *         vs each side's own previous storage) but share one cadence check, one
     *         signed digest, and one nonce increment.
     * @param tenors Tenor durations in seconds; must equal `tenorBuckets` exactly.
     * @param upRates Upper premium per tenor (WAD), charged to BUY_FIXED side.
     * @param loRates Lower premium per tenor (WAD), charged to BUY_FLOATING side.
     * @param observedAt Signer-attested time the off-chain premiums were observed (unix seconds).
     *        Range-checked against `maxAgeSec` and stored as each bucket's data timestamp,
     *        so a payload delayed between observation and relay cannot read as fresh.
     * @param deadline Timestamp after which the signatures are no longer valid.
     * @param signatures EIP-712 signatures sorted by recovered signer address.
     */
    function postRiskPremiums(
        uint256[] calldata tenors,
        int256[] calldata upRates,
        int256[] calldata loRates,
        uint256 observedAt,
        uint256 deadline,
        bytes[] calldata signatures
    ) external {
        _requireFreshObservation(observedAt);

        if (upRates.length != tenors.length) revert ArrayLengthMismatch();
        if (loRates.length != tenors.length) revert ArrayLengthMismatch();

        bytes32 structHash = keccak256(abi.encode(
            RISK_PREMIUM_UPDATE_TYPEHASH,
            deadline,
            observedAt,
            keccak256(abi.encodePacked(tenors)),
            keccak256(abi.encodePacked(upRates)),
            keccak256(abi.encodePacked(loRates))
        ));
        bytes32 digest = _hashTypedDataV4(structHash);

        _verifySignatures(digest, deadline, signatures);

        _validateTenorsAndCadence(tenors, observedAt);
        _validateRateVector(tenors, upRates, _getStoredUpRate, observedAt);
        _validateRateVector(tenors, loRates, _getStoredLoRate, observedAt);

        // Risk premiums must be non-negative on both sides. The inherited rate bounds
        // (minRateBoundWad) may be negative, but the consumer Utils.getRiskPremiumOracleRate
        // reverts (E612) on a negative rate, so a negative premium posted here would brick
        // buySwap for every market using this oracle until a non-negative premium lands.
        // Enforce the sign the consumer assumes at the source.
        for (uint256 i = 0; i < tenors.length; i++) {
            if (upRates[i] < 0) revert NegativeRiskPremium(tenors[i], upRates[i]);
            if (loRates[i] < 0) revert NegativeRiskPremium(tenors[i], loRates[i]);
        }

        // `observedAt` is stored as the data freshness timestamp.
        for (uint256 i = 0; i < tenors.length; i++) {
            riskPremiums[tenors[i]] = RiskPremium({
                upRate: upRates[i],
                loRate: loRates[i],
                updatedAt: observedAt
            });
            emit RiskPremiumPosted(tenors[i], upRates[i], loRates[i]);
        }
    }

    // ============ ERC-165 ============

    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override(BaseTimelockedOracle)
        returns (bool)
    {
        return interfaceId == type(IDualSidedPremiumOracle).interfaceId
            || super.supportsInterface(interfaceId);
    }

}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts/interfaces/IERC5267.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/ShortStrings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.20;

import {StorageSlot} from "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

@openzeppelin/contracts/utils/cryptography/EIP712.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

import {Strings} from "../Strings.sol";

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

contracts/interfaces/External.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

interface IWETH {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
}

// Minimal ERC20 interface for decimals detection
interface IERC20Decimals {
    function decimals() external view returns (uint8);
}

interface IBaseSwapRateOracle {
    function baseSwapRateWad() external view returns (uint256);
}

interface ICollateralPriceOracle {
    function collateralPriceWad() external view returns (uint256);
}

interface IChainlinkOracle {
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
}

/// @notice Shared metadata for all Kairos oracle types.
/// @dev Implementations that may be wrapped by `BaseUpgradableOracleWrapper` must
///      additionally implement ERC-165 `supportsInterface(bytes4)` advertising both
///      `IOracleMetadata` and the specific read interface they implement
///      (`IRateOracle` / `ITenorRateOracle` / `ICumulativeRateOracle`).
///      This is intentionally not enforced by the interface itself so existing
///      non-wrapped oracles continue to compile unchanged.
interface IOracleMetadata {
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
}

/// @notice Read-only rate oracle — provides a single spot rate
/// @dev Precondition for adapters backing a RateConvention.SpotRate or .SpotCompoundRate market:
///      getRate() MUST clamp (saturate, never revert or return isValid=false) readings below a
///      feed-specific negative floor. RateIndexLib accumulates rate·time into an index floored at
///      MIN_INDEX; unbounded negative accrual pins the index to that floor, and BOTH spot conventions
///      then understate the floating leg at settlement because accrual below the floor is dropped.
///      A floor bounds the decay rate and keeps the pinned regime unreachable in practice. See the
///      RateConvention notes in Types.sol. Returning isValid=false instead of clamping bricks index
///      updates and blocks settlement, so the bound must saturate.
///      The first-party adapters carry a constructor-configured `minRateWad` for exactly this
///      (ChainlinkAdapter, PythAdapter); a third-party adapter must implement the same saturation.
///      Note this is an accounting bound, not a liveness one: deriveRateFromIndex takes the
///      SpotCompoundRate log as a difference of logs on the raw indices, so a floored index no longer
///      truncates a ratio to 0 and can no longer revert settlement/liquidation/MTM.
interface IRateOracle is IOracleMetadata {
    function getRate() external view returns (int256 rate, bool isValid);
}

/// @notice Unified tenor-dependent rate oracle — used for both base rate and risk rate oracles
interface ITenorRateOracle is IOracleMetadata {
    function getRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    /// @notice Batch variant — returns interpolated rates for multiple tenors in a single call.
    ///         Used by SwapCore on the LP MtM critical path to amortise external-call overhead.
    function getRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
}

/// @notice Optional capability advertised by a base-rate oracle whose per-tenor quote is a full-tenor
///         compounded-equivalent (bumped) rate B — i.e. B·tenor/YEAR == exp(r·tenor/YEAR) − 1. A `true`
///         answer tells the interim (accrued-only) valuation to accrue the fixed leg on the compounded
///         curve so it tracks a convex Cumulative floating leg; oracles quoting a simple/un-bumped rate
///         return `false` (or omit this interface, treated as `false`) and keep straight-line accrual.
///
/// @dev    IMPLEMENTER CONTRACT for a `true` return: the per-tenor rate B returned by `getRateByTenor`
///         MUST satisfy the identity `1 + B·tenor/YEAR == exp(r·tenor/YEAR)`, where `r` is the
///         continuously-compounded rate the quote represents. The consuming valuation recovers
///         `r = ln(1 + B·tenor/YEAR)·YEAR/tenor` and re-accrues as `exp(r·elapsed/YEAR) − 1`
///         (see `SwapFormulas.calculateCompoundAccruedFixedPayment`), so the compounded mark is only
///         correct when B was produced by exactly this bump. An oracle that returns `true` but bumps
///         with a different convention is still valued far more accurately than a `false`/straight-line
///         quote (the error is the small gap between two nearby convex curves, and it vanishes at
///         maturity where both collapse to the straight line), but a NEW opt-in oracle SHOULD match the
///         identity above — verify it with a round-trip test before pointing a market at it.
interface ICompoundedTenorQuote {
    function isCompoundedTenorQuote() external view returns (bool);
}

/// @notice Attestation binding a base-rate oracle to the SINGLE observation ring whose
///         snapshots produce its per-tenor quote. The compounded (BUY_FIXED) base oracle and
///         its raw (BUY_FLOATING) counterpart of a Cumulative market pair MUST report the same
///         ring address, so both quotes are two transforms — `(exp(r·T/YEAR) − 1)·YEAR/T` and
///         `r` — of ONE realized reading. Because the bump is convex (`exp(x) − 1 ≥ x`), a shared
///         reading guarantees `compoundedQuote ≥ rawQuote` at every block, which makes a paired
///         equal-notional BUY_FIXED + BUY_FLOATING position (whose floating legs cancel on the
///         shared reference index) always loss-making — closing the independent-ring inversion
///         and, with it, the transient-liquidity amplification that depended on it.
/// @dev    `baseRateRing()` returns `address(0)` for an oracle with no such ring (e.g. a
///         Chainlink-fed spot oracle). `createMarket` rejects a pair where either side advertises
///         a ring but the two do not resolve to the same non-zero ring (E615). Self-attested, like
///         `ICompoundedTenorQuote`: it guards against wiring two independent rings, not against an
///         oracle that lies about its ring — base oracles wired into a market are already trusted
///         for pricing correctness. The canonical `RawIndexBaseRateV1` / `RawMorphoBaseRateV1`
///         prove the relationship structurally: they hold no ring of their own and read their
///         compounded parent's, so their `baseRateRing()` cannot diverge from what they quote.
interface ISharedRingBaseRate {
    function baseRateRing() external view returns (address);
}

/// @notice Dual-sided premium oracle — exposes per-tenor "upper" (BUY_FIXED) and
///         "lower" (BUY_FLOATING) premiums from a single posting. Read by side-flagged
///         wrappers; SwapCore points each market side at its corresponding wrapper.
interface IDualSidedPremiumOracle is IOracleMetadata {
    function getUpRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    function getLoRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid);
    function getUpRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
    function getLoRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid);
}

/// @notice For reference rate oracles that provide a cumulative index directly.
///         The cumulative index represents the total growth factor since some epoch,
///         normalized to RAY scale (1e27). Each adapter matches its source's native
///         convention (compound for Aave, simple for stETH, etc.).
interface ICumulativeRateOracle is IOracleMetadata {
    function getCumulativeIndex() external view returns (uint256 cumulativeIndex, bool isValid);
}

/// @notice Oracles that expose a permissionless keeper hook to advance their own
///         internal state (e.g. a TWAR ring buffer's observations). SwapCore opportunistically
///         calls this from `updateMarketRateIndex` and at market creation for any oracle slot
///         that advertises this interface via ERC-165. Implementations should be safe to call
///         from anyone and cheap to reject when called too early (e.g. revert `TooEarly`).
///         Pokeable oracles MUST also advertise `IPokeable` via `supportsInterface`.
interface IPokeable {
    function poke() external;
}

/// @notice Signed rate oracle — extends IRateOracle with EIP-712 N-of-M rate setting + admin
interface IKairosOracle is IRateOracle {
    function setRate(int256 newRate, uint256 deadline, bytes[] calldata signatures) external;
    function setMaxAge(uint256 newMaxAge) external;
    function setMaxRateChange(uint256 newMaxRateChange) external;
    function setRateBounds(int256 newMin, int256 newMax) external;
}

/// @notice Legacy owner-only oracle interface
interface IKairosOracleBeta {
    function setReferenceRate(int256 newRate) external;
    function getRate() external view returns (int256 rate, bool isValid);
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
}

contracts/oracles/BaseTimelockedOracle.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;

import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/External.sol";

/**
 * @title BaseTimelockedOracle
 * @notice Abstract base for tenor-bucketed oracles with EIP-712 N-of-M signer verification,
 *         timelocked admin, circuit breakers, and linear tenor interpolation.
 *
 *         Concrete children (FixedRatePricingOracle, RiskRateOracle) supply their own
 *         storage structs, posting logic, and EIP-712 typehash — inheriting ~600 lines
 *         of shared infrastructure from this contract.
 *
 * @dev Rates are stored in WAD format (18 decimals). Tenor interpolation uses linear
 *      interpolation between configured bucket points, with flat extrapolation BELOW the
 *      shortest bucket. Tenors beyond the longest bucket fail closed (`isValid = false`)
 *      rather than extrapolating, so the oracle never quotes a tenor it has no data for.
 */
abstract contract BaseTimelockedOracle is Ownable2Step, EIP712, ERC165, ITenorRateOracle {
    using EnumerableSet for EnumerableSet.AddressSet;

    // ============ Constants & Immutables ============

    uint256 public constant SIGNER_TIMELOCK = 3 days;

    /// @notice Sanity ceiling on the number of tenor buckets. A real rate curve is
    ///         ~15-20 points; this only blocks an absurd misconfiguration that would
    ///         make a full-vector post (every update must resubmit the complete set,
    ///         see `_validateTenorsAndCadence`) or an LP-valuation batch read too
    ///         gas-heavy to land. Sized with generous headroom for the heaviest child
    ///         (`RiskRateOracle` stores two vectors per tenor), so it never constrains
    ///         a legitimate curve. Constant, not a constructor param: the cap guards
    ///         against deploy/governance misconfiguration, so the deployer must not be
    ///         able to choose it.
    uint256 public constant MAX_TENOR_BUCKETS = 64;

    /// @notice Sanity ceiling on an individual tenor bucket (guards the tenor-gap sign
    ///         overflow). Combined with the strict-ascending requirement this bounds every
    ///         adjacent bucket gap to a value representable as a *positive* `int256`, which is what
    ///         `_interpolateFromMemory` needs for its range/offset arithmetic to keep the
    ///         sign it is supposed to have. Without it a gap above `type(int256).max`
    ///         casts negative and turns bounded interpolation into unbounded signed
    ///         extrapolation, so an ordinary in-range query can return a rate far outside
    ///         the immutable `[ABSOLUTE_MIN_RATE, ABSOLUTE_MAX_RATE]` envelope while still
    ///         reporting `isValid == true`. No legitimate curve comes anywhere near this
    ///         ceiling — it only blocks a deploy/governance misconfiguration.
    uint256 public constant MAX_TENOR_SECONDS = uint256(type(int256).max);

    /// @notice Ceiling on how far past `block.timestamp` a post's signature `deadline` may
    ///         sit, enforced in `_verifySignatures`. Posting is permissionless and the
    ///         signatures are the sole authorization, so an unposted signed payload is a
    ///         bearer instrument: without this bound its holder (a stalled-and-replaced
    ///         mempool transaction, a compromised RPC) could withhold a quorum-approved
    ///         curve and land it later against a reference state the signers never priced.
    ///         `maxAgeSec` does not close this — it bounds the data's age, not the holder's
    ///         timing discretion within it. Constant, not a constructor param: the bound
    ///         guards against signer/deploy configuration drift, so the deployer must not
    ///         be able to choose it. Sized with headroom above the poster's ~10-minute
    ///         per-attempt deadline buffer for congestion re-signing and quorum assembly.
    uint256 public constant MAX_DEADLINE_WINDOW_SEC = 1 hours;

    /// @notice Immutable absolute floor for rates (cannot be changed post-deploy)
    int256 public immutable ABSOLUTE_MIN_RATE;

    /// @notice Immutable absolute ceiling for rates (cannot be changed post-deploy)
    int256 public immutable ABSOLUTE_MAX_RATE;

    // ============ Structs ============

    struct PendingSignerChange {
        address signer;
        bool isAddition;
        uint256 activationTime;
    }

    struct PendingThresholdChange {
        uint256 newThreshold;
        uint256 activationTime;
    }

    struct PendingMaxAgeChange {
        uint256 newMaxAgeSec;
        uint256 activationTime;
    }

    struct PendingMaxRateChangeChange {
        uint256 newMaxRateChangeWad;
        uint256 activationTime;
    }

    struct PendingRateBoundsChange {
        int256 newMinRateBoundWad;
        int256 newMaxRateBoundWad;
        uint256 activationTime;
    }

    struct PendingMinUpdateIntervalChange {
        uint256 newMinUpdateIntervalSec;
        uint256 activationTime;
    }

    struct PendingTenorBucketsChange {
        uint256[] newTenorBuckets;
        uint256 activationTime;
    }

    struct PendingRevokePausabilityChange {
        uint256 activationTime;
    }

    // ============ State ============

    /// @notice Sorted array of tenor bucket points (in seconds)
    uint256[] public tenorBuckets;

    /// @notice Human-readable description
    string public description;

    /// @notice Maximum age in seconds before rates are considered stale
    uint256 public maxAgeSec;

    /// @notice Maximum absolute rate change allowed per update (WAD)
    uint256 public maxRateChangeWad;

    /// @notice Absolute upper bound for rates (WAD)
    int256 public maxRateBoundWad;

    /// @notice Absolute lower bound for rates (WAD)
    int256 public minRateBoundWad;

    /// @notice Minimum seconds between rate updates
    uint256 public minUpdateIntervalSec;

    /// @notice Timestamp of last successful post
    uint256 public lastPostTimestamp;

    /// @notice Observed (data) timestamp of the last accepted post. The posting cadence is
    ///         gated on this — not relay (`block.timestamp`) time — so a valid-but-near-stale
    ///         payload posted at the cadence boundary cannot reset the cooldown and lock out
    ///         fresher corrective posts while its stored observation expires.
    uint256 public lastObservedAt;

    /// @notice Set of authorized signers
    EnumerableSet.AddressSet internal _signers;

    /// @notice Minimum number of valid signatures required
    uint256 public requiredSignatures;

    /// @notice Monotonic post counter — advances once per accepted post. Retained
    ///         for off-chain telemetry/monitoring (indexer, poster logs) and left
    ///         as a public getter for back-compat. It is NOT part of the signed
    ///         EIP-712 digest and provides NO replay protection: binding signatures
    ///         to a confirmation-dependent nonce let a relayer holding two same-nonce
    ///         quorum packets land the stale one and burn the fresher correction (H-02).
    ///         Replay/ordering is now enforced by strictly-increasing signer-attested
    ///         `observedAt` (see `_validateTenorsAndCadence` / `_validateRateVector`).
    uint256 public forecastNonce;

    /// @notice When true, all rate reads return isValid = false
    bool public isPaused;

    /// @notice When true, the oracle can be paused. Once revoked, pausing is permanently disabled.
    bool public isPausable;

    // Pending timelocked changes
    PendingSignerChange public pendingSignerChange;
    PendingThresholdChange public pendingThresholdChange;
    PendingMaxAgeChange public pendingMaxAgeChange;
    PendingMaxRateChangeChange public pendingMaxRateChangeChange;
    PendingRateBoundsChange public pendingRateBoundsChange;
    PendingMinUpdateIntervalChange public pendingMinUpdateIntervalChange;
    PendingTenorBucketsChange internal _pendingTenorBucketsChange;
    PendingRevokePausabilityChange public pendingRevokePausability;

    // ============ Events ============

    event TenorBucketsUpdated(uint256[] newBuckets);
    event SignerAdded(address indexed signer);
    event SignerRemoved(address indexed signer);
    event RequiredSignaturesUpdated(uint256 oldValue, uint256 newValue);
    event SignerChangeQueued(address indexed signer, bool isAddition, uint256 activationTime);
    event SignerChangeCancelled(address indexed signer, bool isAddition);
    event ThresholdChangeQueued(uint256 newThreshold, uint256 activationTime);
    event ThresholdChangeCancelled(uint256 cancelledThreshold);
    event MaxAgeChangeQueued(uint256 newMaxAgeSec, uint256 activationTime);
    event MaxAgeChangeActivated(uint256 oldMaxAgeSec, uint256 newMaxAgeSec);
    event MaxAgeChangeCancelled(uint256 cancelledMaxAgeSec);
    event MaxRateChangeChangeQueued(uint256 newMaxRateChangeWad, uint256 activationTime);
    event MaxRateChangeChangeActivated(uint256 oldMaxRateChangeWad, uint256 newMaxRateChangeWad);
    event MaxRateChangeChangeCancelled(uint256 cancelledMaxRateChangeWad);
    event RateBoundsChangeQueued(int256 newMinRateBoundWad, int256 newMaxRateBoundWad, uint256 activationTime);
    event RateBoundsChangeActivated(int256 oldMinRateBoundWad, int256 oldMaxRateBoundWad, int256 newMinRateBoundWad, int256 newMaxRateBoundWad, bool forced);
    event RateBoundsChangeCancelled(int256 cancelledMinRateBoundWad, int256 cancelledMaxRateBoundWad);
    event StoredRatesReset();
    event MinUpdateIntervalChangeQueued(uint256 newMinUpdateIntervalSec, uint256 activationTime);
    event MinUpdateIntervalChangeActivated(uint256 oldMinUpdateIntervalSec, uint256 newMinUpdateIntervalSec);
    event MinUpdateIntervalChangeCancelled(uint256 cancelledMinUpdateIntervalSec);
    event TenorBucketsChangeQueued(uint256[] newTenorBuckets, uint256 activationTime);
    event TenorBucketsChangeCancelled();
    event Paused();
    event Unpaused();
    event RevokePausabilityQueued(uint256 activationTime);
    event RevokePausabilityCancelled();
    event PausabilityRevoked();

    // ============ Errors ============

    error InvalidMaxAge();
    error InvalidBounds();
    error InvalidMaxRateChange();
    error BoundsExceedAbsoluteLimits();
    error ArrayLengthMismatch();
    error EmptyArray();
    error TenorBucketsNotSorted();
    error TooManyTenorBuckets(uint256 provided, uint256 max);
    error TenorBucketTooLarge(uint256 tenorSeconds, uint256 max);
    error TenorBucketsUnchanged();
    error RateExceedsBounds(uint256 tenorSeconds, int256 rate);
    error RateChangeTooLarge(uint256 tenorSeconds, int256 oldRate, int256 newRate, uint256 delta);
    error ObservationNotNewer(uint256 tenorSeconds, uint256 observedAt, uint256 prevObservedAt);
    error TenorCountMismatch(uint256 expected, uint256 actual);
    error TenorMismatch(uint256 expected, uint256 actual);
    error UpdateTooFrequent(uint256 lastUpdate, uint256 minInterval);
    error DeadlineExpired();
    error DeadlineTooFar(uint256 deadline, uint256 maxDeadline);
    error InsufficientSignatures(uint256 provided, uint256 required);
    error UnauthorizedSigner(address recovered);
    error DuplicateOrUnsortedSigner(address signer);
    error InvalidSignerAddress();
    error SignerAlreadyAuthorized(address signer);
    error SignerNotAuthorized(address signer);
    error InvalidRequiredSignatures();
    error NoPendingSignerChange();
    error NoPendingThresholdChange();
    error NoPendingMaxAgeChange();
    error NoPendingMaxRateChangeChange();
    error NoPendingRateBoundsChange();
    error NoPendingMinUpdateIntervalChange();
    error NoPendingTenorBucketsChange();
    error NoPendingRevokePausability();
    error ChangeAlreadyPending();
    error TimelockNotElapsed(uint256 activationTime);
    error NoSignersProvided();
    error InvalidMinUpdateInterval();
    error NotPausable();
    error AlreadyPaused();
    error NotPaused();
    error StoredRateOutsideNewBounds(uint256 tenorSeconds, int256 rate, int256 newMinRateBoundWad, int256 newMaxRateBoundWad);
    error ObservedAtInFuture(uint256 observedAt);
    error ObservedAtTooStale(uint256 observedAt);
    error RenounceOwnershipDisabled();

    // ============ Constructor ============

    constructor(
        string memory _description,
        uint256 _maxAgeSec,
        uint256 _maxRateChangeWad,
        int256 _maxRateBoundWad,
        int256 _minRateBoundWad,
        int256 _absoluteMaxRate,
        int256 _absoluteMinRate,
        uint256 _minUpdateIntervalSec,
        uint256[] memory _tenorBuckets,
        address[] memory _initialSigners,
        uint256 _requiredSignatures,
        bool _isPausable,
        string memory _eip712Name,
        string memory _eip712Version
    ) Ownable(msg.sender) EIP712(_eip712Name, _eip712Version) {
        if (_maxAgeSec == 0 || _maxAgeSec > SIGNER_TIMELOCK) revert InvalidMaxAge();
        if (_maxRateChangeWad == 0) revert InvalidMaxRateChange();
        // `minUpdateIntervalSec` must not exceed `maxAgeSec`: otherwise a post can land,
        // go stale after `maxAgeSec`, and still be inside the posting cooldown — leaving
        // a forced `isValid=false` window that signers cannot close.
        if (_minUpdateIntervalSec == 0 || _minUpdateIntervalSec > _maxAgeSec) {
            revert InvalidMinUpdateInterval();
        }
        if (_maxRateBoundWad <= _minRateBoundWad) revert InvalidBounds();
        if (_absoluteMaxRate <= _absoluteMinRate) revert InvalidBounds();
        if (_minRateBoundWad < _absoluteMinRate || _maxRateBoundWad > _absoluteMaxRate) {
            revert BoundsExceedAbsoluteLimits();
        }
        _validateTenorBuckets(_tenorBuckets);
        if (_initialSigners.length == 0) revert NoSignersProvided();
        if (_requiredSignatures == 0 || _requiredSignatures > _initialSigners.length) {
            revert InvalidRequiredSignatures();
        }

        ABSOLUTE_MIN_RATE = _absoluteMinRate;
        ABSOLUTE_MAX_RATE = _absoluteMaxRate;

        description = _description;
        maxAgeSec = _maxAgeSec;
        maxRateChangeWad = _maxRateChangeWad;
        maxRateBoundWad = _maxRateBoundWad;
        minRateBoundWad = _minRateBoundWad;
        minUpdateIntervalSec = _minUpdateIntervalSec;
        tenorBuckets = _tenorBuckets;
        requiredSignatures = _requiredSignatures;
        isPausable = _isPausable;

        for (uint256 i = 0; i < _initialSigners.length; i++) {
            if (_initialSigners[i] == address(0)) revert InvalidSignerAddress();
            bool added = _signers.add(_initialSigners[i]);
            if (!added) revert SignerAlreadyAuthorized(_initialSigners[i]);
            emit SignerAdded(_initialSigners[i]);
        }
    }

    // ============ Virtual Hook ============

    /**
     * @notice Returns the stored rate and its update timestamp for a given tenor bucket.
     * @dev Children implement this to read from their own storage (e.g. forecasts, riskRates).
     */
    function _getStoredRate(uint256 tenorSeconds) internal view virtual returns (int256 rate, uint256 updatedAt);

    // ============ ITenorRateOracle ============

    /// @inheritdoc ITenorRateOracle
    function getRateByTenor(uint256 tenorSeconds) external view returns (int256 rate, bool isValid) {
        uint256[] memory tenors = new uint256[](1);
        tenors[0] = tenorSeconds;
        (int256[] memory rates, bool valid) = _getRatesInternal(tenors);
        return (rates[0], valid);
    }

    /// @inheritdoc ITenorRateOracle
    function getRates(uint256[] calldata tenorSeconds) external view returns (int256[] memory rates, bool isValid) {
        return _getRatesInternal(tenorSeconds);
    }

    /// @inheritdoc IOracleMetadata
    function decimals() external pure returns (uint8) {
        return 18;
    }

    // ============ Signature Verification ============

    /**
     * @notice Verifies EIP-712 signatures from N-of-M authorized signers.
     * @param digest The EIP-712 typed data hash
     * @param deadline Timestamp after which signatures are no longer valid. Must lie
     *        within `MAX_DEADLINE_WINDOW_SEC` of the current block, bounding every
     *        payload's total shelf life regardless of what the signer stamped.
     * @param signatures Array of signatures sorted by signer address (ascending)
     */
    function _verifySignatures(bytes32 digest, uint256 deadline, bytes[] calldata signatures) internal {
        if (block.timestamp > deadline) revert DeadlineExpired();
        if (deadline > block.timestamp + MAX_DEADLINE_WINDOW_SEC) {
            revert DeadlineTooFar(deadline, block.timestamp + MAX_DEADLINE_WINDOW_SEC);
        }
        if (signatures.length < requiredSignatures) {
            revert InsufficientSignatures(signatures.length, requiredSignatures);
        }

        address lastSigner = address(0);
        for (uint256 i = 0; i < signatures.length; i++) {
            address recovered = ECDSA.recover(digest, signatures[i]);
            if (!_signers.contains(recovered)) revert UnauthorizedSigner(recovered);
            if (recovered <= lastSigner) revert DuplicateOrUnsortedSigner(recovered);
            lastSigner = recovered;
        }

        // Telemetry only — the digest above does NOT bind to this value (H-02).
        // Replay protection is enforced downstream by strictly-increasing `observedAt`.
        forecastNonce++;
    }

    // ============ Core Rate Validation ============

    /**
     * @notice Validates rate constraints (bounds, rate change, interval, tenor matching).
     * @dev Single-rate-vector entry point. Children with multiple rate vectors per
     *      post (e.g. `RiskRateOracle` with up/lo premiums) call
     *      `_validateTenorsAndCadence` once and `_validateRateVector` per vector
     *      with side-specific previous-rate accessors.
     */
    function _validateCoreRateConstraints(
        uint256[] calldata tenors,
        int256[] calldata rates,
        uint256 observedAt
    ) internal {
        // Pre-check rate-vector length so existing single-vector callers still see
        // `ArrayLengthMismatch` before tenor-set / cadence errors. Multi-vector
        // children (`RiskRateOracle.postRiskPremiums`) check each vector's length
        // up front in their own bodies before invoking the helpers below.
        if (rates.length != tenors.length) revert ArrayLengthMismatch();
        _validateTenorsAndCadence(tenors, observedAt);
        _validateRateVector(tenors, rates, _defaultPrevRate, observedAt);
    }

    /**
     * @notice Empty / cadence / tenor-set checks. Mutates `lastPostTimestamp` and
     *         `lastObservedAt`; the cadence cooldown is gated on `observedAt`.
     * @dev Must be called exactly once per post even when multiple rate vectors
     *      are validated, otherwise the cadence check fails on the second call.
     * @param observedAt Signer-attested observation time of this post. The cadence is
     *        measured against the previous post's observation time, not relay time, so a
     *        near-stale payload cannot reset the cooldown against fresher corrective posts.
     */
    function _validateTenorsAndCadence(uint256[] calldata tenors, uint256 observedAt) internal {
        uint256 len = tenors.length;
        if (len == 0) revert EmptyArray();

        // Gate the cooldown on OBSERVATION time, mirroring the observation-time delta gate in
        // `_validateRateVector`. The `observedAt < lastObservedAt + minUpdateIntervalSec` form
        // avoids underflow and cleanly rejects an out-of-order (older) observation with
        // `UpdateTooFrequent` rather than an arithmetic panic.
        if (lastObservedAt > 0 && observedAt < lastObservedAt + minUpdateIntervalSec) {
            revert UpdateTooFrequent(lastObservedAt, minUpdateIntervalSec);
        }

        if (len != tenorBuckets.length) revert TenorCountMismatch(tenorBuckets.length, len);

        for (uint256 i = 0; i < len; i++) {
            if (tenors[i] != tenorBuckets[i]) revert TenorMismatch(tenorBuckets[i], tenors[i]);
        }

        lastPostTimestamp = block.timestamp;
        lastObservedAt = observedAt;
    }

    /**
     * @notice Per-tenor bounds + rate-change-delta check for one rate vector against
     *         a side-specific previous-rate accessor.
     * @dev `prevRateFn` is an internal function pointer so children with multiple
     *      sides can validate up and lo independently — each side's delta is
     *      compared to its own previous storage, not a shared default.
     * @param observedAt Signer-attested observation time of this post (freshness-bounded
     *        vs `block.timestamp` by `_requireFreshObservation` at the caller). The
     *        rate-change breaker is gated on the OBSERVATION-time gap to the previous post,
     *        not the relay (`block.timestamp`) gap — see the delta check below.
     */
    function _validateRateVector(
        uint256[] calldata tenors,
        int256[] calldata rates,
        function(uint256) internal view returns (int256, uint256) prevRateFn,
        uint256 observedAt
    ) internal view {
        uint256 len = tenors.length;
        if (rates.length != len) revert ArrayLengthMismatch();

        for (uint256 i = 0; i < len; i++) {
            int256 newRate = rates[i];

            if (newRate < minRateBoundWad || newRate > maxRateBoundWad) {
                revert RateExceedsBounds(tenors[i], newRate);
            }

            (int256 prevRate, uint256 prevUpdatedAt) = prevRateFn(tenors[i]);
            if (prevUpdatedAt > 0) {
                // Observations must advance per tenor. Reject a post whose attested
                // observation is not strictly newer than the stored one — that is stale or
                // replayed data, and posting an older `observedAt` must not be a way to
                // duck the rate-change breaker (and it would underflow the gap below).
                if (observedAt <= prevUpdatedAt) {
                    revert ObservationNotNewer(tenors[i], observedAt, prevUpdatedAt);
                }
                // Gate the rate-change breaker on the OBSERVATION-time gap, not the relay
                // (block.timestamp) gap. Otherwise a relayer could stall submission until
                // `block.timestamp - prevUpdatedAt` exceeds maxAgeSec and skip the delta
                // check while still posting a fresh `observedAt`. A genuine
                // gap wider than maxAgeSec between observations still relaxes the breaker,
                // as before — but it is the data gap that matters, not the relay delay.
                if (observedAt - prevUpdatedAt <= maxAgeSec) {
                    uint256 delta = _absDiff(newRate, prevRate);
                    if (delta > maxRateChangeWad) {
                        revert RateChangeTooLarge(tenors[i], prevRate, newRate, delta);
                    }
                }
            }
        }
    }

    /// @dev Concrete forwarder so internal-function-pointer references resolve
    ///      via the abstract `_getStoredRate` virtual dispatch at runtime.
    function _defaultPrevRate(uint256 tenorSeconds) internal view returns (int256, uint256) {
        return _getStoredRate(tenorSeconds);
    }

    // ============ View Functions ============

    function tenorBucketCount() external view returns (uint256) {
        return tenorBuckets.length;
    }

    function getSigners() external view returns (address[] memory) {
        return _signers.values();
    }

    function signerCount() external view returns (uint256) {
        return _signers.length();
    }

    function isSigner(address account) external view returns (bool) {
        return _signers.contains(account);
    }

    function domainSeparator() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    function pendingTenorBucketsChange() external view returns (uint256[] memory newTenorBuckets, uint256 activationTime) {
        return (_pendingTenorBucketsChange.newTenorBuckets, _pendingTenorBucketsChange.activationTime);
    }

    // ============ Pause Functions ============

    function pause() external onlyOwner {
        if (!isPausable) revert NotPausable();
        if (isPaused) revert AlreadyPaused();
        isPaused = true;
        emit Paused();
    }

    function unpause() external onlyOwner {
        if (!isPaused) revert NotPaused();
        isPaused = false;
        emit Unpaused();
    }

    /**
     * @notice Disabled. OpenZeppelin's `Ownable.renounceOwnership` is a
     *         single-tx, no-timelock path to `owner() == address(0)` — renouncing while
     *         `isPaused` is true would leave every rate read permanently
     *         `isValid = false` with no account able to call `unpause()`, and it would
     *         strand any pending timelocked governance change. The contract already
     *         treats removal of emergency controls as a timelocked operation: use
     *         `queueRevokePausability` → `activateRevokePausability` (which clears
     *         `isPaused`) instead. Ownership remains transferable via the
     *         `Ownable2Step` two-step handshake.
     */
    function renounceOwnership() public pure override {
        revert RenounceOwnershipDisabled();
    }

    // ============ Timelocked Revoke Pausability ============

    function queueRevokePausability() external onlyOwner {
        if (!isPausable) revert NotPausable();
        if (pendingRevokePausability.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingRevokePausability = PendingRevokePausabilityChange({activationTime: activation});
        emit RevokePausabilityQueued(activation);
    }

    function activateRevokePausability() external onlyOwner {
        PendingRevokePausabilityChange memory pending = pendingRevokePausability;
        if (pending.activationTime == 0) revert NoPendingRevokePausability();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);

        isPausable = false;
        isPaused = false;
        emit PausabilityRevoked();
        delete pendingRevokePausability;
    }

    function cancelRevokePausability() external onlyOwner {
        if (pendingRevokePausability.activationTime == 0) revert NoPendingRevokePausability();
        emit RevokePausabilityCancelled();
        delete pendingRevokePausability;
    }

    // ============ Timelocked Tenor Buckets ============

    /**
     * @notice Queue a timelocked replacement of the active tenor bucket set.
     *
     * @dev A set element-for-element identical to the active one is rejected with
     *      `TenorBucketsUnchanged`. Activation is a hard reset — it wipes every
     *      stored rate and zeroes `lastObservedAt` — so the next post is treated as a first
     *      post and skips BOTH continuity checks: the `maxRateChangeWad` delta check
     *      (`_validateRateVector` only applies it when the previous `updatedAt` is nonzero)
     *      and the `minUpdateIntervalSec` cadence check (`_validateTenorsAndCadence` only
     *      applies it when `lastObservedAt` is nonzero). Without this guard a no-op update
     *      was a governance-reachable way to clear both checks for the *unchanged* bucket
     *      set, letting the next post move any tenor to any in-bounds value at any cadence.
     *
     *      Gating the queue gates activation. `activateTenorBucketsChange` installs the queued
     *      set verbatim and is — after the constructor — the only writer of `tenorBuckets`;
     *      it requires a pending change, and `ChangeAlreadyPending` permits only one at a
     *      time. So the active set cannot move between a change being queued and that same
     *      change activating, and a set that differs at queue time still differs at
     *      activation. Neither function is `virtual`, so no child can widen this.
     *
     *      Residual caveat (accepted by design). A *genuine* bucket change still resets
     *      forecast history, so the first post for the new set is a fresh initialization that
     *      legitimately skips both continuity checks. That reset is required for correctness
     *      — rates attested under the old geometry are not a valid baseline for the new one,
     *      and leaving them would let a read interpolate an unattested curve — so it cannot be
     *      removed, only kept behind an actual change of the bucket set.
     */
    function setTenorBuckets(uint256[] calldata _tenorBuckets) external onlyOwner {
        _validateTenorBuckets(_tenorBuckets);
        if (_sameAsActiveTenorBuckets(_tenorBuckets)) revert TenorBucketsUnchanged();
        if (_pendingTenorBucketsChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        _pendingTenorBucketsChange.newTenorBuckets = _tenorBuckets;
        _pendingTenorBucketsChange.activationTime = activation;
        emit TenorBucketsChangeQueued(_tenorBuckets, activation);
    }

    /**
     * @notice Install a queued tenor bucket set, clearing all rate history attested under the
     *         previous configuration.
     *
     * @dev The queued set is guaranteed to differ from the active one: `setTenorBuckets`
     *      rejects a no-op with `TenorBucketsUnchanged`, and the active set
     *      cannot move during the timelock window — see the reasoning on `setTenorBuckets`.
     *      No re-check is done here for that reason; the queue-time gate is not a
     *      "queue-time-valid, activation-time-stale" parameter the way `maxAgeSec` and
     *      `minUpdateIntervalSec` are (those two re-validate on activation because a sibling
     *      change *can* land in between).
     *
     *      The reset below makes the next post a first post for the new set — it skips the
     *      `maxRateChangeWad` and `minUpdateIntervalSec` continuity checks. That is inherent
     *      to a genuine bucket change and is the accepted residual documented on
     *      `setTenorBuckets`; what the queue-time gate removes is the ability to reach this
     *      reset *without* changing the bucket set.
     */
    function activateTenorBucketsChange() external onlyOwner {
        PendingTenorBucketsChange storage pending = _pendingTenorBucketsChange;
        if (pending.activationTime == 0) revert NoPendingTenorBucketsChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);

        // Clear every rate attested under the prior bucket configuration before
        // installing the new set. Without this, any tenor shared between the old and
        // new sets keeps its stored rate + updatedAt, so a read can interpolate an
        // unattested curve over the new configuration (or extrapolate from a lone
        // survivor) instead of failing closed until a fresh full-curve post lands.
        // Resetting *before* reassigning iterates the outgoing buckets, so dropped
        // tenors are wiped too and no orphaned stored rate survives the change.
        _resetStoredRates();
        tenorBuckets = pending.newTenorBuckets;
        // Every bucket in the new set now reads as never-posted (updatedAt == 0), so
        // reads fail closed until fresh rates land. Reset the cadence so signers can
        // post the new set immediately instead of waiting out minUpdateIntervalSec.
        lastPostTimestamp = 0;
        lastObservedAt = 0;
        emit StoredRatesReset();
        emit TenorBucketsUpdated(pending.newTenorBuckets);
        delete _pendingTenorBucketsChange;
    }

    function cancelTenorBucketsChange() external onlyOwner {
        if (_pendingTenorBucketsChange.activationTime == 0) revert NoPendingTenorBucketsChange();
        emit TenorBucketsChangeCancelled();
        delete _pendingTenorBucketsChange;
    }

    // ============ Timelocked Signer Management ============

    function queueAddSigner(address signer) external onlyOwner {
        if (signer == address(0)) revert InvalidSignerAddress();
        if (_signers.contains(signer)) revert SignerAlreadyAuthorized(signer);
        if (pendingSignerChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingSignerChange = PendingSignerChange({signer: signer, isAddition: true, activationTime: activation});
        emit SignerChangeQueued(signer, true, activation);
    }

    function queueRemoveSigner(address signer) external onlyOwner {
        if (!_signers.contains(signer)) revert SignerNotAuthorized(signer);
        if (pendingSignerChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingSignerChange = PendingSignerChange({signer: signer, isAddition: false, activationTime: activation});
        emit SignerChangeQueued(signer, false, activation);
    }

    function activateSignerChange() external onlyOwner {
        PendingSignerChange memory pending = pendingSignerChange;
        if (pending.activationTime == 0) revert NoPendingSignerChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);

        if (pending.isAddition) {
            _signers.add(pending.signer);
            emit SignerAdded(pending.signer);
        } else {
            if (_signers.length() - 1 < requiredSignatures) revert InvalidRequiredSignatures();
            _signers.remove(pending.signer);
            emit SignerRemoved(pending.signer);
        }

        delete pendingSignerChange;
    }

    function cancelSignerChange() external onlyOwner {
        PendingSignerChange memory pending = pendingSignerChange;
        if (pending.activationTime == 0) revert NoPendingSignerChange();
        emit SignerChangeCancelled(pending.signer, pending.isAddition);
        delete pendingSignerChange;
    }

    function queueRequiredSignatures(uint256 newThreshold) external onlyOwner {
        if (newThreshold == 0 || newThreshold > _signers.length()) revert InvalidRequiredSignatures();
        if (pendingThresholdChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingThresholdChange = PendingThresholdChange({newThreshold: newThreshold, activationTime: activation});
        emit ThresholdChangeQueued(newThreshold, activation);
    }

    function activateRequiredSignatures() external onlyOwner {
        PendingThresholdChange memory pending = pendingThresholdChange;
        if (pending.activationTime == 0) revert NoPendingThresholdChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);
        if (pending.newThreshold == 0 || pending.newThreshold > _signers.length()) revert InvalidRequiredSignatures();

        uint256 oldValue = requiredSignatures;
        requiredSignatures = pending.newThreshold;
        emit RequiredSignaturesUpdated(oldValue, pending.newThreshold);
        delete pendingThresholdChange;
    }

    function cancelRequiredSignatures() external onlyOwner {
        PendingThresholdChange memory pending = pendingThresholdChange;
        if (pending.activationTime == 0) revert NoPendingThresholdChange();
        emit ThresholdChangeCancelled(pending.newThreshold);
        delete pendingThresholdChange;
    }

    // ============ Timelocked Circuit Breaker Management ============

    // --- Max Age ---

    function queueMaxAgeChange(uint256 _maxAgeSec) external onlyOwner {
        if (_maxAgeSec == 0 || _maxAgeSec > SIGNER_TIMELOCK) revert InvalidMaxAge();
        // Keep the `minUpdateIntervalSec <= maxAgeSec` invariant — a
        // shorter `maxAgeSec` must not drop below the posting cooldown. Validate
        // against the lower of the active and pending cooldown so both parameters
        // can be tightened within one timelock window; `activateMaxAgeChange`
        // re-checks against the active value, so the pending cooldown decrease
        // must activate first, and cancelling it cannot yield an invalid config.
        uint256 effectiveMinInterval = minUpdateIntervalSec;
        PendingMinUpdateIntervalChange memory pendingInterval = pendingMinUpdateIntervalChange;
        if (pendingInterval.activationTime != 0 && pendingInterval.newMinUpdateIntervalSec < effectiveMinInterval) {
            effectiveMinInterval = pendingInterval.newMinUpdateIntervalSec;
        }
        if (_maxAgeSec < effectiveMinInterval) revert InvalidMaxAge();
        if (pendingMaxAgeChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingMaxAgeChange = PendingMaxAgeChange({newMaxAgeSec: _maxAgeSec, activationTime: activation});
        emit MaxAgeChangeQueued(_maxAgeSec, activation);
    }

    function activateMaxAgeChange() external onlyOwner {
        PendingMaxAgeChange memory pending = pendingMaxAgeChange;
        if (pending.activationTime == 0) revert NoPendingMaxAgeChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);
        // Re-check the `minUpdateIntervalSec <= maxAgeSec` invariant:
        // `minUpdateIntervalSec` may have been raised by a separate change activated
        // during this timelock window, so a queue-time-valid value can be stale here.
        if (pending.newMaxAgeSec < minUpdateIntervalSec) revert InvalidMaxAge();

        uint256 oldValue = maxAgeSec;
        maxAgeSec = pending.newMaxAgeSec;
        emit MaxAgeChangeActivated(oldValue, pending.newMaxAgeSec);
        delete pendingMaxAgeChange;
    }

    function cancelMaxAgeChange() external onlyOwner {
        PendingMaxAgeChange memory pending = pendingMaxAgeChange;
        if (pending.activationTime == 0) revert NoPendingMaxAgeChange();
        emit MaxAgeChangeCancelled(pending.newMaxAgeSec);
        delete pendingMaxAgeChange;
    }

    // --- Max Rate Change ---

    function queueMaxRateChangeChange(uint256 _maxRateChangeWad) external onlyOwner {
        if (_maxRateChangeWad == 0) revert InvalidMaxRateChange();
        if (pendingMaxRateChangeChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingMaxRateChangeChange = PendingMaxRateChangeChange({newMaxRateChangeWad: _maxRateChangeWad, activationTime: activation});
        emit MaxRateChangeChangeQueued(_maxRateChangeWad, activation);
    }

    function activateMaxRateChangeChange() external onlyOwner {
        PendingMaxRateChangeChange memory pending = pendingMaxRateChangeChange;
        if (pending.activationTime == 0) revert NoPendingMaxRateChangeChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);

        uint256 oldValue = maxRateChangeWad;
        maxRateChangeWad = pending.newMaxRateChangeWad;
        emit MaxRateChangeChangeActivated(oldValue, pending.newMaxRateChangeWad);
        delete pendingMaxRateChangeChange;
    }

    function cancelMaxRateChangeChange() external onlyOwner {
        PendingMaxRateChangeChange memory pending = pendingMaxRateChangeChange;
        if (pending.activationTime == 0) revert NoPendingMaxRateChangeChange();
        emit MaxRateChangeChangeCancelled(pending.newMaxRateChangeWad);
        delete pendingMaxRateChangeChange;
    }

    // --- Rate Bounds ---

    function queueRateBoundsChange(int256 _minRateBoundWad, int256 _maxRateBoundWad) external onlyOwner {
        if (_maxRateBoundWad <= _minRateBoundWad) revert InvalidBounds();
        if (_minRateBoundWad < ABSOLUTE_MIN_RATE || _maxRateBoundWad > ABSOLUTE_MAX_RATE) {
            revert BoundsExceedAbsoluteLimits();
        }
        if (pendingRateBoundsChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingRateBoundsChange = PendingRateBoundsChange({
            newMinRateBoundWad: _minRateBoundWad,
            newMaxRateBoundWad: _maxRateBoundWad,
            activationTime: activation
        });
        emit RateBoundsChangeQueued(_minRateBoundWad, _maxRateBoundWad, activation);
    }

    /**
     * @notice Activate a queued rate-bounds change in **strict mode**. Reverts with
     *         `StoredRateOutsideNewBounds` if any currently-stored rate would fall
     *         outside the new window — preventing the post-activation `isValid=false`
     *         window a bounds tightening would otherwise open.
     *
     * @dev    Recommended governance flow ("graceful path"):
     *           1. `queueRateBoundsChange(newMin, newMax)` — 3-day timelock starts.
     *           2. During the timelock window, coordinate with the keeper to post
     *              rates inside the proposed `[newMin, newMax]` window. Posts during
     *              this window are still validated against the *current* (pre-change)
     *              bounds, so any value inside `current ∩ proposed` will land.
     *           3. `activateRateBoundsChange()` — strict mode succeeds because every
     *              stored bucket already complies. Zero `isValid=false` window.
     *
     *         For emergencies where governance must tighten regardless of keeper
     *         posting cadence, use the overload below with `acceptOutOfBoundsForce`.
     */
    function activateRateBoundsChange() external onlyOwner {
        _activateRateBoundsChange(false);
    }

    /**
     * @notice Activate with an explicit acknowledgement of the out-of-bounds case.
     *         When `acceptOutOfBoundsForce == true`, the strict-mode check is
     *         skipped AND `_resetStoredRates()` is invoked — children clear their
     *         stored rate state so the next post is not blocked by the
     *         `maxRateChangeWad` delta check.
     *
     * @dev    Recovery after a forced activation is a **single post** of a fresh
     *         curve inside the new bounds. The cleared `updatedAt` causes
     *         `_validateRateVector` to skip its delta-check (its `prevUpdatedAt > 0`
     *         guard fails), and the reset `lastObservedAt` causes
     *         `_validateTenorsAndCadence` to skip its cooldown check (its
     *         `lastObservedAt > 0` guard fails), so any in-bounds curve lands
     *         without needing a `maxRateChangeWad` increase, a `maxAgeSec`
     *         staleness wait, or a `minUpdateIntervalSec` cadence wait.
     *
     *         Between activation and the next valid post, reads return
     *         `isValid=false`. Cap that gap by coordinating with the keeper to
     *         post immediately after activation.
     */
    function activateRateBoundsChange(bool acceptOutOfBoundsForce) external onlyOwner {
        _activateRateBoundsChange(acceptOutOfBoundsForce);
    }

    function _activateRateBoundsChange(bool acceptOutOfBoundsForce) internal {
        PendingRateBoundsChange memory pending = pendingRateBoundsChange;
        if (pending.activationTime == 0) revert NoPendingRateBoundsChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);

        if (!acceptOutOfBoundsForce) {
            (bool ok, uint256 violatingTenor, int256 violatingRate) =
                _allStoredRatesWithinBounds(pending.newMinRateBoundWad, pending.newMaxRateBoundWad);
            if (!ok) {
                revert StoredRateOutsideNewBounds(
                    violatingTenor,
                    violatingRate,
                    pending.newMinRateBoundWad,
                    pending.newMaxRateBoundWad
                );
            }
        }

        int256 oldMin = minRateBoundWad;
        int256 oldMax = maxRateBoundWad;
        minRateBoundWad = pending.newMinRateBoundWad;
        maxRateBoundWad = pending.newMaxRateBoundWad;

        if (acceptOutOfBoundsForce) {
            _resetStoredRates();
            // Also clear the posting cadence. The documented single recovery post
            // must be able to land immediately, but `_validateTenorsAndCadence`
            // would otherwise reject it while
            // `observedAt < lastObservedAt + minUpdateIntervalSec` (the cooldown is
            // gated on observation time, not relay time). Zeroing both (mirrors
            // `activateTenorBucketsChange`) makes the next post a clean "first post"
            // on the delta and the cadence checks alike.
            lastPostTimestamp = 0;
            lastObservedAt = 0;
            emit StoredRatesReset();
        }

        emit RateBoundsChangeActivated(
            oldMin,
            oldMax,
            pending.newMinRateBoundWad,
            pending.newMaxRateBoundWad,
            acceptOutOfBoundsForce
        );
        delete pendingRateBoundsChange;
    }

    /**
     * @notice Hook used by strict-mode bound activation to verify every stored
     *         rate fits inside `[minBound, maxBound]`. Buckets that have never
     *         been posted (`updatedAt == 0`) are skipped — they cannot serve
     *         valid reads and therefore should not block governance.
     *
     * @dev Default implementation walks `tenorBuckets` via `_getStoredRate`.
     *      Children with side-specific rate vectors (e.g. `RiskRateOracle`'s
     *      up + lo) must override to check every side.
     */
    function _allStoredRatesWithinBounds(int256 minBound, int256 maxBound)
        internal
        view
        virtual
        returns (bool ok, uint256 violatingTenor, int256 violatingRate)
    {
        uint256 len = tenorBuckets.length;
        for (uint256 i = 0; i < len; i++) {
            uint256 tenor = tenorBuckets[i];
            (int256 r, uint256 updatedAt) = _getStoredRate(tenor);
            if (updatedAt == 0) continue;
            if (r < minBound || r > maxBound) {
                return (false, tenor, r);
            }
        }
        return (true, 0, 0);
    }

    /**
     * @notice Hook invoked only when a forced bound activation lands. Children
     *         must clear their stored rate state so the next post is accepted as
     *         a "first post" (no `maxRateChangeWad` delta check against an
     *         out-of-bounds prior value).
     *
     * @dev Mandatory — every concrete oracle has stored rate state (it must
     *      implement `_getStoredRate`), and a no-op default would let a forced
     *      activation silently leave out-of-bounds rates in place, breaking the
     *      single-post recovery guarantee documented above.
     */
    function _resetStoredRates() internal virtual;

    function cancelRateBoundsChange() external onlyOwner {
        PendingRateBoundsChange memory pending = pendingRateBoundsChange;
        if (pending.activationTime == 0) revert NoPendingRateBoundsChange();
        emit RateBoundsChangeCancelled(pending.newMinRateBoundWad, pending.newMaxRateBoundWad);
        delete pendingRateBoundsChange;
    }

    // --- Min Update Interval ---

    function queueMinUpdateIntervalChange(uint256 _minUpdateIntervalSec) external onlyOwner {
        // Posting cooldown must stay within `maxAgeSec` so signers can
        // always refresh the oracle before its stored rates go stale. Validate
        // against the higher of the active and pending max age so both parameters
        // can be raised within one timelock window; `activateMinUpdateIntervalChange`
        // re-checks against the active value, so the pending max-age increase must
        // activate first, and cancelling it cannot yield an invalid config.
        uint256 effectiveMaxAge = maxAgeSec;
        PendingMaxAgeChange memory pendingMaxAge = pendingMaxAgeChange;
        if (pendingMaxAge.activationTime != 0 && pendingMaxAge.newMaxAgeSec > effectiveMaxAge) {
            effectiveMaxAge = pendingMaxAge.newMaxAgeSec;
        }
        if (_minUpdateIntervalSec == 0 || _minUpdateIntervalSec > effectiveMaxAge) {
            revert InvalidMinUpdateInterval();
        }
        if (pendingMinUpdateIntervalChange.activationTime != 0) revert ChangeAlreadyPending();

        uint256 activation = block.timestamp + SIGNER_TIMELOCK;
        pendingMinUpdateIntervalChange = PendingMinUpdateIntervalChange({
            newMinUpdateIntervalSec: _minUpdateIntervalSec,
            activationTime: activation
        });
        emit MinUpdateIntervalChangeQueued(_minUpdateIntervalSec, activation);
    }

    function activateMinUpdateIntervalChange() external onlyOwner {
        PendingMinUpdateIntervalChange memory pending = pendingMinUpdateIntervalChange;
        if (pending.activationTime == 0) revert NoPendingMinUpdateIntervalChange();
        if (block.timestamp < pending.activationTime) revert TimelockNotElapsed(pending.activationTime);
        // Re-check the `minUpdateIntervalSec <= maxAgeSec` invariant:
        // `maxAgeSec` may have been lowered by a separate change activated during
        // this timelock window, so a queue-time-valid value can be stale here.
        if (pending.newMinUpdateIntervalSec > maxAgeSec) revert InvalidMinUpdateInterval();

        uint256 oldValue = minUpdateIntervalSec;
        minUpdateIntervalSec = pending.newMinUpdateIntervalSec;
        emit MinUpdateIntervalChangeActivated(oldValue, pending.newMinUpdateIntervalSec);
        delete pendingMinUpdateIntervalChange;
    }

    function cancelMinUpdateIntervalChange() external onlyOwner {
        PendingMinUpdateIntervalChange memory pending = pendingMinUpdateIntervalChange;
        if (pending.activationTime == 0) revert NoPendingMinUpdateIntervalChange();
        emit MinUpdateIntervalChangeCancelled(pending.newMinUpdateIntervalSec);
        delete pendingMinUpdateIntervalChange;
    }

    // ============ ERC-165 ============

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override(ERC165)
        returns (bool)
    {
        return interfaceId == type(IOracleMetadata).interfaceId
            || interfaceId == type(ITenorRateOracle).interfaceId
            || super.supportsInterface(interfaceId);
    }

    // ============ Internal ============

    function _getRatesInternal(uint256[] memory tenorSeconds) internal view returns (int256[] memory rates, bool isValid) {
        return _getRatesInternalWith(tenorSeconds, _defaultPrevRate);
    }

    /// @dev Side-aware variant. Children with multiple rate vectors per tenor
    ///      (e.g. `RiskRateOracle.getLoRates`) call this with their lo accessor;
    ///      the inherited `getRateByTenor` / `getRates` surface uses
    ///      `_defaultPrevRate` and therefore reads through `_getStoredRate`.
    function _getRatesInternalWith(
        uint256[] memory tenorSeconds,
        function(uint256) internal view returns (int256, uint256) rateFn
    ) internal view returns (int256[] memory rates, bool isValid) {
        uint256 bucketLen = tenorBuckets.length;
        uint256 numTenors = tenorSeconds.length;
        rates = new int256[](numTenors);

        if (bucketLen == 0) return (rates, false);

        // Paused oracle always returns invalid
        if (isPaused) return (rates, false);

        // Single staleness check for the entire batch
        uint256 earliestUpdate = _getEarliestUpdateTimestampWith(rateFn);
        if (earliestUpdate == 0 || block.timestamp - earliestUpdate > maxAgeSec) {
            return (rates, false);
        }

        // Load tenor buckets and their rates into memory once. Stored rates that no
        // longer satisfy the currently active bounds (e.g. after a timelocked tightening)
        // invalidate the whole batch — governance bound changes take effect on the next
        // read rather than waiting for staleness or the next post.
        // Linear interpolation between two in-bounds anchors is itself in-bounds, and
        // flat extrapolation returns a stored bucket value verbatim, so checking the
        // stored anchors is sufficient to cover every value `_interpolateFromMemory`
        // can return. That first clause is load-bearing and is upheld on both sides:
        // `_validateTenorBuckets` rejects bucket geometry whose gaps cannot be
        // represented as a positive `int256`, and `_interpolateFromMemory` interpolates
        // on unsigned magnitudes so it cannot step outside its two anchors (guards the tenor-gap sign overflow).
        int256 minBound = minRateBoundWad;
        int256 maxBound = maxRateBoundWad;
        uint256[] memory memBuckets = new uint256[](bucketLen);
        int256[] memory memRates = new int256[](bucketLen);
        for (uint256 i = 0; i < bucketLen; i++) {
            memBuckets[i] = tenorBuckets[i];
            (memRates[i],) = rateFn(memBuckets[i]);
            if (memRates[i] < minBound || memRates[i] > maxBound) {
                return (rates, false);
            }
        }

        // Flat extrapolation beyond the longest bucket would return the last
        // bucket's rate verbatim and still mark it valid — silently quoting a
        // tenor the oracle has no posted data for. Fail closed instead.
        uint256 longestTenor = memBuckets[bucketLen - 1];
        for (uint256 i = 0; i < numTenors; i++) {
            if (tenorSeconds[i] > longestTenor) return (rates, false);
            rates[i] = _interpolateFromMemory(memBuckets, memRates, tenorSeconds[i]);
        }

        return (rates, true);
    }

    function _getEarliestUpdateTimestamp() internal view returns (uint256 earliest) {
        return _getEarliestUpdateTimestampWith(_defaultPrevRate);
    }

    function _getEarliestUpdateTimestampWith(
        function(uint256) internal view returns (int256, uint256) rateFn
    ) internal view returns (uint256 earliest) {
        uint256 len = tenorBuckets.length;
        earliest = type(uint256).max;
        for (uint256 i = 0; i < len; i++) {
            (, uint256 t) = rateFn(tenorBuckets[i]);
            if (t < earliest) earliest = t;
        }
        if (earliest == type(uint256).max) earliest = 0;
    }

    function _absDiff(int256 a, int256 b) internal pure returns (uint256) {
        return a > b ? uint256(a - b) : uint256(b - a);
    }

    /**
     * @notice Shape validation for a candidate tenor bucket set (guards the tenor-gap sign overflow).
     * @dev Shared by the constructor and `setTenorBuckets` so the deploy path and the
     *      timelocked governance path can never diverge. `activateTenorBucketsChange`
     *      installs the queued set verbatim and `setTenorBuckets` is the only writer of
     *      `_pendingTenorBucketsChange.newTenorBuckets`, so gating the queue gates
     *      activation too.
     *
     *      The per-bucket ceiling is what keeps `_interpolateFromMemory` honest: with a
     *      strictly ascending set bounded by `MAX_TENOR_SECONDS`, every adjacent gap — and
     *      therefore every query offset within one — is a positive, `int256`-representable
     *      value, so interpolation can never flip sign and extrapolate past its anchors.
     */
    function _validateTenorBuckets(uint256[] memory _tenorBuckets) internal pure {
        uint256 len = _tenorBuckets.length;
        if (len == 0) revert EmptyArray();
        if (len > MAX_TENOR_BUCKETS) revert TooManyTenorBuckets(len, MAX_TENOR_BUCKETS);
        for (uint256 i = 0; i < len; i++) {
            if (_tenorBuckets[i] > MAX_TENOR_SECONDS) {
                revert TenorBucketTooLarge(_tenorBuckets[i], MAX_TENOR_SECONDS);
            }
            if (i > 0 && _tenorBuckets[i] <= _tenorBuckets[i - 1]) revert TenorBucketsNotSorted();
        }
    }

    /**
     * @notice True when `candidate` is element-for-element identical (including length) to the
     *         currently active `tenorBuckets`.
     * @dev Element-wise rather than a hash comparison. `tenorBuckets` is a storage array, so
     *      hashing it would require copying it into memory first — no cheaper, and it would
     *      hinge on an encoding assumption. The element loop short-circuits on the first
     *      difference, so the accept path (a genuine change) usually costs one length read
     *      plus one element read; only the reject path walks the whole set, and it reverts.
     */
    function _sameAsActiveTenorBuckets(uint256[] calldata candidate) internal view returns (bool) {
        uint256 len = tenorBuckets.length;
        if (candidate.length != len) return false;
        for (uint256 i = 0; i < len; i++) {
            if (candidate[i] != tenorBuckets[i]) return false;
        }
        return true;
    }

    /**
     * @notice Validates a signer-attested observation timestamp at submission time.
     * @dev Rejects a post-dated `observedAt` (which would otherwise extend apparent freshness
     *      beyond the real observation) and any observation already older than `maxAgeSec`
     *      (which would land born-stale). Callers store `observedAt` — not the relay block —
     *      as the data freshness timestamp, so a payload delayed past `maxAgeSec` between
     *      observation and relay cannot masquerade as fresh.
     */
    function _requireFreshObservation(uint256 observedAt) internal view {
        if (observedAt > block.timestamp) revert ObservedAtInFuture(observedAt);
        if (block.timestamp - observedAt > maxAgeSec) revert ObservedAtTooStale(observedAt);
    }

    function _interpolateFromMemory(
        uint256[] memory buckets,
        int256[] memory bucketRates,
        uint256 tenorSeconds
    ) internal pure returns (int256) {
        uint256 len = buckets.length;

        uint256 lowerIdx;
        uint256 upperIdx;
        bool foundLower = false;
        bool foundUpper = false;

        for (uint256 i = 0; i < len; i++) {
            uint256 bucket = buckets[i];
            if (bucket == tenorSeconds) return bucketRates[i];
            if (bucket < tenorSeconds) {
                lowerIdx = i;
                foundLower = true;
            } else if (!foundUpper) {
                upperIdx = i;
                foundUpper = true;
            }
        }

        if (!foundLower) return bucketRates[0];
        if (!foundUpper) return bucketRates[len - 1];

        int256 lowerRate = bucketRates[lowerIdx];
        int256 upperRate = bucketRates[upperIdx];

        // Interpolate on unsigned magnitudes and reapply the sign explicitly (guards the tenor-gap sign overflow).
        // The previous form cast the bucket difference to `int256`, so a gap wider than
        // `type(int256).max` became a negative range and divided a positive offset by it —
        // silently converting interpolation into unbounded extrapolation and letting an
        // ordinary in-range query escape the active rate bounds with `isValid == true`.
        // `_validateTenorBuckets` now rejects that geometry, and this form makes the
        // property structural: `tenorOffset < tenorRange` holds by construction (the
        // caller only reaches here for a tenor strictly between two buckets), so the
        // interpolated step is at most the endpoint gap and the result always lands
        // within `[min(lowerRate, upperRate), max(lowerRate, upperRate)]`.
        uint256 tenorRange = buckets[upperIdx] - buckets[lowerIdx];
        uint256 tenorOffset = tenorSeconds - buckets[lowerIdx];
        uint256 step = Math.mulDiv(_absDiff(upperRate, lowerRate), tenorOffset, tenorRange);

        return upperRate >= lowerRate ? lowerRate + int256(step) : lowerRate - int256(step);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.