Verified contractExactBUSL-1.1
UpgradableSidedPremiumOracle
Address0x337c36a930d6e1b3a03668da0c70cd8941573015
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.34
- Same code
9 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
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,042,762
- Creation transaction
- 0x0753d81954…b3ad98ab2d
8 files
- contracts/oracles/wrappers/UpgradableSidedPremiumOracle.solmain4.87 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/access/Ownable2Step.sol1.99 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/introspection/ERC165.sol911 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol869 B
- contracts/interfaces/External.sol8.84 KB
- contracts/oracles/wrappers/BaseUpgradableOracleWrapper.sol22.76 KB
contracts/oracles/wrappers/UpgradableSidedPremiumOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;
import "../../interfaces/External.sol";
import "./BaseUpgradableOracleWrapper.sol";
/**
* @title UpgradableSidedPremiumOracle
* @notice Upgradable wrapper around an `IDualSidedPremiumOracle`. SwapCore stores oracle
* addresses immutably at market creation; this wrapper is what each market side's
* `riskPremiumOracle` slot points at. The immutable `isUpperSide` flag picks which
* of the two co-posted premiums (upper for BUY_FIXED, lower for BUY_FLOATING) the
* wrapper exposes through `getRate()`.
*
* A market pair therefore needs **one** `RiskRateOracle` plus **two** wrappers:
* one with `isUpperSide=true` for the BUY_FIXED side and one with
* `isUpperSide=false` for the BUY_FLOATING side. They share the downstream's
* posting cadence and signature pipeline — the side flag is purely a read-time
* routing concern.
*/
contract UpgradableSidedPremiumOracle is BaseUpgradableOracleWrapper, IRateOracle {
/// @notice True → BUY_FIXED side (upper premium); false → BUY_FLOATING side (lower premium).
bool public immutable isUpperSide;
/// @dev Representative tenor used for `getRate()` reads and downstream health checks.
uint256 public immutable defaultTenorSeconds;
error InvalidTenor();
constructor(
bool _isUpperSide,
uint256 _defaultTenorSeconds,
address _downstream,
address _owner
) BaseUpgradableOracleWrapper(_downstream, _owner) {
if (_defaultTenorSeconds == 0) revert InvalidTenor();
isUpperSide = _isUpperSide;
defaultTenorSeconds = _defaultTenorSeconds;
}
/// @inheritdoc IRateOracle
/// @dev Routes to the side-specific downstream view. SwapCore reads risk premiums
/// via `Utils.getRiskPremiumOracleRate`, which calls `getRate()` exclusively.
/// When the emergency cutoff is engaged, returns `(0, false)` without touching
/// the downstream — a stable invalid response even if the downstream is reverting.
function getRate()
external
view
override
returns (int256 rate, bool isValid)
{
if (emergencyCutoff) return (0, false);
if (isUpperSide) {
(rate, isValid) = IDualSidedPremiumOracle(downstream).getUpRateByTenor(defaultTenorSeconds);
} else {
(rate, isValid) = IDualSidedPremiumOracle(downstream).getLoRateByTenor(defaultTenorSeconds);
}
// KAIRO risk premiums are unconditionally non-negative (consumer gate E612). A downstream
// that turns negative post-activation is invalidated in the cutoff shape rather than
// forwarded: `Utils.getRiskPremiumOracleRate` checks sign before validity, so the wrapper
// guard surfaces as E605 (invalid premium) instead of E612 — entry is blocked either way,
// and the negative value is never readable through the wrapper.
if (isValid && rate < 0) return (0, false);
}
function _requiredDownstreamInterfaceId() internal pure override returns (bytes4) {
return type(IDualSidedPremiumOracle).interfaceId;
}
/// @dev Probes only the SELECTED side: the opposite premium is served by this pair's other
/// wrapper and is that wrapper's concern. A negative selected-side probe is rejected
/// outright — KAIRO premiums are unconditionally non-negative (`RiskRateOracle` refuses
/// negative posts at source, `Utils.getRiskPremiumOracleRate` reverts E612 on read), so
/// activating a downstream that currently reports one would wedge every buy on this side
/// until yet another 3-day replacement delay elapses.
function _validateDownstreamHealth(address newDownstream) internal view override {
if (isUpperSide) {
try IDualSidedPremiumOracle(newDownstream).getUpRateByTenor(defaultTenorSeconds) returns (int256 r, bool ok) {
if (!ok) revert DownstreamUnhealthy();
if (r < 0) revert NegativeDownstreamRate(defaultTenorSeconds, r);
} catch {
revert DownstreamUnhealthy();
}
} else {
try IDualSidedPremiumOracle(newDownstream).getLoRateByTenor(defaultTenorSeconds) returns (int256 r, bool ok) {
if (!ok) revert DownstreamUnhealthy();
if (r < 0) revert NegativeDownstreamRate(defaultTenorSeconds, r);
} catch {
revert DownstreamUnhealthy();
}
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IRateOracle).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/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/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);
}
contracts/interfaces/External.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.34;
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`.
/// @dev Read-invariance contract. poke() may only advance internal history: it MUST NOT
/// change the value of a valid read and MUST NOT invalidate one. It may restore a read
/// that was invalid or reverting (a ring past its liveness gap), which is safe because
/// no consumer prices an invalid read. SwapCore reads oracles from views that cannot
/// poke and pokes from permissionless paths, so a value that steps at poke would let
/// anyone mark against the un-poked quote and settle against the post-poke one.
/// Non-pokeable feeds satisfy this trivially.
interface IPokeable {
function poke() external;
}
contracts/oracles/wrappers/BaseUpgradableOracleWrapper.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 {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../../interfaces/External.sol";
/**
* @title BaseUpgradableOracleWrapper
* @notice Abstract base for thin upgradable indirection wrappers placed between SwapCore
* and a concrete oracle implementation.
*
* SwapCore stores oracle addresses immutably at market creation. To allow the
* underlying oracle to be replaced (bug, deprecation, vendor change) without
* migrating every market, this wrapper is what SwapCore points at. Three
* governance levers, in escalating finality:
*
* 1. Timelocked downstream pointer update (3 days) — `queueDownstream` then
* `activateDownstream`. Mirrors the existing `BaseTimelockedOracle`
* `SIGNER_TIMELOCK` pattern.
* 2. Instant emergency cutoff — `engageEmergencyCutoff` forces every read
* to return `isValid = false`, causing SwapCore to revert until cleared
* (or locked permanent for retirement).
* 3. Timelocked upgradability renouncement (3 days) — `queueRenounceUpgradability`
* then `activateRenounceUpgradability` permanently disables the pointer
* update levers AND the emergency cutoff levers, freezing the wrapper at
* its current downstream and cutoff state.
*
* @dev `description()` forwards to the active downstream; `decimals()` returns a value
* snapshotted at construction and refreshed on each activation. Every
* state transition (constructor, queueDownstream, activateDownstream) requires the
* downstream to advertise the wrapper's required interface via ERC-165
* `supportsInterface` plus `IOracleMetadata`. The queue and activate paths enforce
* `decimals()` consistency against the cached value so upgrades cannot silently
* shift SwapCore's WAD normalization, and the downstream's actual read view is
* re-validated at activation to catch a downstream that bricked between queue and
* activate.
*/
abstract contract BaseUpgradableOracleWrapper is Ownable2Step, ERC165, IOracleMetadata {
// ============ Constants ============
uint256 public constant DOWNSTREAM_TIMELOCK = 3 days;
// ============ Storage ============
/// @notice Currently active downstream oracle. SwapCore reads ultimately resolve here.
address public downstream;
/// @notice Queued upgrade target. Becomes active after `pendingDownstreamActivation`.
address public pendingDownstream;
/// @notice Unix timestamp at which the queued downstream becomes activatable. 0 = no pending change.
uint256 public pendingDownstreamActivation;
/// @notice When true, every read returned by subclasses surfaces `isValid = false`.
bool public emergencyCutoff;
/// @notice One-way lock. When set, `releaseEmergencyCutoff` reverts. Used to retire a wrapper.
bool public cutoffPermanent;
/// @notice Once true, all upgrade and cutoff levers are permanently disabled. Set via
/// the timelocked `queueRenounceUpgradability` → `activateRenounceUpgradability`
/// flow. Freezes the wrapper at the current downstream and cutoff state.
bool public upgradabilityRenounced;
/// @notice Unix timestamp at which renouncement becomes activatable. 0 = no pending renouncement.
uint256 public pendingRenouncementActivation;
/// @notice Downstream `decimals()` snapshotted at construction and refreshed on each
/// activation. Candidate downstreams are matched against THIS cached value rather
/// than a live call to the current downstream, so a metadata-broken current
/// downstream cannot block governance from queueing/activating a healthy
/// replacement. The decimals-consistency invariant is preserved: a
/// candidate whose decimals differ from this value is always rejected.
uint8 public cachedDownstreamDecimals;
// ============ Events ============
event DownstreamQueued(address indexed newDownstream, uint256 activationTime);
event DownstreamActivated(address indexed oldDownstream, address indexed newDownstream);
event DownstreamCancelled(address indexed cancelledDownstream);
event EmergencyCutoffEngaged();
event EmergencyCutoffReleased();
event EmergencyCutoffLockedPermanent();
event RenounceUpgradabilityQueued(uint256 activationTime);
event UpgradabilityRenounced();
event RenounceUpgradabilityCancelled();
// ============ Errors ============
error ZeroAddress();
error ChangeAlreadyPending();
error NoPendingChange();
error TimelockNotElapsed(uint256 activationTime);
error DecimalsMismatch(uint8 expected, uint8 actual);
error DownstreamUnhealthy();
error CutoffLocked();
error CutoffNotEngaged();
error SameDownstream();
error Renounced();
error AlreadyRenounced();
error InterfaceNotSupported(bytes4 interfaceId);
error CutoffAlreadyEngaged();
error RenounceOwnershipDisabled();
error DownstreamNotPokeable();
/// @dev A downstream probe (at construction/activation) or forwarded read returned a negative
/// rate that the wrapper's numeric-domain profile forbids — e.g. a Cumulative-profile base
/// wrapper or a risk-premium wrapper, whose consumers reject negative values outright
/// (E512 / E612). Catching the sign at activation keeps a 3-day-timelocked downstream
/// swap from wedging every projected-rate consumer of a live market.
/// `tenorSeconds` is the probed tenor, or 0 for tenor-less `getRate()` wrappers.
error NegativeDownstreamRate(uint256 tenorSeconds, int256 rate);
// ============ Constructor ============
/**
* @param _downstream Initial downstream oracle. Must support ERC-165 introspection
* for `IOracleMetadata` and the wrapper's required read interface
* (see `requiredDownstreamInterface()`).
* @param _owner Governance address that controls upgrades and the emergency cutoff.
*/
constructor(address _downstream, address _owner) Ownable(_owner) {
// _owner zero-check is enforced by Ownable's constructor before this body executes.
if (_downstream == address(0)) revert ZeroAddress();
_requireDownstreamInterface(_downstream);
downstream = _downstream;
// Snapshot decimals up front so recovery never depends on the (possibly later
// broken) current downstream's metadata. A downstream whose metadata is already
// unreadable at deploy time fails closed here — a wrapper must not be deployed
// around a metadata-broken oracle.
cachedDownstreamDecimals = IOracleMetadata(_downstream).decimals();
// Mirror Ownable's constructor pattern: emit the lifecycle event with the
// zero-address as the prior value so indexers can subscribe to a single
// `DownstreamActivated` stream for the complete downstream history.
emit DownstreamActivated(address(0), _downstream);
}
// ============ Metadata (forwarded to downstream) ============
/// @notice Returns the decimals snapshotted at construction / last activation, so external
/// reads (and SwapCore's WAD normalization) never revert if the current downstream's
/// metadata breaks. The cache always equals the active downstream's decimals because
/// every activation enforces a decimals match.
function decimals() external view override returns (uint8) {
return cachedDownstreamDecimals;
}
/// @notice Forwards to the active downstream. Wrapper does not snapshot.
function description() external view override returns (string memory) {
return IOracleMetadata(downstream).description();
}
// ============ Keeper poke (forwarded to downstream) ============
/// @notice Forwards a permissionless keeper poke to the active downstream oracle.
/// @dev Pure passthrough: the wrapper advertises `IPokeable` exactly when the active
/// downstream does (see `supportsInterface`), and callers probe that live. The
/// guard here is the last line of defence for a caller that decided to poke before
/// a downstream swap landed: it reverts `DownstreamNotPokeable` (which
/// `OraclePokeLib.poke` treats as a completed no-op) rather than letting the
/// selector blindly reach an unrelated function on a non-pokeable downstream. Not
/// gated by `emergencyCutoff`: a poke only refreshes the downstream's own internal
/// state.
function poke() external {
if (!_downstreamSupportsPoke()) revert DownstreamNotPokeable();
IPokeable(downstream).poke();
}
/// @dev Bounded-gas low-level staticcall, mirroring `OraclePokeLib.supportsPoke`.
/// Any of these is treated as not pokeable (without reverting):
/// revert / OOG within the 30k cap, returndata length != 32, non-canonical
/// bool encoding, EOA, or any other malformed response. The high-level
/// `try/catch` over a typed-return call is not equivalent — Solidity's
/// typed-return decoding can revert *outside* the try/catch on certain
/// malformed responses, and the high-level call would also forward all
/// remaining gas, which the spec caps at 30k.
function _downstreamSupportsPoke() internal view returns (bool result) {
address ds = downstream;
bytes memory data = abi.encodeCall(IERC165.supportsInterface, (type(IPokeable).interfaceId));
assembly ("memory-safe") {
let ok := staticcall(
30000, // ERC-165 spec-recommended gas cap.
ds,
add(data, 0x20),
mload(data),
0x00,
0x20
)
if and(ok, eq(returndatasize(), 0x20)) {
// Strict canonical bool: only `1` registers as pokeable.
result := eq(mload(0x00), 1)
}
}
}
// ============ Downstream Pointer (3-day timelock) ============
/**
* @notice Queue a downstream replacement. Fails fast at queue time on three
* distinct grounds: the candidate doesn't advertise the required ERC-165
* interface; its `decimals()` doesn't match the cached downstream decimals
* (which would silently shift SwapCore's WAD normalization); or its
* metadata call reverts.
*/
function queueDownstream(address newDownstream) external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
if (newDownstream == address(0)) revert ZeroAddress();
if (newDownstream == downstream) revert SameDownstream();
if (pendingDownstreamActivation != 0) revert ChangeAlreadyPending();
_requireDownstreamInterface(newDownstream);
// Compare against the cached decimals (set at construction / last activation) rather
// than live-calling the current downstream, so a metadata-broken current downstream
// cannot block queueing a healthy replacement.
uint8 newDecimals = IOracleMetadata(newDownstream).decimals();
if (newDecimals != cachedDownstreamDecimals) revert DecimalsMismatch(cachedDownstreamDecimals, newDecimals);
uint256 activation = block.timestamp + DOWNSTREAM_TIMELOCK;
pendingDownstream = newDownstream;
pendingDownstreamActivation = activation;
emit DownstreamQueued(newDownstream, activation);
}
/// @notice Cancel a queued downstream. Instant; mirrors `BaseTimelockedOracle.cancel*` patterns.
function cancelPendingDownstream() external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
if (pendingDownstreamActivation == 0) revert NoPendingChange();
address cancelled = pendingDownstream;
delete pendingDownstream;
delete pendingDownstreamActivation;
emit DownstreamCancelled(cancelled);
}
/**
* @notice Activate a queued downstream after the timelock has elapsed. Re-validates the
* downstream's read view via `_validateDownstreamHealth` (subclass-specific) to
* catch a downstream that bricked between queue and activate.
*/
function activateDownstream() external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
uint256 activation = pendingDownstreamActivation;
if (activation == 0) revert NoPendingChange();
if (block.timestamp < activation) revert TimelockNotElapsed(activation);
address newDownstream = pendingDownstream;
// Re-check ERC-165 conformance, decimals consistency, and the actual read
// view in case the candidate was upgraded or bricked between queue and activate.
_requireDownstreamInterface(newDownstream);
// Compare against the cached decimals, not the (possibly broken) current
// downstream. Refresh the cache after the swap so it always tracks the active
// downstream — the match check above means it never actually drifts.
uint8 newDecimals = IOracleMetadata(newDownstream).decimals();
if (newDecimals != cachedDownstreamDecimals) revert DecimalsMismatch(cachedDownstreamDecimals, newDecimals);
_validateDownstreamHealth(newDownstream);
address oldDownstream = downstream;
downstream = newDownstream;
cachedDownstreamDecimals = newDecimals;
delete pendingDownstream;
delete pendingDownstreamActivation;
emit DownstreamActivated(oldDownstream, newDownstream);
}
// ============ Emergency Cutoff (instant) ============
/// @notice Force every read to surface `isValid = false`. Instant by design.
/// @dev Reverts if cutoff is already engaged so off-chain monitors don't see a
/// no-op `EmergencyCutoffEngaged` event.
///
/// Subclass read functions check `emergencyCutoff` *before* calling the
/// downstream and short-circuit to a zeroed invalid response. This makes the
/// cutoff a true emergency lever: it produces a stable `(…, false)` regardless
/// of downstream state, including a downstream that has started reverting —
/// the exact failure mode an operator engages the cutoff to contain.
function engageEmergencyCutoff() external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
if (emergencyCutoff) revert CutoffAlreadyEngaged();
emergencyCutoff = true;
emit EmergencyCutoffEngaged();
}
/// @notice Clear the emergency cutoff. Instant. Reverts if `cutoffPermanent`,
/// renounced, or already released (no no-op `EmergencyCutoffReleased`
/// events for off-chain monitors).
function releaseEmergencyCutoff() external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
if (cutoffPermanent) revert CutoffLocked();
if (!emergencyCutoff) revert CutoffNotEngaged();
emergencyCutoff = false;
emit EmergencyCutoffReleased();
}
/**
* @notice Lock the emergency cutoff one-way. Effectively retires the wrapper while
* keeping SwapCore's revert path live (E606/E610/E611). Requires the cutoff
* to already be engaged and not yet locked so retirement is an explicit
* two-step action that can't emit duplicate lock events.
*/
function lockEmergencyCutoffPermanent() external onlyOwner {
if (upgradabilityRenounced) revert Renounced();
if (!emergencyCutoff) revert CutoffNotEngaged();
if (cutoffPermanent) revert CutoffLocked();
cutoffPermanent = true;
emit EmergencyCutoffLockedPermanent();
}
// ============ Renounce Upgradability (3-day timelock, one-way) ============
/**
* @notice Queue permanent renouncement of all upgrade and cutoff levers. After the
* 3-day timelock and `activateRenounceUpgradability`, the wrapper is frozen at
* its current downstream and cutoff state forever. Use this to prove to
* depositors that a market's oracle pointer cannot be redirected.
*/
function queueRenounceUpgradability() external onlyOwner {
if (upgradabilityRenounced) revert AlreadyRenounced();
if (pendingRenouncementActivation != 0) revert ChangeAlreadyPending();
uint256 activation = block.timestamp + DOWNSTREAM_TIMELOCK;
pendingRenouncementActivation = activation;
emit RenounceUpgradabilityQueued(activation);
}
/// @notice Cancel a queued renouncement. Instant.
function cancelRenounceUpgradability() external onlyOwner {
if (upgradabilityRenounced) revert AlreadyRenounced();
if (pendingRenouncementActivation == 0) revert NoPendingChange();
delete pendingRenouncementActivation;
emit RenounceUpgradabilityCancelled();
}
/**
* @notice Activate a queued renouncement after the timelock has elapsed. Sets
* `upgradabilityRenounced = true` permanently and clears any pending
* downstream change (which can never be activated post-renouncement).
* The current `downstream` and `emergencyCutoff` values are now permanent.
*/
function activateRenounceUpgradability() external onlyOwner {
if (upgradabilityRenounced) revert AlreadyRenounced();
uint256 activation = pendingRenouncementActivation;
if (activation == 0) revert NoPendingChange();
if (block.timestamp < activation) revert TimelockNotElapsed(activation);
upgradabilityRenounced = true;
delete pendingRenouncementActivation;
// Strand any in-flight downstream change — it can never be activated post-renouncement.
if (pendingDownstreamActivation != 0) {
address strandedDownstream = pendingDownstream;
delete pendingDownstream;
delete pendingDownstreamActivation;
emit DownstreamCancelled(strandedDownstream);
}
emit UpgradabilityRenounced();
}
/**
* @notice Disabled. OpenZeppelin's `Ownable.renounceOwnership` is a single-tx,
* no-timelock path to `owner() == address(0)` — it would instantly orphan
* every `onlyOwner` lever (downstream updates, emergency cutoff, the
* renouncement flow itself), bypassing the 3-day timelock and leaving
* `upgradabilityRenounced` false with no `UpgradabilityRenounced` event.
* To permanently freeze the wrapper, use `queueRenounceUpgradability` →
* `activateRenounceUpgradability` instead. Ownership remains transferable
* via the `Ownable2Step` two-step handshake.
*/
function renounceOwnership() public pure override {
revert RenounceOwnershipDisabled();
}
// ============ ERC-165 introspection ============
/// @notice ERC-165 interfaceId of the downstream read interface this wrapper requires.
/// Public so indexers and governance UIs can self-discover what a wrapper
/// expects from its downstream.
function requiredDownstreamInterface() external pure returns (bytes4) {
return _requiredDownstreamInterfaceId();
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165)
returns (bool)
{
// Passthrough: `IPokeable` is advertised exactly when the active downstream
// advertises it, so a wrapper never claims a capability its downstream lacks and
// a timelocked downstream swap changes the answer the moment it activates.
return interfaceId == type(IOracleMetadata).interfaceId
|| (interfaceId == type(IPokeable).interfaceId && _downstreamSupportsPoke())
|| super.supportsInterface(interfaceId);
}
// ============ Internal helpers ============
/// @dev Reverts unless `candidate` advertises both `IOracleMetadata` (decimals/
/// description, used by SwapCore's WAD normalization) and the wrapper's
/// minimal SwapCore-facing read interface (e.g. `IRateOracle` /
/// `ITenorRateOracle` / `ICumulativeRateOracle`) via ERC-165. Each
/// `supportsInterface` call is wrapped in try/catch so a non-ERC-165
/// contract surfaces `DownstreamUnhealthy` cleanly.
///
/// Self-reference is rejected up front: a wrapper advertises both
/// `IOracleMetadata` and its read interface, so `address(this)` would
/// otherwise pass introspection. Pointing `downstream` at the wrapper
/// itself makes `description()` recurse to out-of-gas with no recovery path
/// (the read paths short-circuit on `emergencyCutoff` before touching the
/// downstream, but `description()` forwards unconditionally). This single
/// chokepoint guards every downstream assignment —
/// constructor, `queueDownstream`, `activateDownstream`.
function _requireDownstreamInterface(address candidate) internal view {
if (candidate == address(this)) revert SameDownstream();
bytes4 metaId = type(IOracleMetadata).interfaceId;
bytes4 readId = _requiredDownstreamInterfaceId();
try IERC165(candidate).supportsInterface(metaId) returns (bool ok) {
if (!ok) revert InterfaceNotSupported(metaId);
} catch {
revert DownstreamUnhealthy();
}
try IERC165(candidate).supportsInterface(readId) returns (bool ok) {
if (!ok) revert InterfaceNotSupported(readId);
} catch {
revert DownstreamUnhealthy();
}
}
/// @dev Subclasses return the ERC-165 interfaceId of the read interface they
/// require from their downstream (e.g. `type(IRateOracle).interfaceId`).
function _requiredDownstreamInterfaceId() internal pure virtual returns (bytes4);
/// @dev Subclasses validate the downstream's read view at activation time. Reverts
/// with `DownstreamUnhealthy` if the call reverts or returns `isValid = false`.
function _validateDownstreamHealth(address newDownstream) internal view virtual;
}
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.