Verified contractExactBUSL-1.1
FluidUsdOracleMainViews
Address0xd173d03aa0ec46dda26022edea875c5440b7eb40
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.36
- Same code
Only this contract
Details
- Compiler
- solc 0.8.36+commit.8a079791
- Language
- solidity
- Optimization
- Yes, 10,000,000 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,405,372
- Creation transaction
- 0xfd9e7ed6bf…9138e4a461
25 files
- contracts/oracleV2/usdOracle/mainViews.solmain4.67 KB
- @openzeppelin/contracts/interfaces/draft-IERC1822.sol879 B
- @openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol6.51 KB
- @openzeppelin/contracts/proxy/beacon/IBeacon.sol450 B
- @openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol4.22 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/utils/Address.sol9.16 KB
- @openzeppelin/contracts/utils/StorageSlot.sol2.67 KB
- contracts/libraries/StringBytes32Utils.sol1.39 KB
- contracts/oracleV2/common/tokenSymbolResolver.sol2.59 KB
- contracts/oracleV2/interfaces/external/IChainlinkAggregatorV3.sol919 B
- contracts/oracleV2/interfaces/iFluidCappedRate.sol777 B
- contracts/oracleV2/interfaces/iFluidOracle.sol2.36 KB
- contracts/oracleV2/interfaces/iFluidOracleWithDebt.sol639 B
- contracts/oracleV2/interfaces/iFluidOracleWrite.sol1.44 KB
- contracts/oracleV2/interfaces/iUSDOracle.sol4.85 KB
- contracts/oracleV2/usdOracle/error.sol238 B
- contracts/oracleV2/usdOracle/errorTypes.sol2.58 KB
- contracts/oracleV2/usdOracle/events.sol2.17 KB
- contracts/oracleV2/usdOracle/main.sol85.45 KB
- contracts/oracleV2/usdOracle/sourceReaders/chainlinkSourceReader.sol2.6 KB
- contracts/oracleV2/usdOracle/sourceReaders/fluidSourceReader.sol3.31 KB
- contracts/oracleV2/usdOracle/structs.sol5.8 KB
- contracts/oracleV2/usdOracle/variables.sol9.45 KB
contracts/oracleV2/usdOracle/mainViews.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { FluidUsdOracleViews } from "./main.sol";
/// @title FluidUsdOracleMainViews
/// @notice Holds `FluidUsdOracle`'s enumeration views, which it delegatecalls to stay under EIP-170.
/// @dev Deploy before `FluidUsdOracle` and pass as `MAIN_VIEWS`; build both from the same source or the
/// inherited storage layout stops matching. Called directly it reads its own empty storage.
contract FluidUsdOracleMainViews is FluidUsdOracleViews {
/// @param liquidity_ Must match the delegatecalling `FluidUsdOracle` — under delegatecall immutables
/// still resolve from this contract's own code.
constructor(address liquidity_) validAddress(liquidity_) {
LIQUIDITY = liquidity_;
}
/// @notice Storage-layout version this contract was built against; checked by the `FluidUsdOracle` constructor.
function layoutVersion() external pure returns (uint256) {
return MAIN_VIEWS_LAYOUT_VERSION;
}
/// @notice Returns every configured oracle key for `token_` with its resolved source chains and live rates.
function getConfiguredTokenOracles(
address token_
) external view virtual override returns (ConfiguredTokenOracle[] memory infos_) {
ConfigMap[] memory configMaps_ = configsMap[token_];
uint256 len_ = configMaps_.length;
infos_ = new ConfiguredTokenOracle[](len_);
string memory tokenSymbol_ = _tokenSymbol(token_);
for (uint256 i = 0; i < len_; ++i) {
infos_[i] = _buildConfiguredTokenOracle(token_, tokenSymbol_, configMaps_[i]);
}
}
/// @dev Builds a single ConfiguredTokenOracle entry. Extracted to avoid stack-too-deep in the loop.
function _buildConfiguredTokenOracle(
address token_,
string memory tokenSymbol_,
ConfigMap memory configMap_
) internal view returns (ConfiguredTokenOracle memory info_) {
OracleKeyConfig memory keyCfg_ = _configs[
_keyHash(token_, configMap_.eMode, configMap_.isOperate ? 1 : 0, configMap_.isCollateral ? 1 : 0)
];
info_.token = token_;
info_.symbol = tokenSymbol_;
info_.eMode = configMap_.eMode;
info_.isOperate = configMap_.isOperate;
info_.isCollateral = configMap_.isCollateral;
info_.priceMode = keyCfg_.priceMode;
info_.sourceCapMode = keyCfg_.sourceCapMode;
info_.overallCapMode = keyCfg_.overallCapMode;
info_.overallCapOperand = keyCfg_.overallCapOperand;
info_.maxDeviationBPS = keyCfg_.maxDeviationBPS;
info_.isFallback = keyCfg_.flagsBitmap & KEY_FLAG_FALLBACK != 0;
info_.isCrossFallback = keyCfg_.flagsBitmap & KEY_FLAG_CROSS_FALLBACK != 0;
TokenSourceConfig storage tokenCfg_ = _tokenSources[token_];
info_.governanceApproved = tokenCfg_.primarySrc.flagsBitmap & FLAG_GOVERNANCE_APPROVED != 0;
TokenSources storage primaryCfg_;
TokenSources storage altCfg_;
bool hasAlt_;
bool useAdditional_ = (tokenCfg_.primarySrc.tokenType == TOKEN_TYPE_PEG &&
keyCfg_.priceMode == PRICE_MODE_MARKET);
if (useAdditional_) {
primaryCfg_ = _additionalTokenSources[token_].primarySrc;
altCfg_ = _additionalTokenSources[token_].altSrc;
hasAlt_ = tokenCfg_.primarySrc.flagsBitmap & FLAG_HAS_ADDITIONAL_ALT_SOURCES != 0;
} else {
primaryCfg_ = tokenCfg_.primarySrc;
altCfg_ = tokenCfg_.altSrc;
hasAlt_ = tokenCfg_.primarySrc.flagsBitmap & FLAG_HAS_ALT_SOURCE != 0;
}
info_.primary = _readSourcesWithRates(primaryCfg_, configMap_.isOperate, configMap_.isCollateral);
if (hasAlt_) {
info_.alt = _readSourcesWithRates(altCfg_, configMap_.isOperate, configMap_.isCollateral);
}
// Reported for every key: primary/alt only resolve to these when priceMode is MARKET, but
// OVERALL_CAP_MIN/MAX_CROSS_PATH reads them on PEG keys too.
uint8 flags_ = tokenCfg_.primarySrc.flagsBitmap;
if (flags_ & FLAG_HAS_ADDITIONAL_SOURCES != 0) {
info_.additionalPrimary = _readSourcesWithRates(
_additionalTokenSources[token_].primarySrc,
configMap_.isOperate,
configMap_.isCollateral
);
}
if (flags_ & FLAG_HAS_ADDITIONAL_ALT_SOURCES != 0) {
info_.additionalAlt = _readSourcesWithRates(
_additionalTokenSources[token_].altSrc,
configMap_.isOperate,
configMap_.isCollateral
);
}
}
}
@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
@openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @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:
* ```
* 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(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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
}
}
}
contracts/libraries/StringBytes32Utils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.21 <=0.8.36;
/// @dev Helpers for strings stored as a `bytes32` word plus an explicit byte length.
library StringBytes32Utils {
error StringBytes32Utils__InvalidStringLength();
function _validatedStringLength(uint256 lengthUint_) private pure returns (uint8 length_) {
if (lengthUint_ == 0 || lengthUint_ > 32) revert StringBytes32Utils__InvalidStringLength();
length_ = uint8(lengthUint_);
}
function stringToBytes32(string calldata string_) internal pure returns (bytes32 bytes32_, uint8 length_) {
length_ = _validatedStringLength(bytes(string_).length);
assembly {
bytes32_ := calldataload(string_.offset)
}
}
function stringMemoryToBytes32(string memory string_) internal pure returns (bytes32 bytes32_, uint8 length_) {
length_ = _validatedStringLength(bytes(string_).length);
assembly {
bytes32_ := mload(add(string_, 0x20))
}
}
function bytes32ToString(bytes32 bytes32_, uint8 length_) internal pure returns (string memory string_) {
if (length_ > 32) revert StringBytes32Utils__InvalidStringLength();
string_ = new string(length_);
bytes memory stringBytes_ = bytes(string_);
assembly {
mstore(add(stringBytes_, 0x20), bytes32_)
}
}
}
contracts/oracleV2/common/tokenSymbolResolver.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { StringBytes32Utils } from "../../libraries/StringBytes32Utils.sol";
/// @title TokenSymbolResolver
/// @notice Shared helper for human-readable token symbols: native asset per chain, ERC20 `symbol()`, or `"UNK"`.
///
/// @dev Native sentinel must match Liquidity / `NATIVE_TOKEN_ADDRESS` in sibling modules (same `0xEeee…` address).
abstract contract TokenSymbolResolver {
address private constant _NATIVE_TOKEN_SENTINEL = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev A `try`/`catch` around `symbol()` covers a reverting token but not a malformed answer: solc
/// skips the existence check when return data is expected, and a *decode* failure surfaces in
/// this frame rather than in `catch`. Callers are enumeration views, where one odd token must
/// not take down the whole response, so anything that is not a well-formed ABI string is `"UNK"`.
function _tokenSymbol(address token_) internal view returns (string memory symbol_) {
if (token_ == _NATIVE_TOKEN_SENTINEL) {
if (block.chainid == 137) {
return "POL";
}
if (block.chainid == 9745) {
return "XPL";
}
if (block.chainid == 56) {
return "BNB";
}
return "ETH";
}
(bool success_, bytes memory data_) = token_.staticcall(abi.encodeCall(IERC20Metadata.symbol, ()));
if (!success_) {
return "UNK";
}
// legacy bytes32 symbols (MKR style) return one left-aligned word
if (data_.length == 32) {
uint8 length_;
while (length_ < 32 && data_[length_] != 0) ++length_;
return length_ == 0 ? "UNK" : StringBytes32Utils.bytes32ToString(bytes32(data_), length_);
}
// an ABI string needs an offset word and a length word; shorter means no code at the address, which
// would revert the decode below
if (data_.length < 64) {
return "UNK";
}
// abi.decode(string) reverts on a bad offset or length; check both first so one odd token cannot break the view
(uint256 offset_, uint256 len_) = abi.decode(data_, (uint256, uint256));
if (offset_ != 0x20 || len_ > data_.length || 64 + ((len_ + 31) / 32) * 32 > data_.length) {
return "UNK";
}
return abi.decode(data_, (string));
}
}
contracts/oracleV2/interfaces/external/IChainlinkAggregatorV3.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
/// from https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
/// Copyright (c) 2018 SmartContract ChainLink, Ltd.
interface IChainlinkAggregatorV3 {
/// @notice represents the number of decimals the aggregator responses represent.
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
)
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
contracts/oracleV2/interfaces/iFluidCappedRate.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
import { IFluidOracleWithDebt } from "./iFluidOracleWithDebt.sol";
interface IFluidCappedRate is IFluidOracleWithDebt {
/// @notice Retrieves the center price for use in a Fluid dex pool
/// @dev This function is marked as non-constant (potentially state-changing) to allow flexibility in price fetching mechanisms.
/// While typically used as a read-only operation, this design permits write operations if needed for certain token pairs
/// (e.g., fetching up-to-date exchange rates that may require state changes).
/// @return price_ The current price ratio of token1 to token0, expressed with 27 decimal places
function centerPrice() external returns (uint256 price_);
}
contracts/oracleV2/interfaces/iFluidOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
interface IFluidOracle {
/// @notice Returns the raw underlying exchange rate in 1e27 precision, without applying collateral/debt caps.
/// @dev Heartbeat-aware read: if a heartbeat refresh is due, computes and returns the fresh rate without requiring
/// a storage write.
function getExchangeRate() external view returns (uint256 exchangeRate_);
/// @notice Get the `exchangeRate_` between the underlying asset and the peg asset in 1e27 for operates
function getExchangeRateOperate() external view returns (uint256 exchangeRate_);
/// @notice Get the `exchangeRate_` between the underlying asset and the peg asset in 1e27 for liquidations
function getExchangeRateLiquidate() external view returns (uint256 exchangeRate_);
/// @notice Same as `getExchangeRateOperate()`, for resolver/UI reads only. May bypass checks that can revert on the guarded getter.
/// @dev Example today: L2 sequencer uptime / grace-period. Additional bypasses may be added here over time.
function getExchangeRateOperateRaw() external view returns (uint256 exchangeRate_);
/// @notice Same as `getExchangeRateLiquidate()`, for resolver/UI reads only. May bypass checks that can revert on the guarded getter.
/// @dev Example today: L2 sequencer uptime / grace-period. Additional bypasses may be added here over time.
function getExchangeRateLiquidateRaw() external view returns (uint256 exchangeRate_);
/// @notice Same as `getExchangeRate()`, for resolver/UI reads only. May bypass checks that can revert on the guarded getter.
/// @dev Example today: L2 sequencer uptime / grace-period. Additional bypasses may be added here over time.
function getExchangeRateRaw() external view returns (uint256 exchangeRate_);
/// @notice helper string to easily identify the oracle. E.g. token symbols
function infoName() external view returns (string memory);
/// @notice target decimals of the returned oracle rate when scaling to 1e27. E.g. for ETH / USDC it would be 15
/// because diff of ETH decimals to 1e27 is 9, and USDC has 6 decimals, so 6+9 = 15, e.g. 2029,047772120364926
/// For USDC / ETH: 21 + 18 = 39, e.g. 0,000492842018675092636829357843847601646
function targetDecimals() external view returns (uint8);
}
contracts/oracleV2/interfaces/iFluidOracleWithDebt.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
import { IFluidOracle } from "./iFluidOracle.sol";
/// @notice Fluid oracle that exposes directional debt getters (e.g. CLX stock oracles).
/// @dev Distinct from `IFluidCappedRate`: no `centerPrice()` required.
interface IFluidOracleWithDebt is IFluidOracle {
/// @notice Operate exchange rate for the debt asset side
function getExchangeRateOperateDebt() external view returns (uint256 exchangeRate_);
/// @notice Liquidate exchange rate for the debt asset side
function getExchangeRateLiquidateDebt() external view returns (uint256 exchangeRate_);
}
contracts/oracleV2/interfaces/iFluidOracleWrite.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
/// @notice Optional non-view oracle getters for vault / USD-oracle hot paths (e.g. CLX cache warm).
/// Directional getters mirror `IFluidOracleWithDebt`.
/// @dev Each getter is optional; implementations may expose only the subset that applies to them.
/// Implementations must enforce equivalent checks on their view getters, so callers can fall back to those.
/// Vault core falls back only on empty revert data (missing selector) and rethrows non-empty reverts;
/// readers with per-leg failure isolation (USD oracle price tree) fall back on any failure.
interface IFluidOracleWrite {
/// @notice Non-view operate rate. May persist oracle state (e.g. last regular-hours price).
function getExchangeRateOperateWrite() external returns (uint256 exchangeRate_);
/// @notice Non-view liquidate rate. May persist oracle state (e.g. last regular-hours price).
function getExchangeRateLiquidateWrite() external returns (uint256 exchangeRate_);
/// @notice Non-view operate debt rate. May persist oracle state (e.g. last regular-hours price).
function getExchangeRateOperateDebtWrite() external returns (uint256 exchangeRate_);
/// @notice Non-view liquidate debt rate. May persist oracle state (e.g. last regular-hours price).
function getExchangeRateLiquidateDebtWrite() external returns (uint256 exchangeRate_);
}
contracts/oracleV2/interfaces/iUSDOracle.sol
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.21 <=0.8.36;
import { ViewStructs } from "../usdOracle/structs.sol";
// NOTE: 1 unit of base currency means 1e27
// Eg: If base currency is USD, then 1 USD of value means 1e27
interface IUSDOracle {
/// @notice Returns whether the given address is an enabled guardian.
function isGuardian(address addr_) external view returns (bool);
/// @notice Returns token-level metadata used by pricing.
function getTokenConfig(
address token_
) external view returns (bool operatePaused_, bool liquidatePaused_, uint8 tokenType_, uint8 decimals_);
/// @notice Returns whether token-level source config is governance-approved.
function isTokenConfigGovernanceApproved(address token_) external view returns (bool);
/// @notice Returns the price for a given token key. Intended for DexV2 and MoneyMarket.
/// @dev Intentionally non-view for future flexibility. Use `getPriceView()` for read-only consumers.
function getPrice(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) external returns (uint256 price_);
/// @notice View-only variant of `getPrice()` for read-only consumers.
function getPriceView(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) external view returns (uint256 price_);
/// @notice Returns detailed pricing: full getPrice() result, token decimals, and token peg type.
/// Reverts with the same errors as `getPrice()` when pricing fails.
/// Intended for V1 vault wrappers (T1-T4) that need both the price and token decimals.
/// @dev Intentionally non-view for future flexibility. Use `getPriceDetailedView()` for read-only consumers.
function getPriceDetailed(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) external returns (uint256 price_, uint8 decimals_, uint8 tokenType_);
/// @notice View-only variant of `getPriceDetailed()` for read-only consumers such as vault oracles.
/// Reverts with the same errors as `getPriceView()` when pricing fails.
function getPriceDetailedView(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) external view returns (uint256 price_, uint8 decimals_, uint8 tokenType_);
/// @notice Same as `getPriceDetailedView()`, for resolver/UI reads only. May bypass checks that can revert on the guarded getter.
/// @dev Example today: L2 sequencer uptime / grace-period. Additional bypasses may be added here over time.
function getPriceDetailedViewRaw(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) external view returns (uint256 price_, uint8 decimals_, uint8 tokenType_);
/// @notice Returns the raw composed price for a token and price mode, plus token metadata.
/// No caps, no deviation, no reverts (returns 0 on failure). Includes alt-source fallback when configured.
/// Intended for limit handlers, auth contracts, and other consumers that always need a resolved price.
/// Capped rate sources use getExchangeRate() (uncapped, no operate/liquidate/collateral/debt distinction).
/// Chainlink uses the liquidate (lenient) staleness timespan.
function getPriceRawForMode(
address token_,
uint8 priceMode_
) external view returns (uint256 priceRaw_, uint8 decimals_, uint8 tokenType_);
/// @notice Multi-token `getPriceRawForMode()`, same per-token semantics. Guard (L2 sequencer) checked once per batch.
/// @param priceModes_ One mode per token; length mismatch reverts `UsdOracle__InvalidParams`.
/// @dev Returns three parallel arrays, one entry per token in `tokens_` order.
function getPricesRawForMode(
address[] calldata tokens_,
uint8[] calldata priceModes_
) external view returns (uint256[] memory pricesRaw_, uint8[] memory decimals_, uint8[] memory tokenTypes_);
/// @notice True if `configsMap[token_]` lists at least one key with this eMode.
function isEmodeValid(uint256 emode_, address token_) external view returns (bool);
/// @notice Returns every oracle key row for `token_` with best-effort primary (and alt) leg rates and composed prices.
/// @dev Uses non-reverting source reads (`doRevert_ = false`); failed legs surface as `rate == 0` and may zero the composed `price`.
/// @param token_ Token to enumerate.
/// @return infos_ One struct per configured `(eMode, isOperate, isCollateral)` row in `configsMap[token_]`.
function getConfiguredTokenOracles(
address token_
) external view returns (ViewStructs.ConfiguredTokenOracle[] memory infos_);
}
contracts/oracleV2/usdOracle/error.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
contract Error {
error FluidUsdOracleError(uint256 errorId_);
function _revert(uint256 errorId_) internal pure {
revert FluidUsdOracleError(errorId_);
}
}
contracts/oracleV2/usdOracle/errorTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
library ErrorTypes {
uint256 internal constant UsdOracle__AddressZero = 310001;
uint256 internal constant UsdOracle__Unauthorized = 310002;
uint256 internal constant UsdOracle__InvalidMultiplier = 310003;
uint256 internal constant UsdOracle__InvalidSource = 310004;
uint256 internal constant UsdOracle__NoConfig = 310005;
uint256 internal constant UsdOracle__InvalidSourceType = 310006;
uint256 internal constant UsdOracle__RateZero = 310007;
uint256 internal constant UsdOracle__ChainlinkStale = 310008;
uint256 internal constant UsdOracle__InvalidParams = 310009;
uint256 internal constant UsdOracle__RateInvalid = 310010;
uint256 internal constant UsdOracle__ConfigDoesNotExist = 310011;
uint256 internal constant UsdOracle__InvalidCapConfig = 310012;
uint256 internal constant UsdOracle__AltSourceNotConfigured = 310013;
uint256 internal constant UsdOracle__TokenPaused = 310014;
uint256 internal constant UsdOracle__KeyNotRegistered = 310015;
uint256 internal constant UsdOracle__TokenNotListed = 310016;
uint256 internal constant UsdOracle__MaxDeviation = 310019;
uint256 internal constant UsdOracle__PriceModeNotAllowed = 310020;
uint256 internal constant UsdOracle__AdditionalNotAllowedForNonPeg = 310021;
uint256 internal constant UsdOracle__SourceConfigNotSet = 310022;
/// @dev `removeAltSourceConfig` / `removeAdditionalAltSourceConfig` while any per-key config for the token still has fallback enabled.
uint256 internal constant UsdOracle__FallbackMustBeDisabled = 310023;
/// @dev `removeAltSourceConfig` / `removeAdditionalAltSourceConfig` while any per-key config for the token still has `maxDeviationBPS > 0`.
uint256 internal constant UsdOracle__DeviationCheckMustBeDisabled = 310024;
/// @dev self-call-only method called by an external account (e.g. `_getPriceImplNoWrite`).
uint256 internal constant UsdOracle__OnlySelf = 310025;
/// @dev source-config removal, or `setTokenType` across the PEG boundary, while a key still has CROSS_PATH.
uint256 internal constant UsdOracle__CrossPathMustBeDisabled = 310026;
/// @dev constructor: `MAIN_VIEWS` does not report `MAIN_VIEWS_LAYOUT_VERSION`, i.e. it was built from another storage layout.
uint256 internal constant UsdOracle__MainViewsLayoutMismatch = 310027;
/// @dev `delegateMainViews` called with calldata that is not `getConfiguredTokenOracles`.
uint256 internal constant UsdOracle__InvalidMainViewsCall = 310028;
}
contracts/oracleV2/usdOracle/events.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { Structs } from "./structs.sol";
abstract contract Events is Structs {
// ---- Token-level source config events ----
event LogSourceConfigSet(address token, SourceConfig source1, SourceConfig source2, SourceConfig source3);
event LogSourceConfigRemoved(address token);
event LogAltSourceConfigSet(
address token,
SourceConfig altSource1,
SourceConfig altSource2,
SourceConfig altSource3
);
event LogAltSourceConfigRemoved(address token);
event LogAdditionalSourceConfigSet(address token, SourceConfig source1, SourceConfig source2, SourceConfig source3);
event LogAdditionalSourceConfigRemoved(address token);
event LogAdditionalAltSourceConfigSet(
address token,
SourceConfig altSource1,
SourceConfig altSource2,
SourceConfig altSource3
);
event LogAdditionalAltSourceConfigRemoved(address token);
// ---- Per-key config events ----
/// @dev Emitted by `setPriceMode`.
event LogPriceModeSet(OracleKey key, uint8 priceMode);
event LogOracleKeyConfigRemoved(OracleKey key);
event LogSourceCapModeSet(OracleKey key, uint8 sourceCapMode);
event LogOverallCapSet(OracleKey key, uint8 overallCapMode, uint16 overallCapOperand);
event LogDeviationCheckEnabled(OracleKey key, uint24 maxDeviationBPS);
event LogDeviationCheckDisabled(OracleKey key);
event LogFallbackEnabled(OracleKey key);
event LogFallbackDisabled(OracleKey key);
/// @notice emitted when the reference chain is allowed to fall back to its own alt chain
event LogCrossFallbackEnabled(OracleKey key);
/// @notice emitted when reference fallback is disabled again
event LogCrossFallbackDisabled(OracleKey key);
// ---- Token metadata + guardian events ----
event LogGuardianSet(address guardian, bool allowed);
event LogTokenPauseSet(address token, bool operatePaused, bool liquidatePaused);
event LogTokenTypeSet(address token, uint8 tokenType, uint8 decimals);
event LogTokenConfigGovernanceApproved(address token, bool approved);
}
contracts/oracleV2/usdOracle/main.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { UUPSUpgradeable } from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IUSDOracle } from "../interfaces/iUSDOracle.sol";
import { IFluidCappedRate } from "../interfaces/iFluidCappedRate.sol";
import { IFluidOracleWithDebt } from "../interfaces/iFluidOracleWithDebt.sol";
import { IChainlinkAggregatorV3 } from "../interfaces/external/IChainlinkAggregatorV3.sol";
import { Variables } from "./variables.sol";
import { Error } from "./error.sol";
import { ErrorTypes } from "./errorTypes.sol";
import { Events } from "./events.sol";
import { ChainlinkSourceReader } from "./sourceReaders/chainlinkSourceReader.sol";
import { FluidSourceReader } from "./sourceReaders/fluidSourceReader.sol";
import { TokenSymbolResolver } from "../common/tokenSymbolResolver.sol";
interface IReadFromStorage {
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}
// ==================== Core ====================
abstract contract FluidUsdOracleCore is Variables, Error {
/// @dev validates that an address is not the zero address
modifier validAddress(address value_) {
_checkValidAddress(value_);
_;
}
function _checkValidAddress(address value_) internal pure {
if (value_ == address(0)) {
_revert(ErrorTypes.UsdOracle__AddressZero);
}
}
/// @dev Computes the storage key for a config lookup.
function _keyHash(
address token_,
uint256 eMode_,
uint256 isOperate_,
uint256 isCollateral_
) internal pure returns (bytes32) {
return keccak256(abi.encode(token_, eMode_, isOperate_, isCollateral_));
}
/// @dev SOURCE_CHAINLINK and SOURCE_REDSTONE both use AggregatorV3-compatible feeds.
function _isChainlinkStyleSourceType(uint8 sourceType_) internal pure returns (bool) {
return sourceType_ == SOURCE_CHAINLINK || sourceType_ == SOURCE_REDSTONE;
}
/// @dev Returns true if `configsMap[token_]` contains at least one row with `eMode == eMode_`.
function _tokenHasEmodeInConfigsMap(address token_, uint256 eMode_) internal view returns (bool) {
ConfigMap[] storage maps_ = configsMap[token_];
uint256 len_ = maps_.length;
for (uint256 i = 0; i < len_; ++i) {
if (uint256(maps_[i].eMode) == eMode_) {
return true;
}
}
return false;
}
/// @dev True for STABLE tokens in PEG mode, which resolve to a constant $1 and skip the price tree.
function _isStablePeg(uint8 tokenType_, uint8 priceMode_) internal pure returns (bool) {
return tokenType_ == TOKEN_TYPE_STABLE && priceMode_ == PRICE_MODE_PEG;
}
/// @dev True for the two cross-path overall cap modes, which price against a second source leg.
function _isCrossPath(uint8 overallCapMode_) internal pure returns (bool) {
return overallCapMode_ == OVERALL_CAP_MIN_CROSS_PATH || overallCapMode_ == OVERALL_CAP_MAX_CROSS_PATH;
}
/// @dev Reverts if any listed key for `token_` still has a deviation check, or, with `checkAltBuckets_`,
/// fallback or CROSS_PATH. With `rejectPegModeCaps_`, also if a PEG-mode key carries a per-leg or
/// overall cap: on a STABLE token that key returns `$1` before any cap runs.
function _revertIfTokenKeysBlockAltRemoval(
address token_,
bool checkAltBuckets_,
bool rejectPegModeCaps_
) internal view {
ConfigMap[] storage maps_ = configsMap[token_];
uint256 len_ = maps_.length;
for (uint256 i = 0; i < len_; ++i) {
ConfigMap memory cm_ = maps_[i];
bytes32 keyHash_ = _keyHash(token_, uint256(cm_.eMode), cm_.isOperate ? 1 : 0, cm_.isCollateral ? 1 : 0);
OracleKeyConfig memory keyCfg_ = _configs[keyHash_];
if (keyCfg_.priceMode == PRICE_MODE_NOT_SET) {
continue;
}
if (checkAltBuckets_ && keyCfg_.flagsBitmap & (KEY_FLAG_FALLBACK | KEY_FLAG_CROSS_FALLBACK) != 0) {
_revert(ErrorTypes.UsdOracle__FallbackMustBeDisabled);
}
if (keyCfg_.maxDeviationBPS > 0) {
_revert(ErrorTypes.UsdOracle__DeviationCheckMustBeDisabled);
}
if (checkAltBuckets_ && _isCrossPath(keyCfg_.overallCapMode)) {
_revert(ErrorTypes.UsdOracle__CrossPathMustBeDisabled);
}
if (
rejectPegModeCaps_ &&
keyCfg_.priceMode == PRICE_MODE_PEG &&
(keyCfg_.sourceCapMode != SOURCE_CAP_NONE || keyCfg_.overallCapMode != OVERALL_CAP_NONE)
) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
}
}
}
// ==================== Authorization ====================
/// @dev All access control: governance resolution, modifiers, transient storage session,
/// guardian management, and token pause logic.
abstract contract FluidUsdOracleAuthorization is FluidUsdOracleCore, Events {
/// @dev Validates that an address is governance (at Liquidity)
modifier onlyGovernance() {
_checkAuth(false);
_;
}
/// @dev Validates that an address is either governance (at Liquidity) or TEAM_MULTISIG
modifier onlyGovernanceOrMultisig() {
_checkAuth(true);
_;
}
/// @dev Ensures a key has been registered in transient storage for this transaction.
modifier onlyWithTransientOracleKey() {
_checkOnlyWithTransientOracleKey();
_;
}
/// @dev Allows governance always. Allows multisig only if _tIsNewConfig == 1.
modifier onlyGovernanceOrMSNewConfig() {
_checkAuth(_tIsNewConfig == 1);
_;
}
/// @dev Ensures a config exists for the registered key (priceMode is set).
modifier onlyForExistingConfig() {
_checkOnlyForExistingConfig();
_;
}
/// @dev Governance always; TEAM_MULTISIG only when `allowMultisig_`.
function _checkAuth(bool allowMultisig_) internal view {
if (msg.sender == _getGovernanceAddr()) {
return;
}
if (allowMultisig_ && msg.sender == TEAM_MULTISIG) {
return;
}
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
/// @dev TEAM_MULTISIG and not also governance (needed for when TEAM_MULTISIG == governance).
function _isTeamMultisig() internal view returns (bool) {
return msg.sender == TEAM_MULTISIG && msg.sender != _getGovernanceAddr();
}
/// @dev Reverts if `registerTransientOracleKey` was not called in this tx.
function _checkOnlyWithTransientOracleKey() internal view {
if (_tToken == address(0)) {
_revert(ErrorTypes.UsdOracle__KeyNotRegistered);
}
}
/// @dev Reverts if no priceMode is set for the registered key.
function _checkOnlyForExistingConfig() internal view {
if (!_registeredConfigExists()) {
_revert(ErrorTypes.UsdOracle__ConfigDoesNotExist);
}
}
/// @notice Registers an `OracleKey` in transient storage for subsequent admin calls within the same transaction.
/// @dev Must be called before any other per-key admin method. Calling again overwrites and resets the new-config flag.
/// Reverts if the token has not been listed via `setTokenType`.
/// @param key_ Token, eMode, operate/collateral tuple identifying the per-key config being edited.
function registerTransientOracleKey(OracleKey memory key_) external onlyGovernanceOrMultisig {
if (key_.token == address(0)) {
_revert(ErrorTypes.UsdOracle__AddressZero);
}
if (key_.isOperate > 1 || key_.isCollateral > 1 || key_.eMode > type(uint240).max) {
_revert(ErrorTypes.UsdOracle__InvalidParams);
}
if (_tokenSources[key_.token].primarySrc.tokenType == TOKEN_TYPE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__TokenNotListed);
}
_tToken = key_.token;
_tEMode = key_.eMode;
_tIsOperate = key_.isOperate;
_tIsCollateral = key_.isCollateral;
_tIsNewConfig = 0;
}
/// @notice Sets or removes a guardian address for operate-side pause toggles.
/// @dev Only governance may call. Guardians cannot change liquidate pause state.
/// @param guardian_ Address to grant or revoke guardian role.
/// @param allowed_ True to enable, false to disable.
function setGuardian(address guardian_, bool allowed_) external onlyGovernance validAddress(guardian_) {
_guardians[guardian_] = allowed_ ? 1 : 0;
emit LogGuardianSet(guardian_, allowed_);
}
/// @notice Lists a token and assigns its type (PEG, STABLE, VOLATILE).
/// @dev Governance may change the type of an already-listed token. Multisig may only list a token that is
/// not yet listed (`TOKEN_TYPE_NOT_SET`); post-listing type changes are governance-only.
/// Crossing the PEG type boundary reverts while any key still reads a second leg (fallback,
/// deviation check, or CROSS_PATH): which bucket that leg lives in is type-dependent. Any retype
/// reverts while a key has a deviation check, whose reference is `$1` on STABLE and the alt otherwise.
/// Retyping to STABLE also reverts while a PEG-mode key carries a cap, which the constant `$1` skips.
/// Fetches and stores ERC20 `decimals` (18 for `NATIVE_TOKEN_ADDRESS`). Writes `_tokenSources[token_].primarySrc` metadata fields only.
/// @param token_ ERC20 or native sentinel address to list.
/// @param tokenType_ One of `TOKEN_TYPE_PEG`, `TOKEN_TYPE_STABLE`, or `TOKEN_TYPE_VOLATILE`.
function setTokenType(address token_, uint8 tokenType_) external onlyGovernanceOrMultisig validAddress(token_) {
if (tokenType_ == TOKEN_TYPE_NOT_SET || tokenType_ > TOKEN_TYPE_VOLATILE) {
_revert(ErrorTypes.UsdOracle__InvalidParams);
}
TokenSourceConfig storage cfg_ = _tokenSources[token_];
if (_isTeamMultisig() && cfg_.primarySrc.tokenType != TOKEN_TYPE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
// PEG reads its second leg from `_additionalTokenSources`, STABLE / VOLATILE from `altSrc`, so fallback
// and CROSS_PATH only move across that boundary; the deviation reference moves on every retype
// ($1 on STABLE, the alt on VOLATILE, which a STABLE token may not even have)
uint8 previousType_ = cfg_.primarySrc.tokenType;
if (previousType_ != TOKEN_TYPE_NOT_SET && previousType_ != tokenType_) {
bool crossesPegBoundary_ = (previousType_ == TOKEN_TYPE_PEG) != (tokenType_ == TOKEN_TYPE_PEG);
_revertIfTokenKeysBlockAltRemoval(token_, crossesPegBoundary_, tokenType_ == TOKEN_TYPE_STABLE);
}
uint8 decimals_;
if (token_ == NATIVE_TOKEN_ADDRESS) {
decimals_ = 18;
} else {
decimals_ = IERC20Metadata(token_).decimals();
}
cfg_.primarySrc.tokenType = tokenType_;
cfg_.primarySrc.decimals = decimals_;
emit LogTokenTypeSet(token_, tokenType_, decimals_);
}
/// @notice Sets per-token pause bits for pricing: operate (bit 0) and/or liquidate (bit 1).
/// @dev Guardians may toggle operate pause only; governance or multisig may set any combination.
/// @param token_ Token whose pause state is updated.
/// @param pauseOperate_ When true, sets `PAUSED_OPERATE` on the token metadata.
/// @param pauseLiquidate_ When true, sets `PAUSED_LIQUIDATE` on the token metadata.
function setPausedState(address token_, bool pauseOperate_, bool pauseLiquidate_) external validAddress(token_) {
bool isGovernanceOrMultisig_ = msg.sender == _getGovernanceAddr() || msg.sender == TEAM_MULTISIG;
if (!isGovernanceOrMultisig_ && _guardians[msg.sender] != 1) {
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
TokenSourceConfig storage cfg_ = _tokenSources[token_];
if (!isGovernanceOrMultisig_) {
bool isLiquidatePaused_ = cfg_.primarySrc.pauseState & PAUSED_LIQUIDATE != 0;
if (pauseLiquidate_ != isLiquidatePaused_) {
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
}
uint8 newState_ = (pauseOperate_ ? PAUSED_OPERATE : 0) | (pauseLiquidate_ ? PAUSED_LIQUIDATE : 0);
cfg_.primarySrc.pauseState = newState_;
emit LogTokenPauseSet(token_, pauseOperate_, pauseLiquidate_);
}
/// @notice Sets or clears the governance-approved flag on token-level oracle sources (`FLAG_GOVERNANCE_APPROVED`).
/// @dev Only governance may call. Used to stamp multisig-created token-level configs or revoke approval.
/// @param token_ Token whose approval bit is updated.
/// @param approved_ True to set the flag, false to clear it.
function setTokenConfigGovernanceApproved(
address token_,
bool approved_
) external onlyGovernance validAddress(token_) {
_setTokenGovernanceApproved(token_, _tokenSources[token_], approved_);
}
// --- Internal methods ---
/// @dev `approved_ == true` sets `FLAG_GOVERNANCE_APPROVED`; `false` clears it (e.g. multisig token-level source write).
function _setTokenGovernanceApproved(address token_, TokenSourceConfig storage cfg_, bool approved_) internal {
if (approved_) {
cfg_.primarySrc.flagsBitmap |= FLAG_GOVERNANCE_APPROVED;
} else {
cfg_.primarySrc.flagsBitmap &= ~FLAG_GOVERNANCE_APPROVED;
}
emit LogTokenConfigGovernanceApproved(token_, approved_);
}
/// @dev gets the governance address at Liquidity.
function _getGovernanceAddr() internal view virtual returns (address governance_) {
governance_ = address(uint160(IReadFromStorage(LIQUIDITY).readFromStorage(LIQUIDITY_GOVERNANCE_SLOT)));
}
/// @dev Loads the registered OracleKey from transient storage.
function _getRegisteredKey() internal view returns (OracleKey memory key_) {
key_.token = _tToken;
key_.eMode = _tEMode;
key_.isOperate = uint8(_tIsOperate);
key_.isCollateral = uint8(_tIsCollateral);
}
/// @dev Clears the transient admin session for the current transaction.
function _clearRegisteredKey() internal {
_tToken = address(0);
_tEMode = 0;
_tIsOperate = 0;
_tIsCollateral = 0;
_tIsNewConfig = 0;
}
/// @dev Returns storage pointer to the OracleKeyConfig for the registered key.
function _getRegisteredConfig() internal view returns (OracleKeyConfig storage) {
return _configs[_keyHash(_tToken, _tEMode, _tIsOperate, _tIsCollateral)];
}
/// @dev Governance may always create or modify. TEAM_MULTISIG may only create new configs
/// (exact slot empty) on tokens that are not yet governance-approved.
function _revertIfTeamMultisigModifiesExistingConfig(bool exists_) internal view {
if (exists_ && _isTeamMultisig()) {
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
}
/// @dev Per-key create/modify gate for `setPriceMode`. Same create-only rule as the bool overload,
/// plus: TEAM_MULTISIG creating eMode≠0 is treated as modifying existing live config when that
/// leg already has eMode 0 and the token is `FLAG_GOVERNANCE_APPROVED` (would shadow fallback).
function _revertIfTeamMultisigModifiesExistingConfig(
bool exists_,
OracleKey memory key_,
TokenSourceConfig storage tokenCfg_
) internal view {
if (!_isTeamMultisig()) {
return;
}
if (exists_) {
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
if (
key_.eMode == 0 ||
tokenCfg_.primarySrc.flagsBitmap & FLAG_GOVERNANCE_APPROVED == 0 ||
_configs[_keyHash(key_.token, 0, key_.isOperate, key_.isCollateral)].priceMode == PRICE_MODE_NOT_SET
) {
return;
}
_revert(ErrorTypes.UsdOracle__Unauthorized);
}
/// @dev Checks if a configuration exists for the registered key (priceMode is set).
function _registeredConfigExists() internal view returns (bool) {
return _getRegisteredConfig().priceMode != PRICE_MODE_NOT_SET;
}
}
// ==================== Upgradeable ====================
abstract contract FluidUsdOracleUpgradeable is FluidUsdOracleAuthorization, UUPSUpgradeable {
/// @dev Restricts UUPS implementation upgrades to governance (`onlyGovernance`).
function _authorizeUpgrade(address) internal virtual override onlyGovernance {}
}
// ==================== Token Source Configs ====================
/// @dev Token-level source configuration: primary/alt sources in _tokenSources and _additionalTokenSources.
/// Source feeds are configured per-token and validated once here (Chainlink latestRoundData, capped-rate
/// getRate, etc.). All per-key configs that reference this token+mode inherit the validated sources
/// automatically — no feed re-specification or re-validation needed when adding new keys.
/// These methods do NOT use the transient admin session (no registerTransientOracleKey needed).
abstract contract FluidUsdOracleTokenSourceConfigs is FluidUsdOracleUpgradeable {
// ---- Primary Source Config (in _tokenSources) ----
// For VOLATILE/STABLE this is market price; for PEG this is peg price.
/// @notice Sets primary (up to three leg) source configuration for a listed token.
/// @dev Does not use the transient oracle key session. TEAM_MULTISIG may only create a new primary config, not overwrite.
/// Blocked entirely once the token is governance-approved.
/// @param token_ Listed token address.
/// @param src1_ Required first source chain leg.
/// @param src2_ Optional second leg; use `SOURCE_NOT_SET` / zero address to omit.
/// @param src3_ Optional third leg; must be unset if `src2_` is unset.
function setSourceConfig(
address token_,
SourceConfig memory src1_,
SourceConfig memory src2_,
SourceConfig memory src3_
) external onlyGovernanceOrMultisig validAddress(token_) {
TokenSourceConfig storage cfg_ = _tokenSources[token_];
_revertIfTeamMultisigModifiesExistingConfig(
cfg_.primarySrc.sourceType1 != SOURCE_NOT_SET || cfg_.primarySrc.flagsBitmap & FLAG_GOVERNANCE_APPROVED != 0
);
if (cfg_.primarySrc.tokenType == TOKEN_TYPE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__TokenNotListed);
}
_validateThreeSourceConfig(src1_, src2_, src3_);
_writeSources(cfg_.primarySrc, src1_, src2_, src3_);
_setTokenGovernanceApproved(token_, cfg_, !_isTeamMultisig());
emit LogSourceConfigSet(token_, src1_, src2_, src3_);
}
/// @notice Removes primary source configuration for a token.
/// @dev If alt sources exist, calls `removeAltSourceConfig` first. Only governance.
/// @param token_ Token whose primary sources are cleared.
function removeSourceConfig(address token_) external onlyGovernance validAddress(token_) {
TokenSourceConfig storage cfg_ = _tokenSources[token_];
if (cfg_.primarySrc.sourceType1 == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
// primary removal breaks every key; guard fallback/deviation keys like alt removal does
_revertIfTokenKeysBlockAltRemoval(token_, true, false);
if (cfg_.primarySrc.flagsBitmap & FLAG_HAS_ALT_SOURCE != 0) {
removeAltSourceConfig(token_);
}
_clearSources(cfg_.primarySrc);
_setTokenGovernanceApproved(token_, cfg_, true);
emit LogSourceConfigRemoved(token_);
}
// ---- Alt Source Config (in _tokenSources, slots 4-6) ----
/// @notice Sets alt (fallback / deviation second-leg) source configuration for a token.
/// @dev Requires primary sources. TEAM_MULTISIG may only create a new alt config, not overwrite.
/// Blocked entirely once the token is governance-approved.
/// @param token_ Listed token address.
/// @param alt1_ First alt leg (required if configuring alt).
/// @param alt2_ Optional second alt leg.
/// @param alt3_ Optional third alt leg.
function setAltSourceConfig(
address token_,
SourceConfig memory alt1_,
SourceConfig memory alt2_,
SourceConfig memory alt3_
) external onlyGovernanceOrMultisig validAddress(token_) {
TokenSourceConfig storage cfg_ = _tokenSources[token_];
_revertIfTeamMultisigModifiesExistingConfig(
cfg_.primarySrc.flagsBitmap & (FLAG_HAS_ALT_SOURCE | FLAG_GOVERNANCE_APPROVED) != 0
);
if (cfg_.primarySrc.sourceType1 == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
_validateThreeSourceConfig(alt1_, alt2_, alt3_);
_writeSources(cfg_.altSrc, alt1_, alt2_, alt3_);
cfg_.primarySrc.flagsBitmap = cfg_.primarySrc.flagsBitmap | FLAG_HAS_ALT_SOURCE;
_setTokenGovernanceApproved(token_, cfg_, !_isTeamMultisig());
emit LogAltSourceConfigSet(token_, alt1_, alt2_, alt3_);
}
/// @notice Removes alt source configuration and clears `FLAG_HAS_ALT_SOURCE`.
/// @dev Reverts if any key for `token_` still has fallback enabled or deviation check (`maxDeviationBPS > 0`).
/// Only governance.
/// @param token_ Token whose alt sources are cleared.
function removeAltSourceConfig(address token_) public onlyGovernance validAddress(token_) {
TokenSourceConfig storage cfg_ = _tokenSources[token_];
if (cfg_.primarySrc.flagsBitmap & FLAG_HAS_ALT_SOURCE == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
_revertIfTokenKeysBlockAltRemoval(token_, true, false);
_clearSources(cfg_.altSrc);
cfg_.primarySrc.flagsBitmap = cfg_.primarySrc.flagsBitmap & ~FLAG_HAS_ALT_SOURCE;
_setTokenGovernanceApproved(token_, cfg_, true);
emit LogAltSourceConfigRemoved(token_);
}
// ---- Additional Source Config (in _additionalTokenSources) ----
// Only for PEG tokens. Stores market price sources (secondary price type for PEG).
/// @notice Sets additional market-price sources for a PEG token (`_additionalTokenSources.primarySrc`).
/// @dev TEAM_MULTISIG may only create a new additional config, not overwrite. Only valid for `TOKEN_TYPE_PEG`.
/// Blocked entirely once the token is governance-approved.
/// @param token_ PEG token address.
/// @param src1_ First market source leg.
/// @param src2_ Optional second leg.
/// @param src3_ Optional third leg.
function setAdditionalSourceConfig(
address token_,
SourceConfig memory src1_,
SourceConfig memory src2_,
SourceConfig memory src3_
) external onlyGovernanceOrMultisig validAddress(token_) {
TokenSourceConfig storage mainCfg_ = _tokenSources[token_];
_revertIfTeamMultisigModifiesExistingConfig(
mainCfg_.primarySrc.flagsBitmap & (FLAG_HAS_ADDITIONAL_SOURCES | FLAG_GOVERNANCE_APPROVED) != 0
);
if (mainCfg_.primarySrc.tokenType != TOKEN_TYPE_PEG) {
_revert(ErrorTypes.UsdOracle__AdditionalNotAllowedForNonPeg);
}
_validateThreeSourceConfig(src1_, src2_, src3_);
_writeSources(_additionalTokenSources[token_].primarySrc, src1_, src2_, src3_);
mainCfg_.primarySrc.flagsBitmap = mainCfg_.primarySrc.flagsBitmap | FLAG_HAS_ADDITIONAL_SOURCES;
_setTokenGovernanceApproved(token_, mainCfg_, !_isTeamMultisig());
emit LogAdditionalSourceConfigSet(token_, src1_, src2_, src3_);
}
/// @notice Removes additional (market) primary sources for a PEG token.
/// @dev If additional alt sources exist, removes them first. Only governance.
/// @param token_ PEG token address.
function removeAdditionalSourceConfig(address token_) external onlyGovernance validAddress(token_) {
TokenSourceConfig storage mainCfg_ = _tokenSources[token_];
if (mainCfg_.primarySrc.flagsBitmap & FLAG_HAS_ADDITIONAL_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
// additional sources back the PEG deviation/cross-path leg; guard fallback/deviation keys like alt removal does
_revertIfTokenKeysBlockAltRemoval(token_, true, false);
if (mainCfg_.primarySrc.flagsBitmap & FLAG_HAS_ADDITIONAL_ALT_SOURCES != 0) {
removeAdditionalAltSourceConfig(token_);
}
_clearSources(_additionalTokenSources[token_].primarySrc);
mainCfg_.primarySrc.flagsBitmap = mainCfg_.primarySrc.flagsBitmap & ~FLAG_HAS_ADDITIONAL_SOURCES;
_setTokenGovernanceApproved(token_, mainCfg_, true);
emit LogAdditionalSourceConfigRemoved(token_);
}
// ---- Additional Alt Source Config (in _additionalTokenSources, slots 4-6) ----
/// @notice Sets alt sources for the additional (market) mapping on a PEG token.
/// @dev Requires `setAdditionalSourceConfig` to exist. TEAM_MULTISIG may only create, not overwrite.
/// Blocked entirely once the token is governance-approved.
/// @param token_ PEG token address.
/// @param alt1_ First additional-alt leg.
/// @param alt2_ Optional second leg.
/// @param alt3_ Optional third leg.
function setAdditionalAltSourceConfig(
address token_,
SourceConfig memory alt1_,
SourceConfig memory alt2_,
SourceConfig memory alt3_
) external onlyGovernanceOrMultisig validAddress(token_) {
TokenSourceConfig storage mainCfg_ = _tokenSources[token_];
_revertIfTeamMultisigModifiesExistingConfig(
mainCfg_.primarySrc.flagsBitmap & (FLAG_HAS_ADDITIONAL_ALT_SOURCES | FLAG_GOVERNANCE_APPROVED) != 0
);
if (mainCfg_.primarySrc.flagsBitmap & FLAG_HAS_ADDITIONAL_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
_validateThreeSourceConfig(alt1_, alt2_, alt3_);
_writeSources(_additionalTokenSources[token_].altSrc, alt1_, alt2_, alt3_);
mainCfg_.primarySrc.flagsBitmap = mainCfg_.primarySrc.flagsBitmap | FLAG_HAS_ADDITIONAL_ALT_SOURCES;
_setTokenGovernanceApproved(token_, mainCfg_, !_isTeamMultisig());
emit LogAdditionalAltSourceConfigSet(token_, alt1_, alt2_, alt3_);
}
/// @notice Removes additional alt sources and clears `FLAG_HAS_ADDITIONAL_ALT_SOURCES`.
/// @dev Same key-level constraints as `removeAltSourceConfig`. Only governance.
/// @param token_ PEG token address.
function removeAdditionalAltSourceConfig(address token_) public onlyGovernance validAddress(token_) {
TokenSourceConfig storage mainCfg_ = _tokenSources[token_];
if (mainCfg_.primarySrc.flagsBitmap & FLAG_HAS_ADDITIONAL_ALT_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
_revertIfTokenKeysBlockAltRemoval(token_, true, false);
_clearSources(_additionalTokenSources[token_].altSrc);
mainCfg_.primarySrc.flagsBitmap = mainCfg_.primarySrc.flagsBitmap & ~FLAG_HAS_ADDITIONAL_ALT_SOURCES;
_setTokenGovernanceApproved(token_, mainCfg_, true);
emit LogAdditionalAltSourceConfigRemoved(token_);
}
// --- Internal methods ---
/// @dev Verifies that the source chain is contiguous and each configured source is valid.
function _validateThreeSourceConfig(
SourceConfig memory sourceCfg1_,
SourceConfig memory sourceCfg2_,
SourceConfig memory sourceCfg3_
) internal {
_verifySourceConfig(sourceCfg1_.sourceType, sourceCfg1_.source);
if (sourceCfg3_.sourceType != SOURCE_NOT_SET && sourceCfg2_.sourceType == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
_validateOptionalSourceConfig(sourceCfg2_);
_validateOptionalSourceConfig(sourceCfg3_);
}
/// @dev Validates an optional 2nd/3rd source leg; no-op when `SOURCE_NOT_SET`.
function _validateOptionalSourceConfig(SourceConfig memory sourceCfg_) internal {
if (sourceCfg_.sourceType == SOURCE_NOT_SET) {
if (sourceCfg_.source != address(0)) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
return;
}
_verifySourceConfig(sourceCfg_.sourceType, sourceCfg_.source);
}
/// @dev Verifies that the source configuration is valid for the given source type and address.
function _verifySourceConfig(uint8 sourceType_, address source_) internal {
if (sourceType_ != SOURCE_STABLE && source_ == address(0)) {
_revert(ErrorTypes.UsdOracle__AddressZero);
}
if (sourceType_ == SOURCE_CAPPED_RATE) {
if (!_isCappedRate(source_)) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
return;
}
if (sourceType_ == SOURCE_FLUID_ORACLE) {
if (!_isFluidOracleWithDebt(source_)) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
return;
}
if (_isChainlinkStyleSourceType(sourceType_)) {
if (!_isChainlinkFeed(source_)) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
return;
}
if (sourceType_ == SOURCE_STABLE) {
if (source_ != address(0)) {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
return;
}
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
/// @dev Checks if the provided address is a valid Chainlink feed by calling latestRoundData.
function _isChainlinkFeed(address contract_) internal view returns (bool) {
try IChainlinkAggregatorV3(contract_).latestRoundData() returns (
uint80 roundId,
int256,
uint256,
uint256,
uint80
) {
if (roundId > 0) {
return true;
}
} catch {}
return false;
}
/// @dev Checks if the provided address implements the FluidCappedRate interface with required methods.
function _isCappedRate(address contract_) internal returns (bool) {
try IFluidCappedRate(contract_).centerPrice() returns (uint256 value) {
if (value == 0) {
return false;
}
} catch {
return false;
}
return _isFluidOracleWithDebt(contract_);
}
/// @dev Checks if the address implements Fluid oracle + debt getters (e.g. CLX). No `centerPrice()` required.
function _isFluidOracleWithDebt(address contract_) internal view returns (bool) {
try IFluidOracleWithDebt(contract_).getExchangeRateOperate() returns (uint256 value) {
if (value == 0) {
return false;
}
} catch {
return false;
}
try IFluidOracleWithDebt(contract_).getExchangeRateOperateDebt() returns (uint256 value) {
if (value == 0) {
return false;
}
} catch {
return false;
}
return true;
}
/// @dev Writes a 3-source chain into a TokenSources bucket.
function _writeSources(
TokenSources storage bucket_,
SourceConfig memory src1_,
SourceConfig memory src2_,
SourceConfig memory src3_
) internal {
bucket_.source1 = src1_.source;
bucket_.multiplier1 = _deriveMultiplier(src1_.sourceType, src1_.source);
bucket_.sourceType1 = src1_.sourceType;
bucket_.sourceType2 = src2_.sourceType;
bucket_.sourceType3 = src3_.sourceType;
bucket_.capOperand1 = src1_.capOperand;
bucket_.source2 = src2_.source;
bucket_.multiplier2 = _deriveMultiplier(src2_.sourceType, src2_.source);
bucket_.capOperand2 = src2_.capOperand;
bucket_.source3 = src3_.source;
bucket_.multiplier3 = _deriveMultiplier(src3_.sourceType, src3_.source);
bucket_.capOperand3 = src3_.capOperand;
}
/// @dev Derives and validates source multiplier; return is stored for read-path gas efficiency.
function _deriveMultiplier(uint8 sourceType_, address source_) internal view returns (int8 multiplier_) {
if (
sourceType_ == SOURCE_NOT_SET ||
sourceType_ == SOURCE_CAPPED_RATE ||
sourceType_ == SOURCE_FLUID_ORACLE ||
sourceType_ == SOURCE_STABLE
) {
return 0;
}
if (_isChainlinkStyleSourceType(sourceType_)) {
uint8 feedDecimals_;
try IChainlinkAggregatorV3(source_).decimals() returns (uint8 d_) {
feedDecimals_ = d_;
} catch {
_revert(ErrorTypes.UsdOracle__InvalidSource);
}
int256 derived_ = int256(uint256(27)) - int256(uint256(feedDecimals_));
if (derived_ > MAX_MULTIPLIER || derived_ < MIN_MULTIPLIER) {
_revert(ErrorTypes.UsdOracle__InvalidMultiplier);
}
return int8(derived_);
}
_revert(ErrorTypes.UsdOracle__InvalidSourceType);
}
/// @dev Clears a 3-source chain from a TokenSources bucket.
function _clearSources(TokenSources storage bucket_) internal {
bucket_.source1 = address(0);
bucket_.multiplier1 = 0;
bucket_.sourceType1 = SOURCE_NOT_SET;
bucket_.sourceType2 = SOURCE_NOT_SET;
bucket_.sourceType3 = SOURCE_NOT_SET;
bucket_.capOperand1 = 0;
bucket_.source2 = address(0);
bucket_.multiplier2 = 0;
bucket_.capOperand2 = 0;
bucket_.source3 = address(0);
bucket_.multiplier3 = 0;
bucket_.capOperand3 = 0;
}
}
// ==================== Key Configs ====================
/// @dev Per-key configuration: priceMode assignment, source cap mode, overall cap, deviation check, and fallback management.
/// Each key only stores a priceMode reference (which token-level source mapping to use) plus
/// key-specific parameters — source feeds are never specified here, they are inherited from the
/// token-level config. Uses the transient admin session (registerTransientOracleKey must be called first)
/// so the key tuple is confirmed once and reused across all subsequent admin calls in the tx.
abstract contract FluidUsdOracleKeyConfigs is FluidUsdOracleTokenSourceConfigs {
/// @notice Sets `PRICE_MODE_PEG` or `PRICE_MODE_MARKET` for the oracle key registered in this transaction.
/// @dev Requires `registerTransientOracleKey`. Multisig may only create new keys; governance may update.
/// Validates token type vs required token-level sources. STABLE + PEG is rejected when the key
/// already has CROSS_PATH (`$1` skips overall cap, which would leave a dead depeg floor).
/// When creating: TEAM_MULTISIG cannot add eMode≠0 for a leg that already has eMode 0 if the token
/// is governance-approved (would shadow live eMode-0 fallback). Unapproved tokens remain MS-onboardable.
/// Changing the mode of an existing key reverts `FallbackMustBeDisabled` while `KEY_FLAG_FALLBACK` or
/// `KEY_FLAG_CROSS_FALLBACK` is set: each was validated against the alt bucket of the old mapping.
/// @param priceMode_ `PRICE_MODE_MARKET` or `PRICE_MODE_PEG`.
function setPriceMode(uint8 priceMode_) external onlyWithTransientOracleKey onlyGovernanceOrMultisig {
bool exists_ = _registeredConfigExists();
OracleKey memory key_ = _getRegisteredKey();
TokenSourceConfig storage mainCfg_ = _tokenSources[key_.token];
uint8 tokenType_ = mainCfg_.primarySrc.tokenType;
if (tokenType_ == TOKEN_TYPE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__TokenNotListed);
}
_revertIfTeamMultisigModifiesExistingConfig(exists_, key_, mainCfg_);
if (priceMode_ == PRICE_MODE_PEG) {
// PEG mode: allowed for PEG tokens (needs sources) and STABLE tokens (constant $1, no sources).
// VOLATILE tokens cannot use PEG mode.
if (tokenType_ == TOKEN_TYPE_VOLATILE) {
_revert(ErrorTypes.UsdOracle__PriceModeNotAllowed);
}
if (tokenType_ == TOKEN_TYPE_PEG && mainCfg_.primarySrc.sourceType1 == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
} else if (priceMode_ == PRICE_MODE_MARKET) {
if (tokenType_ == TOKEN_TYPE_PEG) {
uint8 flags_ = mainCfg_.primarySrc.flagsBitmap;
if (flags_ & FLAG_HAS_ADDITIONAL_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
} else if (mainCfg_.primarySrc.sourceType1 == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
} else {
_revert(ErrorTypes.UsdOracle__InvalidParams);
}
bytes32 keyHash_ = _keyHash(key_.token, key_.eMode, key_.isOperate, key_.isCollateral);
if (exists_) {
OracleKeyConfig memory liveCfg_ = _configs[keyHash_];
uint8 fallbackFlags_ = liveCfg_.flagsBitmap & (KEY_FLAG_FALLBACK | KEY_FLAG_CROSS_FALLBACK);
if (
_isStablePeg(tokenType_, priceMode_) &&
(liveCfg_.maxDeviationBPS > 0 ||
fallbackFlags_ != 0 ||
liveCfg_.overallCapMode != OVERALL_CAP_NONE ||
liveCfg_.sourceCapMode != SOURCE_CAP_NONE)
) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
// both flags were validated against the alt bucket of the mapping the old mode reads
if (liveCfg_.priceMode != priceMode_ && fallbackFlags_ != 0) {
_revert(ErrorTypes.UsdOracle__FallbackMustBeDisabled);
}
}
_configs[keyHash_].priceMode = priceMode_;
if (!exists_) {
configsMap[key_.token].push(
ConfigMap({
eMode: uint240(key_.eMode),
isOperate: key_.isOperate != 0,
isCollateral: key_.isCollateral != 0
})
);
if (_isTeamMultisig()) {
_tIsNewConfig = 1;
}
}
emit LogPriceModeSet(key_, priceMode_);
}
/// @notice Deletes the per-key config for the transiently registered oracle key and removes it from `configsMap`.
/// @dev Only governance. Clears transient session after removal.
function removeConfig() external onlyGovernance onlyWithTransientOracleKey onlyForExistingConfig {
OracleKey memory key_ = _getRegisteredKey();
delete _configs[_keyHash(key_.token, key_.eMode, key_.isOperate, key_.isCollateral)];
ConfigMap[] storage arr_ = configsMap[key_.token];
for (uint i = 0; i < arr_.length; i++) {
if (
arr_[i].eMode == key_.eMode &&
arr_[i].isOperate == (key_.isOperate != 0) &&
arr_[i].isCollateral == (key_.isCollateral != 0)
) {
arr_[i] = arr_[arr_.length - 1];
arr_.pop();
break;
}
}
emit LogOracleKeyConfigRemoved(key_);
_clearRegisteredKey();
}
/// @notice Sets per-leg capping direction for the registered key (`SOURCE_CAP_MIN`, `SOURCE_CAP_MAX`, or `SOURCE_CAP_NONE`).
/// @dev `SOURCE_CAP_MIN` only for collateral keys; `SOURCE_CAP_MAX` only for debt keys. Cap operands live on token sources.
/// @param sourceCapMode_ Cap mode enum value.
function setSourceCapMode(
uint8 sourceCapMode_
) external onlyWithTransientOracleKey onlyGovernanceOrMSNewConfig onlyForExistingConfig {
if (sourceCapMode_ > SOURCE_CAP_MAX) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
if (sourceCapMode_ != SOURCE_CAP_NONE) {
_revertIfStablePegKey();
}
if (sourceCapMode_ == SOURCE_CAP_MIN) {
if (_tIsCollateral != 1) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
} else if (sourceCapMode_ == SOURCE_CAP_MAX) {
if (_tIsCollateral != 0) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
}
_getRegisteredConfig().sourceCapMode = sourceCapMode_;
emit LogSourceCapModeSet(_getRegisteredKey(), sourceCapMode_);
}
/// @dev A STABLE key in PEG mode returns the constant `$1` before any cap, deviation check or fallback, so
/// that configuration would be accepted and never run.
function _revertIfStablePegKey() internal view {
if (_isStablePeg(_tokenSources[_tToken].primarySrc.tokenType, _getRegisteredConfig().priceMode)) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
}
/// @dev Reverts unless `_tToken` has a primary source on `_tokenSources` plus the reference source the
/// second leg is read from: `_additionalTokenSources.primarySrc` for PEG (see
/// `_getPegResolvedPrice`), `_tokenSources.altSrc` otherwise. Deviation checks and cross-path
/// overall caps both compare against that same source.
function _revertIfReferenceSourceMissing() internal view {
TokenSources storage primarySrc_ = _tokenSources[_tToken].primarySrc;
if (primarySrc_.sourceType1 == SOURCE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
uint8 flags_ = primarySrc_.flagsBitmap;
if (primarySrc_.tokenType == TOKEN_TYPE_PEG) {
if (flags_ & FLAG_HAS_ADDITIONAL_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__SourceConfigNotSet);
}
} else if (flags_ & FLAG_HAS_ALT_SOURCE == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
}
/// @notice Sets overall cap mode and operand for the registered key (cross-path or operand clamp).
/// @dev MIN modes require collateral keys; MAX modes require debt keys. Cross-path operand must be 0.
/// PEG CROSS_PATH requires `_tokenSources.primarySrc` and additional (same as deviation). VOLATILE/STABLE
/// MARKET require alt. STABLE PEG is rejected. `setPriceMode(PEG)` on STABLE and `setTokenType` cannot
/// leave a live CROSS_PATH key on an incompatible mode or type.
/// Operand modes scale `overallCapOperand_` by `CAP_PRECISION` (2-decimal operand → ORACLE_PRECISION).
/// @param overallCapMode_ One of `OVERALL_CAP_*` constants.
/// @param overallCapOperand_ 2-decimal operand for operand modes; must be 0 for `OVERALL_CAP_NONE` and cross-path modes.
function setOverallCap(
uint8 overallCapMode_,
uint16 overallCapOperand_
) external onlyWithTransientOracleKey onlyGovernanceOrMSNewConfig onlyForExistingConfig {
if (overallCapMode_ > OVERALL_CAP_MAX_OPERAND) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
if (overallCapMode_ == OVERALL_CAP_NONE) {
if (overallCapOperand_ != 0) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
} else {
_revertIfStablePegKey();
if (overallCapMode_ == OVERALL_CAP_MIN_CROSS_PATH || overallCapMode_ == OVERALL_CAP_MIN_OPERAND) {
if (_tIsCollateral != 1) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
} else {
if (_tIsCollateral != 0) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
}
if (overallCapMode_ <= OVERALL_CAP_MAX_CROSS_PATH) {
if (overallCapOperand_ != 0) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
_revertIfReferenceSourceMissing();
} else {
// Operand modes: operand must be > 0
if (overallCapOperand_ == 0) {
_revert(ErrorTypes.UsdOracle__InvalidCapConfig);
}
}
}
OracleKeyConfig storage cfg_ = _getRegisteredConfig();
cfg_.overallCapMode = overallCapMode_;
cfg_.overallCapOperand = overallCapOperand_;
emit LogOverallCapSet(_getRegisteredKey(), overallCapMode_, overallCapOperand_);
}
/// @notice Enables operate-only max deviation between primary and reference leg (PEG: peg vs market; STABLE: vs `$1`; else primary vs alt).
/// @dev Requires the appropriate second-leg sources to exist, except on STABLE tokens. Can be combined with fallback.
/// @param maxDeviationBPS_ Max deviation in basis points; must satisfy `0 < maxDeviationBPS_ <= BPS_DENOMINATOR`.
function enableDeviationCheck(
uint24 maxDeviationBPS_
) external onlyWithTransientOracleKey onlyGovernanceOrMSNewConfig onlyForExistingConfig {
if (maxDeviationBPS_ == 0 || maxDeviationBPS_ > BPS_DENOMINATOR) {
_revert(ErrorTypes.UsdOracle__InvalidParams);
}
_revertIfStablePegKey();
// a STABLE key compares against the constant $1 and reads no reference for the check
if (_tokenSources[_tToken].primarySrc.tokenType != TOKEN_TYPE_STABLE) {
_revertIfReferenceSourceMissing();
}
_getRegisteredConfig().maxDeviationBPS = maxDeviationBPS_;
OracleKey memory key_ = _getRegisteredKey();
emit LogDeviationCheckEnabled(key_, maxDeviationBPS_);
}
/// @notice Disables deviation check for the registered key (`maxDeviationBPS = 0`).
/// @dev Only governance.
function disableDeviationCheck() external onlyWithTransientOracleKey onlyGovernance onlyForExistingConfig {
_getRegisteredConfig().maxDeviationBPS = 0;
OracleKey memory key_ = _getRegisteredKey();
emit LogDeviationCheckDisabled(key_);
}
/// @notice Enables fallback to the alt chain for the mapping this key uses (primary vs additional for PEG market mode).
/// @dev Requires the corresponding alt sources flag. Can be combined with deviation check.
function enableFallback() external onlyWithTransientOracleKey onlyGovernanceOrMSNewConfig onlyForExistingConfig {
_revertIfStablePegKey();
OracleKeyConfig storage cfg_ = _getRegisteredConfig();
TokenSourceConfig storage mainCfg_ = _tokenSources[_tToken];
uint8 tokenType_ = mainCfg_.primarySrc.tokenType;
uint8 flags_ = mainCfg_.primarySrc.flagsBitmap;
// Fallback uses the alt chain on whichever mapping this key reads from. For PEG tokens in MARKET
// mode, price (and thus fallback) is resolved from `_additionalTokenSources`, so we require
// `_additionalTokenSources.altSrc` (`FLAG_HAS_ADDITIONAL_ALT_SOURCES`). For all other cases the
// key uses `_tokenSources` only, so we require `_tokenSources.altSrc` (`FLAG_HAS_ALT_SOURCE`).
if (tokenType_ == TOKEN_TYPE_PEG && cfg_.priceMode == PRICE_MODE_MARKET) {
if (flags_ & FLAG_HAS_ADDITIONAL_ALT_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
} else {
if (flags_ & FLAG_HAS_ALT_SOURCE == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
}
cfg_.flagsBitmap = cfg_.flagsBitmap | KEY_FLAG_FALLBACK;
OracleKey memory key_ = _getRegisteredKey();
emit LogFallbackEnabled(key_);
}
/// @notice Disables fallback for the registered key (clears `KEY_FLAG_FALLBACK`).
/// @dev Only governance.
function disableFallback() external onlyWithTransientOracleKey onlyGovernance onlyForExistingConfig {
OracleKeyConfig storage cfg_ = _getRegisteredConfig();
cfg_.flagsBitmap = cfg_.flagsBitmap & ~KEY_FLAG_FALLBACK;
OracleKey memory key_ = _getRegisteredKey();
emit LogFallbackDisabled(key_);
}
/// @notice Enables the cross mapping's chain to fall back to its own alt chain for the registered key.
/// @dev Mirror of `enableFallback`: the cross chain is the mapping this key does NOT price from, so the
/// required alt bucket is the opposite one. Applies wherever the reference is read, so on operate keys
/// the deviation check and the CROSS_PATH cap also resolve through that alt once the reference primary
/// composes to `0`; without the flag those reads stay fail-closed.
function enableCrossFallback()
external
onlyWithTransientOracleKey
onlyGovernanceOrMSNewConfig
onlyForExistingConfig
{
OracleKeyConfig storage cfg_ = _getRegisteredConfig();
TokenSourceConfig storage mainCfg_ = _tokenSources[_tToken];
uint8 tokenType_ = mainCfg_.primarySrc.tokenType;
uint8 flags_ = mainCfg_.primarySrc.flagsBitmap;
// only PEG tokens price off two mappings; every other key has no cross mapping to fall back to
if (tokenType_ != TOKEN_TYPE_PEG) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
if (cfg_.priceMode == PRICE_MODE_MARKET) {
// prices off `_additionalTokenSources`, so the cross chain is `_tokenSources` and its alt
if (flags_ & FLAG_HAS_ALT_SOURCE == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
} else {
// prices off `_tokenSources`, so the cross chain is `_additionalTokenSources` and its alt
if (flags_ & FLAG_HAS_ADDITIONAL_ALT_SOURCES == 0) {
_revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
}
}
cfg_.flagsBitmap = cfg_.flagsBitmap | KEY_FLAG_CROSS_FALLBACK;
OracleKey memory key_ = _getRegisteredKey();
emit LogCrossFallbackEnabled(key_);
}
/// @notice Disables cross fallback for the registered key (clears `KEY_FLAG_CROSS_FALLBACK`).
/// @dev Only governance.
function disableCrossFallback() external onlyWithTransientOracleKey onlyGovernance onlyForExistingConfig {
OracleKeyConfig storage cfg_ = _getRegisteredConfig();
cfg_.flagsBitmap = cfg_.flagsBitmap & ~KEY_FLAG_CROSS_FALLBACK;
OracleKey memory key_ = _getRegisteredKey();
emit LogCrossFallbackDisabled(key_);
}
}
// ==================== Source Read ====================
/// @dev Implements source reads with a `doRevert_` flag: true = revert on failure, false = return 0.
abstract contract FluidUsdOracleSourceRead is FluidUsdOracleCore, ChainlinkSourceReader, FluidSourceReader {
/// @dev Applies source multiplier so every leg is normalized to ORACLE_PRECISION.
function _applyMultiplier(uint256 rate_, int8 multiplier_) internal pure returns (uint256) {
if (multiplier_ > 0) {
return rate_ * uint256(10 ** uint8(multiplier_));
}
if (multiplier_ < 0) {
unchecked {
return rate_ / uint256(10 ** uint8(-multiplier_));
}
}
return rate_;
}
/// @dev Applies the leg multiplier, then zero-checks per `doRevert_` (division can round small rates to 0).
function _normalizeRate(uint256 rate_, int8 multiplier_, bool doRevert_) internal pure returns (uint256) {
rate_ = _applyMultiplier(rate_, multiplier_);
if (rate_ == 0) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__RateZero);
}
return rate_;
}
/// @dev Applies a per-leg cap: returns min(rate, cap) or max(rate, cap) depending on capDirection_.
/// capOperand_ is in 2-decimal precision (100 = 1.00 = 1e27 in ORACLE_PRECISION).
function _applyLegCap(uint256 rate_, uint16 capOperand_, uint8 capDirection_) internal pure returns (uint256) {
// keep a 0 (failed/stale leg) as the failure sentinel; else SOURCE_CAP_MAX would floor it and mask the failure
if (rate_ == 0) return 0;
if (capOperand_ == 0) return rate_;
uint256 capValue_;
unchecked {
capValue_ = uint256(capOperand_) * CAP_PRECISION;
}
if (capDirection_ == SOURCE_CAP_MIN) {
return rate_ < capValue_ ? rate_ : capValue_;
}
// SOURCE_CAP_MAX
return rate_ > capValue_ ? rate_ : capValue_;
}
/// @dev Applies overall cap to the final price.
/// Cross-path modes use refPrice_ (PEG: other mapping primary; else altSrc).
/// Operand modes compare against overallCapOperand * 1e25.
/// refPrice_ is ignored for non-cross-path modes.
function _applyOverallCap(
uint256 price_,
uint256 refPrice_,
OracleKeyConfig memory keyConfig_
) internal pure returns (uint256) {
uint8 mode_ = keyConfig_.overallCapMode;
if (mode_ == OVERALL_CAP_NONE) {
return price_;
}
if (mode_ == OVERALL_CAP_MIN_CROSS_PATH) {
return price_ < refPrice_ ? price_ : refPrice_;
}
if (mode_ == OVERALL_CAP_MAX_CROSS_PATH) {
return price_ > refPrice_ ? price_ : refPrice_;
}
uint256 capValue_;
unchecked {
capValue_ = uint256(keyConfig_.overallCapOperand) * CAP_PRECISION;
}
if (mode_ == OVERALL_CAP_MIN_OPERAND) {
return price_ < capValue_ ? price_ : capValue_;
}
// OVERALL_CAP_MAX_OPERAND
return price_ > capValue_ ? price_ : capValue_;
}
/// @dev Reads a single configured source and returns its normalized 1e27 rate.
/// When doRevert_ is true, reverts on failure. When false, returns 0 instead.
function _readSource(
uint8 sourceType_,
address source_,
int8 multiplier_,
bool isOperate_,
bool isCollateral_,
bool doRevert_
) internal view returns (uint256 rate_) {
if (sourceType_ == SOURCE_CAPPED_RATE || sourceType_ == SOURCE_FLUID_ORACLE) {
rate_ = _readFluidSource(source_, isOperate_, isCollateral_);
} else if (_isChainlinkStyleSourceType(sourceType_)) {
rate_ = _readChainlink(source_, isOperate_, doRevert_);
} else if (sourceType_ == SOURCE_STABLE) {
rate_ = ORACLE_PRECISION;
} else {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__InvalidSourceType);
}
rate_ = _normalizeRate(rate_, multiplier_, doRevert_);
}
function _readSourceMaybeWrite(
uint8 sourceType_,
address source_,
int8 multiplier_,
PriceReadContext memory ctx_,
bool doRevert_
) internal returns (uint256 rate_) {
if (ctx_.isWrite && (sourceType_ == SOURCE_CAPPED_RATE || sourceType_ == SOURCE_FLUID_ORACLE)) {
return
_normalizeRate(
_readFluidSourceWrite(source_, ctx_.isOperate, ctx_.isCollateral),
multiplier_,
doRevert_
);
}
return _readSource(sourceType_, source_, multiplier_, ctx_.isOperate, ctx_.isCollateral, doRevert_);
}
/// @dev Reads a single source in "raw" mode for getPriceRawForMode. Returns 0 on any failure (never reverts).
/// Capped rate / Fluid oracle sources use the uncapped `getExchangeRate()` getter instead of the directional getExchangeRate* methods,
/// returning the unfiltered price without operate/liquidate/collateral/debt distinction.
/// Chainlink sources use the liquidate (more lenient) staleness timespan since getPriceRawForMode
/// has no isOperate parameter. Returns 0 on stale data instead of reverting.
function _readSourceRaw(
uint8 sourceType_,
address source_,
int8 multiplier_
) internal view returns (uint256 rate_) {
if (sourceType_ == SOURCE_CAPPED_RATE || sourceType_ == SOURCE_FLUID_ORACLE) {
rate_ = _readFluidSourceRaw(source_);
} else if (_isChainlinkStyleSourceType(sourceType_)) {
rate_ = _readChainlinkRaw(source_);
} else if (sourceType_ == SOURCE_STABLE) {
rate_ = ORACLE_PRECISION;
} else {
return 0;
}
if (rate_ != 0) {
rate_ = _applyMultiplier(rate_, multiplier_);
}
}
/// @dev Reads up to 3 sources from a `TokenSources` bucket (non-reverting), returning configs, rates, and composed price.
function _readSourcesWithRates(
TokenSources storage bucket_,
bool isOperate_,
bool isCollateral_
) internal view returns (SourcesWithRates memory result_) {
result_.source1 = SourceConfig(bucket_.sourceType1, bucket_.source1, bucket_.capOperand1);
result_.source2 = SourceConfig(bucket_.sourceType2, bucket_.source2, bucket_.capOperand2);
result_.source3 = SourceConfig(bucket_.sourceType3, bucket_.source3, bucket_.capOperand3);
result_.rate1 = _readSource(
bucket_.sourceType1,
bucket_.source1,
bucket_.multiplier1,
isOperate_,
isCollateral_,
false
);
result_.price = result_.rate1;
if (bucket_.sourceType2 != SOURCE_NOT_SET) {
result_.rate2 = _readSource(
bucket_.sourceType2,
bucket_.source2,
bucket_.multiplier2,
isOperate_,
isCollateral_,
false
);
result_.price = (result_.price * result_.rate2) / ORACLE_PRECISION;
}
if (bucket_.sourceType3 != SOURCE_NOT_SET) {
result_.rate3 = _readSource(
bucket_.sourceType3,
bucket_.source3,
bucket_.multiplier3,
isOperate_,
isCollateral_,
false
);
result_.price = (result_.price * result_.rate3) / ORACLE_PRECISION;
}
}
/// @dev Computes a composed price from a `TokenSources` bucket.
/// Loads slot 2 / 3 only if the prior source type indicates they are configured.
/// When capDirection_ != SOURCE_CAP_NONE, applies per-leg capping using each leg's capOperand.
/// When doRevert_ is true, reverts on any source failure or zero price. When false, returns 0 instead.
function _readComposedPrice(
TokenSources storage bucket_,
PriceReadContext memory ctx_,
bool doRevert_,
uint8 capDirection_
) internal returns (uint256 price_) {
uint8 sourceType2_ = bucket_.sourceType2;
uint8 sourceType3_ = bucket_.sourceType3;
price_ = _readSourceMaybeWrite(bucket_.sourceType1, bucket_.source1, bucket_.multiplier1, ctx_, doRevert_);
if (capDirection_ != SOURCE_CAP_NONE) {
price_ = _applyLegCap(price_, bucket_.capOperand1, capDirection_);
}
if (sourceType2_ == SOURCE_NOT_SET) {
return price_;
}
uint256 rate2_ = _readSourceMaybeWrite(sourceType2_, bucket_.source2, bucket_.multiplier2, ctx_, doRevert_);
if (capDirection_ != SOURCE_CAP_NONE) {
rate2_ = _applyLegCap(rate2_, bucket_.capOperand2, capDirection_);
}
price_ = (price_ * rate2_) / ORACLE_PRECISION;
if (sourceType3_ == SOURCE_NOT_SET) {
if (price_ == 0) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__RateZero);
}
return price_;
}
uint256 rate3_ = _readSourceMaybeWrite(sourceType3_, bucket_.source3, bucket_.multiplier3, ctx_, doRevert_);
if (capDirection_ != SOURCE_CAP_NONE) {
rate3_ = _applyLegCap(rate3_, bucket_.capOperand3, capDirection_);
}
price_ = (price_ * rate3_) / ORACLE_PRECISION;
if (price_ == 0) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__RateZero);
}
}
/// @dev Raw composed price from a `TokenSources` bucket (for `getPriceRawForMode`).
/// Loads slot 2 / 3 only if the prior source type indicates they are configured. Never reverts.
function _readComposedPriceRaw(TokenSources storage bucket_) internal view returns (uint256 priceRaw_) {
uint8 sourceType2_ = bucket_.sourceType2;
uint8 sourceType3_ = bucket_.sourceType3;
priceRaw_ = _readSourceRaw(bucket_.sourceType1, bucket_.source1, bucket_.multiplier1);
if (sourceType2_ == SOURCE_NOT_SET) {
return priceRaw_;
}
uint256 rate2_ = _readSourceRaw(sourceType2_, bucket_.source2, bucket_.multiplier2);
priceRaw_ = (priceRaw_ * rate2_) / ORACLE_PRECISION;
if (sourceType3_ == SOURCE_NOT_SET) {
return priceRaw_;
}
uint256 rate3_ = _readSourceRaw(sourceType3_, bucket_.source3, bucket_.multiplier3);
priceRaw_ = (priceRaw_ * rate3_) / ORACLE_PRECISION;
}
}
// ==================== Alt Price Read (deviation/fallback) ====================
/// @dev Handles alt-source flow: deviation check and/or fallback.
abstract contract FluidUsdOracleAltPriceRead is FluidUsdOracleSourceRead {
/// @dev Reads the reference chain; with `useAlt_` a `0` falls through to that mapping's alt. `doRevert_`
/// applies to the last attempt only, so the caller's fail-closed / soft semantics are preserved.
function _readReference(
TokenSources storage refCfg_,
TokenSources storage refAltCfg_,
bool useAlt_,
PriceReadContext memory ctx_,
bool doRevert_,
uint8 capDirection_
) internal returns (uint256 price_) {
if (!useAlt_) {
return _readComposedPrice(refCfg_, ctx_, doRevert_, capDirection_);
}
price_ = _readComposedPrice(refCfg_, ctx_, false, capDirection_);
if (price_ == 0) {
price_ = _readComposedPrice(refAltCfg_, ctx_, doRevert_, capDirection_);
}
}
/// @dev Reads primary price (non-reverting), then resolves fallback, deviation, and overall cap.
/// For non-PEG: fallbackAltCfg_ and deviationCfg_ both point to altSrc.
/// For PEG: fallbackAltCfg_ is the selected mapping's altSrc; deviationCfg_ crosses mappings
/// (and doubles as the cross-path reference for overall cap).
/// The reference price is read at most once, reused for deviation check and cross-path cap.
/// `deviationVsPeg_` (STABLE tokens) makes the deviation check compare against the constant $1
/// instead of the alt, so a market depeg is caught even when the alt is another feed. With a
/// CROSS_PATH cap the alt is checked against $1 too, so neither feed can carry the key off the peg.
/// CROSS_PATH operate fail-closes (`doRevert_=true`). CROSS_PATH liquidate reads the ref soft and
/// skips the cap when it is `0`, and conversely returns the ref once primary and alt have both
/// failed, so neither path dying alone can halt liquidations. Only the stand-in direction requires
/// `KEY_FLAG_FALLBACK`; the cap skip applies to every liquidate CROSS_PATH key.
/// Every reference read goes through `_readReference`, so with `KEY_FLAG_CROSS_FALLBACK` the
/// reference chain's own alt is reachable from the deviation check, the cap and the stand-in alike.
function _getPriceWithAlt(
TokenSources storage primaryCfg_,
TokenSources storage fallbackAltCfg_,
bool hasFallbackAlt_,
TokenSources storage deviationCfg_,
TokenSources storage deviationAltCfg_,
bool useDeviationAlt_,
OracleKeyConfig memory keyConfig_,
PriceReadContext memory ctx_,
bool deviationVsPeg_
) internal returns (uint256 price_) {
price_ = _readComposedPrice(primaryCfg_, ctx_, false, keyConfig_.sourceCapMode);
bool isCrossPath_ = _isCrossPath(keyConfig_.overallCapMode);
if (price_ == 0) {
if (ctx_.isOperate && keyConfig_.maxDeviationBPS > 0) {
_revert(ErrorTypes.UsdOracle__RateZero);
}
if (keyConfig_.flagsBitmap & KEY_FLAG_FALLBACK == 0) {
_revert(ErrorTypes.UsdOracle__RateZero);
}
// Enabling fallback is the opt-in for substituting a chain at all. The alt is the closer
// substitute, so the CROSS_PATH ref only stands in once the alt is unavailable or dead too.
bool refStandIn_ = !ctx_.isOperate && isCrossPath_;
if (!hasFallbackAlt_) {
if (!refStandIn_) _revert(ErrorTypes.UsdOracle__AltSourceNotConfigured);
} else {
price_ = _readComposedPrice(fallbackAltCfg_, ctx_, !refStandIn_, keyConfig_.sourceCapMode);
}
// only reachable with `refStandIn_`: a strict `_readComposedPrice` never returns 0, so operate stops above
if (price_ == 0) {
return
_readReference(
deviationCfg_,
deviationAltCfg_,
useDeviationAlt_,
ctx_,
true,
keyConfig_.sourceCapMode
);
}
}
uint256 refPrice_;
if (ctx_.isOperate && keyConfig_.maxDeviationBPS > 0) {
// STABLE deviation is against $1; the composed ref is read only if a cross-path cap needs it
uint256 deviationRef_ = ORACLE_PRECISION;
if (!deviationVsPeg_ || isCrossPath_) {
refPrice_ = _readReference(
deviationCfg_,
deviationAltCfg_,
useDeviationAlt_,
ctx_,
true,
keyConfig_.sourceCapMode
);
if (!deviationVsPeg_) deviationRef_ = refPrice_;
}
_revertIfAboveMaxDeviation(price_, deviationRef_, keyConfig_.maxDeviationBPS);
// on STABLE the alt is not the deviation reference but still feeds the CROSS_PATH cap
if (deviationVsPeg_ && isCrossPath_) {
_revertIfAboveMaxDeviation(refPrice_, deviationRef_, keyConfig_.maxDeviationBPS);
}
} else if (isCrossPath_) {
// Operate fail-closes. Liquidate must still price off primary if the other path is dead —
// never `min(price, 0)`.
refPrice_ = _readReference(
deviationCfg_,
deviationAltCfg_,
useDeviationAlt_,
ctx_,
ctx_.isOperate,
keyConfig_.sourceCapMode
);
if (refPrice_ == 0) {
return price_;
}
}
return _applyOverallCap(price_, refPrice_, keyConfig_);
}
function _revertIfAboveMaxDeviation(uint256 price_, uint256 ref_, uint256 maxDeviationBPS_) private pure {
uint256 diff_;
unchecked {
diff_ = price_ > ref_ ? price_ - ref_ : ref_ - price_;
}
if ((diff_ * BPS_DENOMINATOR) / price_ > maxDeviationBPS_) {
_revert(ErrorTypes.UsdOracle__MaxDeviation);
}
}
/// @dev Resolves price from the non-PEG source config storage reference.
/// Non-PEG: deviation and fallback both use altSrc.
/// Applies per-leg caps via sourceCapMode and overall cap if configured.
function _getResolvedPrice(
TokenSourceConfig storage srcCfg_,
TokenMetadata memory meta_,
OracleKeyConfig memory keyConfig_,
PriceReadContext memory ctx_
) internal returns (uint256 price_) {
uint8 capDirection_ = keyConfig_.sourceCapMode;
bool hasAlt_ = meta_.flagsBitmap & FLAG_HAS_ALT_SOURCE != 0;
if (
hasAlt_ ||
keyConfig_.maxDeviationBPS > 0 ||
keyConfig_.flagsBitmap & KEY_FLAG_FALLBACK != 0 ||
_isCrossPath(keyConfig_.overallCapMode)
) {
return
_getPriceWithAlt(
srcCfg_.primarySrc,
srcCfg_.altSrc,
hasAlt_,
srcCfg_.altSrc,
srcCfg_.altSrc,
false,
keyConfig_,
ctx_,
meta_.tokenType == TOKEN_TYPE_STABLE
);
}
price_ = _readComposedPrice(srcCfg_.primarySrc, ctx_, true, capDirection_);
return _applyOverallCap(price_, 0, keyConfig_);
}
/// @dev PEG-token resolved price:
/// - deviation compares `_tokenSources.primarySrc` vs `_additionalTokenSources.primarySrc`
/// - fallback remains within the selected mapping and uses that mapping's alt sources
/// - per-leg caps, deviation, and overall cap (cross-path or operand) handled by _getPriceWithAlt
function _getPegResolvedPrice(
address token_,
TokenSourceConfig storage tokenCfg_,
TokenMetadata memory meta_,
OracleKeyConfig memory keyConfig_,
PriceReadContext memory ctx_
) internal returns (uint256 price_) {
TokenSources storage primaryCfg_;
TokenSources storage altBucket_;
TokenSources storage deviationRef_;
TokenSources storage deviationRefAlt_;
bool hasFallbackAlt_;
if (keyConfig_.priceMode == PRICE_MODE_MARKET) {
// market price is in additional sources
primaryCfg_ = _additionalTokenSources[token_].primarySrc;
hasFallbackAlt_ = meta_.flagsBitmap & FLAG_HAS_ADDITIONAL_ALT_SOURCES != 0;
altBucket_ = _additionalTokenSources[token_].altSrc;
deviationRef_ = tokenCfg_.primarySrc;
deviationRefAlt_ = tokenCfg_.altSrc;
} else {
// peg price is in primary sources
primaryCfg_ = tokenCfg_.primarySrc;
hasFallbackAlt_ = meta_.flagsBitmap & FLAG_HAS_ALT_SOURCE != 0;
altBucket_ = tokenCfg_.altSrc;
deviationRef_ = _additionalTokenSources[token_].primarySrc;
deviationRefAlt_ = _additionalTokenSources[token_].altSrc;
}
if (
!hasFallbackAlt_ &&
keyConfig_.maxDeviationBPS == 0 &&
keyConfig_.flagsBitmap & KEY_FLAG_FALLBACK == 0 &&
!_isCrossPath(keyConfig_.overallCapMode)
) {
price_ = _readComposedPrice(primaryCfg_, ctx_, true, keyConfig_.sourceCapMode);
return _applyOverallCap(price_, 0, keyConfig_);
}
return
_getPriceWithAlt(
primaryCfg_,
altBucket_,
hasFallbackAlt_,
deviationRef_,
deviationRefAlt_,
keyConfig_.flagsBitmap & KEY_FLAG_CROSS_FALLBACK != 0 &&
meta_.flagsBitmap &
(
keyConfig_.priceMode == PRICE_MODE_MARKET
? FLAG_HAS_ALT_SOURCE
: FLAG_HAS_ADDITIONAL_ALT_SOURCES
) !=
0,
keyConfig_,
ctx_,
false
);
}
}
// ==================== Views ====================
/// @dev All public view / query methods: getPrice, getPriceRawForMode, getPriceDetailed, getConfiguredTokenOracles, etc.
abstract contract FluidUsdOracleViews is IUSDOracle, FluidUsdOracleAltPriceRead, TokenSymbolResolver {
/// @dev Guard hook for price reads; L2 overrides with the sequencer gate. Raw/impl entries skip it on purpose.
function _beforeGuardedPriceRead() internal view virtual {}
/// @inheritdoc IUSDOracle
function isGuardian(address addr_) external view override returns (bool) {
return _guardians[addr_] == 1;
}
/// @inheritdoc IUSDOracle
function getTokenConfig(
address token_
) external view override returns (bool operatePaused_, bool liquidatePaused_, uint8 tokenType_, uint8 decimals_) {
TokenSourceConfig storage cfg_ = _tokenSources[token_];
operatePaused_ = cfg_.primarySrc.pauseState & PAUSED_OPERATE != 0;
liquidatePaused_ = cfg_.primarySrc.pauseState & PAUSED_LIQUIDATE != 0;
tokenType_ = cfg_.primarySrc.tokenType;
decimals_ = cfg_.primarySrc.decimals;
}
/// @inheritdoc IUSDOracle
function isTokenConfigGovernanceApproved(address token_) external view override returns (bool) {
return _tokenSources[token_].primarySrc.flagsBitmap & FLAG_GOVERNANCE_APPROVED != 0;
}
/// @inheritdoc IUSDOracle
function isEmodeValid(uint256 emode_, address token_) external view override returns (bool) {
return _tokenHasEmodeInConfigsMap(token_, emode_);
}
/// @inheritdoc IUSDOracle
/// @dev Runs the tree in Write mode: Fluid/capped legs use `IFluidOracleWrite` getters. Reads should use `getPriceView`.
function getPrice(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public virtual override returns (uint256 price_) {
_beforeGuardedPriceRead();
return _getPriceImpl(token_, emode_, isOperate_, isCollateral_, true);
}
/// @inheritdoc IUSDOracle
function getPriceView(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public view virtual override returns (uint256 price_) {
_beforeGuardedPriceRead();
return _getPriceImplStatic(token_, emode_, isOperate_, isCollateral_);
}
/// @inheritdoc IUSDOracle
function getPriceDetailed(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public virtual override returns (uint256 price_, uint8 decimals_, uint8 tokenType_) {
price_ = getPrice(token_, emode_, isOperate_, isCollateral_);
(decimals_, tokenType_) = _getMetadata(token_);
}
/// @inheritdoc IUSDOracle
function getPriceDetailedView(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public view virtual override returns (uint256 price_, uint8 decimals_, uint8 tokenType_) {
price_ = getPriceView(token_, emode_, isOperate_, isCollateral_);
(decimals_, tokenType_) = _getMetadata(token_);
}
/// @inheritdoc IUSDOracle
/// @dev Resolver read path: intentionally not behind `_beforeGuardedPriceRead` (e.g. skips the L2 sequencer gate).
function getPriceDetailedViewRaw(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public view virtual override returns (uint256 price_, uint8 decimals_, uint8 tokenType_) {
price_ = _getPriceImplStatic(token_, emode_, isOperate_, isCollateral_);
(decimals_, tokenType_) = _getMetadata(token_);
}
/// @inheritdoc IUSDOracle
function getPriceRawForMode(
address token_,
uint8 priceMode_
) public view virtual override returns (uint256 priceRaw_, uint8 decimals_, uint8 tokenType_) {
_beforeGuardedPriceRead();
return _priceRawForMode(token_, priceMode_);
}
/// @inheritdoc IUSDOracle
function getPricesRawForMode(
address[] calldata tokens_,
uint8[] calldata priceModes_
)
public
view
virtual
override
returns (uint256[] memory pricesRaw_, uint8[] memory decimals_, uint8[] memory tokenTypes_)
{
_beforeGuardedPriceRead(); // once for the whole batch
uint256 len_ = tokens_.length;
if (priceModes_.length != len_) {
_revert(ErrorTypes.UsdOracle__InvalidParams);
}
pricesRaw_ = new uint256[](len_);
decimals_ = new uint8[](len_);
tokenTypes_ = new uint8[](len_);
for (uint256 i = 0; i < len_; ++i) {
(pricesRaw_[i], decimals_[i], tokenTypes_[i]) = _priceRawForMode(tokens_[i], priceModes_[i]);
}
}
/// @dev Unguarded body shared by the single and batch getters.
function _priceRawForMode(
address token_,
uint8 priceMode_
) internal view returns (uint256 priceRaw_, uint8 decimals_, uint8 tokenType_) {
if (priceMode_ == PRICE_MODE_NOT_SET) {
return (0, 0, 0);
}
TokenSourceConfig storage tokenCfg_ = _tokenSources[token_];
TokenMetadata memory meta_ = _metadata(tokenCfg_);
tokenType_ = meta_.tokenType;
decimals_ = meta_.decimals;
if (tokenType_ == TOKEN_TYPE_NOT_SET) {
return (0, 0, 0);
}
if (priceMode_ == PRICE_MODE_PEG) {
if (tokenType_ == TOKEN_TYPE_STABLE) {
return (ORACLE_PRECISION, decimals_, tokenType_);
}
if (tokenType_ != TOKEN_TYPE_PEG) {
return (0, decimals_, tokenType_);
}
}
TokenSources storage primaryCfg_;
TokenSources storage fallbackAltCfg_;
bool hasFallbackAlt_;
if (tokenType_ == TOKEN_TYPE_PEG && priceMode_ == PRICE_MODE_MARKET) {
if (meta_.flagsBitmap & FLAG_HAS_ADDITIONAL_SOURCES == 0) {
return (0, decimals_, tokenType_);
}
primaryCfg_ = _additionalTokenSources[token_].primarySrc;
fallbackAltCfg_ = _additionalTokenSources[token_].altSrc;
hasFallbackAlt_ = meta_.flagsBitmap & FLAG_HAS_ADDITIONAL_ALT_SOURCES != 0;
} else {
primaryCfg_ = tokenCfg_.primarySrc;
fallbackAltCfg_ = tokenCfg_.altSrc;
hasFallbackAlt_ = meta_.flagsBitmap & FLAG_HAS_ALT_SOURCE != 0;
}
if (primaryCfg_.sourceType1 == SOURCE_NOT_SET) {
return (0, decimals_, tokenType_);
}
priceRaw_ = _readComposedPriceRaw(primaryCfg_);
if (priceRaw_ == 0 && hasFallbackAlt_) {
priceRaw_ = _readComposedPriceRaw(fallbackAltCfg_);
}
}
// --- Internal methods ---
/// @dev Enforces pause bits, resolves key config (eMode fallback to 0), then PEG vs non-PEG price resolution.
function _getPriceImpl(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_,
bool isWrite_
) internal returns (uint256 price_) {
TokenSourceConfig storage tokenCfg_ = _tokenSources[token_];
TokenMetadata memory meta_ = _metadata(tokenCfg_);
uint8 pauseState_ = meta_.pauseState;
if (isOperate_) {
if (pauseState_ & PAUSED_OPERATE != 0) {
_revert(ErrorTypes.UsdOracle__TokenPaused);
}
} else {
if (pauseState_ & PAUSED_LIQUIDATE != 0) {
_revert(ErrorTypes.UsdOracle__TokenPaused);
}
}
uint256 isOp_ = isOperate_ ? 1 : 0;
uint256 isCol_ = isCollateral_ ? 1 : 0;
// Load key config for emode_, falling back to eMode 0 if unset.
OracleKeyConfig memory keyConfig_ = _configs[_keyHash(token_, emode_, isOp_, isCol_)];
if (keyConfig_.priceMode == PRICE_MODE_NOT_SET) {
keyConfig_ = _configs[_keyHash(token_, 0, isOp_, isCol_)];
}
if (keyConfig_.priceMode == PRICE_MODE_NOT_SET) {
_revert(ErrorTypes.UsdOracle__NoConfig);
}
uint8 tokenType_ = meta_.tokenType;
// STABLE + PEG: constant $1, cheapest path (2 SLOADs, no caps — peg is exactly $1).
if (_isStablePeg(tokenType_, keyConfig_.priceMode)) {
return ORACLE_PRECISION;
}
PriceReadContext memory ctx_ = PriceReadContext({
isOperate: isOperate_,
isCollateral: isCollateral_,
isWrite: isWrite_
});
if (tokenType_ == TOKEN_TYPE_PEG) {
return _getPegResolvedPrice(token_, tokenCfg_, meta_, keyConfig_, ctx_);
}
return _getResolvedPrice(tokenCfg_, meta_, keyConfig_, ctx_);
}
/// @dev View entry helper: staticcall `_getPriceImplNoWrite` so one non-view price tree serves Write and view.
function _getPriceImplStatic(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) internal view returns (uint256 price_) {
(bool success_, bytes memory data_) = address(this).staticcall(
abi.encodeCall(this._getPriceImplNoWrite, (token_, emode_, isOperate_, isCollateral_))
);
if (!success_) {
assembly {
revert(add(data_, 0x20), mload(data_))
}
}
price_ = abi.decode(data_, (uint256));
}
/// @dev Self-staticcall target for `_getPriceImplStatic` (Write mode off); public only for the bridge, self-call gated.
function _getPriceImplNoWrite(
address token_,
uint256 emode_,
bool isOperate_,
bool isCollateral_
) public virtual returns (uint256 price_) {
if (msg.sender != address(this)) {
_revert(ErrorTypes.UsdOracle__OnlySelf);
}
return _getPriceImpl(token_, emode_, isOperate_, isCollateral_, false);
}
/// @dev Copies packed token metadata from `_tokenSources[token].primarySrc` storage slot 0.
function _metadata(TokenSourceConfig storage tokenCfg_) internal view returns (TokenMetadata memory meta_) {
meta_ = TokenMetadata({
pauseState: tokenCfg_.primarySrc.pauseState,
tokenType: tokenCfg_.primarySrc.tokenType,
decimals: tokenCfg_.primarySrc.decimals,
flagsBitmap: tokenCfg_.primarySrc.flagsBitmap
});
}
/// @dev Reads listing metadata from `_tokenSources[token_].primarySrc`.
function _getMetadata(address token_) internal view returns (uint8 decimals_, uint8 tokenType_) {
TokenSourceConfig storage tokenCfg_ = _tokenSources[token_];
decimals_ = tokenCfg_.primarySrc.decimals;
tokenType_ = tokenCfg_.primarySrc.tokenType;
}
}
// ==================== Final Contract ====================
/// @title FluidUsdOracle
/// @notice Core USD oracle: token-level sources, per-key modes/caps, and `getPrice` in `ORACLE_PRECISION` (1e27) USD units.
contract FluidUsdOracle is FluidUsdOracleKeyConfigs, FluidUsdOracleViews {
/// @notice Deploys the oracle with the Liquidity contract used to resolve governance.
/// @param liquidity_ Liquidity proxy address (governance read via `LIQUIDITY_GOVERNANCE_SLOT`).
/// @param mainViews_ `FluidUsdOracleMainViews`, deployed first; must be built from this same source.
constructor(address liquidity_, address mainViews_) validAddress(liquidity_) validAddress(mainViews_) {
LIQUIDITY = liquidity_;
MAIN_VIEWS = mainViews_;
(bool success_, bytes memory data_) = mainViews_.staticcall(abi.encodeWithSignature("layoutVersion()"));
if (!success_ || data_.length != 32 || abi.decode(data_, (uint256)) != MAIN_VIEWS_LAYOUT_VERSION) {
_revert(ErrorTypes.UsdOracle__MainViewsLayoutMismatch);
}
}
/// @inheritdoc IUSDOracle
/// @dev Body lives on `MAIN_VIEWS` to stay under EIP-170. The self-staticcall is what lets a
/// `view` reach a delegatecall at all, and what pins `MAIN_VIEWS` read-only.
function getConfiguredTokenOracles(address) external view override returns (ConfiguredTokenOracle[] memory) {
(bool success_, ) = address(this).staticcall(abi.encodeWithSelector(this.delegateMainViews.selector, msg.data));
_passThroughReturndata(success_);
}
/// @notice Delegatecalls `MAIN_VIEWS` with `data_`. Callable only by this contract.
/// @dev Read-only rests entirely on the caller's staticcall frame.
function delegateMainViews(bytes calldata data_) external {
if (msg.sender != address(this)) {
_revert(ErrorTypes.UsdOracle__OnlySelf);
}
if (bytes4(data_) != this.getConfiguredTokenOracles.selector) {
_revert(ErrorTypes.UsdOracle__InvalidMainViewsCall);
}
(bool success_, ) = MAIN_VIEWS.delegatecall(data_);
_passThroughReturndata(success_);
}
/// @dev Ends the call. Passes returndata through rather than decoding it: an ABI round-trip for
/// `ConfiguredTokenOracle[]` costs ~1,100 B, more than the split saves. Clobbering memory from 0
/// is safe only because execution stops here.
function _passThroughReturndata(bool success_) internal pure {
assembly {
returndatacopy(0, 0, returndatasize())
switch success_
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
}
contracts/oracleV2/usdOracle/sourceReaders/chainlinkSourceReader.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { IChainlinkAggregatorV3 } from "../../interfaces/external/IChainlinkAggregatorV3.sol";
import { Error } from "../error.sol";
import { ErrorTypes } from "../errorTypes.sol";
import { Variables } from "../variables.sol";
abstract contract ChainlinkSourceReader is Variables, Error {
/// @dev Reads the latest price from a Chainlink aggregator (staleness + sign checks).
/// When doRevert_ is true, reverts on stale/invalid data. When false, returns 0 instead.
function _readChainlink(address feed_, bool isOperate_, bool doRevert_) internal view returns (uint256 rate_) {
int256 exchangeRate_;
uint256 updatedAt_;
try IChainlinkAggregatorV3(feed_).latestRoundData() returns (
uint80,
int256 exchangeRateResult_,
uint256,
uint256 updatedAtResult_,
uint80
) {
exchangeRate_ = exchangeRateResult_;
updatedAt_ = updatedAtResult_;
} catch {}
if (updatedAt_ == 0) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__RateInvalid);
}
if (isOperate_) {
if (updatedAt_ + MAX_UPDATE_TIMESPAN_OPERATE < block.timestamp) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__ChainlinkStale);
}
} else if (updatedAt_ + MAX_UPDATE_TIMESPAN_LIQUIDATE < block.timestamp) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__ChainlinkStale);
}
if (exchangeRate_ < 0) {
if (!doRevert_) return 0;
_revert(ErrorTypes.UsdOracle__RateInvalid);
}
rate_ = uint256(exchangeRate_);
}
/// @dev Raw Chainlink read: liquidate timespan only, returns 0 on failure/stale/non-positive (no revert).
function _readChainlinkRaw(address feed_) internal view returns (uint256 rate_) {
int256 exchangeRate_;
uint256 updatedAt_;
try IChainlinkAggregatorV3(feed_).latestRoundData() returns (
uint80,
int256 exchangeRateResult_,
uint256,
uint256 updatedAtResult_,
uint80
) {
exchangeRate_ = exchangeRateResult_;
updatedAt_ = updatedAtResult_;
} catch {
return 0;
}
if (updatedAt_ == 0 || updatedAt_ + MAX_UPDATE_TIMESPAN_LIQUIDATE < block.timestamp || exchangeRate_ <= 0) {
return 0;
}
rate_ = uint256(exchangeRate_);
}
}
contracts/oracleV2/usdOracle/sourceReaders/fluidSourceReader.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { IFluidOracleWithDebt } from "../../interfaces/iFluidOracleWithDebt.sol";
import { IFluidOracleWrite } from "../../interfaces/iFluidOracleWrite.sol";
/// @dev Shared directional read path for `SOURCE_CAPPED_RATE` and `SOURCE_FLUID_ORACLE`
/// (same getters; capped-rate also requires `centerPrice()` at config time only).
abstract contract FluidSourceReader {
/// @dev Reads the latest exchange rate from a Fluid oracle / capped rate (directional getters). Returns 0 on call failure.
function _readFluidSource(
address oracle_,
bool isOperate_,
bool isCollateral_
) internal view returns (uint256 rate_) {
if (isOperate_) {
if (isCollateral_) {
try IFluidOracleWithDebt(oracle_).getExchangeRateOperate() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
} else {
try IFluidOracleWithDebt(oracle_).getExchangeRateOperateDebt() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
}
} else {
if (isCollateral_) {
try IFluidOracleWithDebt(oracle_).getExchangeRateLiquidate() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
} else {
try IFluidOracleWithDebt(oracle_).getExchangeRateLiquidateDebt() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
}
}
}
/// @dev Raw read via `getExchangeRate()` (uncapped, no directional distinction).
function _readFluidSourceRaw(address oracle_) internal view returns (uint256 rate_) {
try IFluidOracleWithDebt(oracle_).getExchangeRate() returns (uint256 price_) {
rate_ = price_;
} catch {}
}
/// @dev Like `_readFluidSource`, but tries the direction's Write getter first (e.g. CLX cache warm).
/// Any Write failure falls back to the view getter, keeping per-leg failure isolation.
function _readFluidSourceWrite(
address oracle_,
bool isOperate_,
bool isCollateral_
) internal returns (uint256 rate_) {
if (isOperate_) {
if (isCollateral_) {
try IFluidOracleWrite(oracle_).getExchangeRateOperateWrite() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
} else {
try IFluidOracleWrite(oracle_).getExchangeRateOperateDebtWrite() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
}
} else {
if (isCollateral_) {
try IFluidOracleWrite(oracle_).getExchangeRateLiquidateWrite() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
} else {
try IFluidOracleWrite(oracle_).getExchangeRateLiquidateDebtWrite() returns (uint256 exchangeRate_) {
return exchangeRate_;
} catch {}
}
}
return _readFluidSource(oracle_, isOperate_, isCollateral_);
}
}
contracts/oracleV2/usdOracle/structs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
abstract contract StorageStructs {
struct TokenSources {
// ---------- storage slot 0 ----------
address source1; // 160 -- primary source 1 address
int8 multiplier1; // 8 -- decimals multiplier: positive = multiply, negative = divide, to get to 1e27
uint8 sourceType1; // 8 -- source type (see SOURCE_* constants)
uint8 sourceType2; // 8 -- stored in slot 0 to avoid loading slot 1 just to check existence
uint8 sourceType3; // 8 -- stored in slot 0 to avoid loading slot 2 just to check existence
uint16 capOperand1; // 16 -- cap bound for leg 1 in 2-decimal precision (100 = 1.00). 0 = no cap.
// -------------------------------------
// Metadata (only meaningful on `_tokenSources.primarySrc`; zero on alt/additional buckets).
uint8 pauseState; // 8 -- bit 0 = operate paused, bit 1 = liquidate paused
uint8 tokenType; // 8 -- 0 = not listed, 1 = PEG, 2 = STABLE, 3 = VOLATILE
uint8 decimals; // 8 -- IERC20.decimals() or 18 for native token
/// @dev Stored and read only on `_tokenSources`, never on `_additionalTokenSources`.
/// Some bits describe whether corresponding configs exist in `_additionalTokenSources`.
/// bit 0 (FLAG_HAS_ALT_SOURCE): alt sources exist in this mapping (storage slots 3-5 / `altSrc`)
/// bit 1 (FLAG_HAS_ADDITIONAL_SOURCES): _additionalTokenSources has primary sources
/// bit 2 (FLAG_HAS_ADDITIONAL_ALT_SOURCES): _additionalTokenSources has alt sources
/// bit 3 (FLAG_GOVERNANCE_APPROVED): token-level sources approved by governance for downstream
/// policy (e.g. borrow limits) and MS eMode≠0 shadow-create freeze vs existing eMode-0 legs
uint8 flagsBitmap; // 8
// -------------------------------------
uint16 __placeholder1; // 16 -- future slot 0 expansion
// ---------- storage slot 1 ----------
int8 multiplier2;
address source2;
uint16 capOperand2; // 16 -- cap bound for leg 2
uint72 __placeholder2;
// ---------- storage slot 2 ----------
int8 multiplier3;
address source3;
uint16 capOperand3; // 16 -- cap bound for leg 3
uint72 __placeholder3;
}
/// @dev Token-level source configuration using reusable three-source storage buckets.
/// `_tokenSources.primarySrc` packs metadata into storage slot 0 of the mapping value.
/// `_additionalTokenSources` and `altSrc` reuse the same shape but ignore metadata bytes.
/// Full `_tokenSources[token]` layout: slots 0-2 = `primarySrc`, slots 3-5 = `altSrc`.
struct TokenSourceConfig {
TokenSources primarySrc;
TokenSources altSrc;
}
/// @dev Per-(token, eMode, isOperate, isCollateral) key configuration. Fits in 1 storage slot.
/// Intentionally slim: only stores a priceMode reference (which token-level source mapping
/// to read) plus key-specific parameters. Source feeds are configured per-token once and
/// shared by all keys for that token+mode — avoiding redundant feed storage and verification.
struct OracleKeyConfig {
uint8 priceMode; // PRICE_MODE_MARKET or PRICE_MODE_PEG
uint8 sourceCapMode; // SOURCE_CAP_NONE / SOURCE_CAP_MIN / SOURCE_CAP_MAX
uint8 overallCapMode; // OVERALL_CAP_NONE / MIN_CROSS_PATH / MAX_CROSS_PATH / MIN_OPERAND / MAX_OPERAND
uint16 overallCapOperand; // 2-decimal precision bound for *_OPERAND modes (100 = 1.00). 0 for cross-path/none.
uint24 maxDeviationBPS; // max deviation in basis points (100 = 1%). 0 = disabled.
uint8 flagsBitmap; // bit 0: KEY_FLAG_FALLBACK, bit 1: KEY_FLAG_CROSS_FALLBACK
}
struct ConfigMap {
uint240 eMode;
bool isOperate;
bool isCollateral;
}
}
abstract contract MemoryStructs {
struct SourceConfig {
uint8 sourceType;
address source;
uint16 capOperand; // cap bound in 2-decimal precision (100 = 1.00). 0 = no cap for this leg.
}
/// @dev Read context threaded through the price tree as one memory pointer (avoids stack-too-deep).
/// `isWrite` selects `_readFluidSourceWrite` at Fluid/capped leaves.
struct PriceReadContext {
bool isOperate;
bool isCollateral;
bool isWrite;
}
struct OracleKey {
address token;
uint256 eMode;
uint8 isOperate; // 0 = liquidate, 1 = operate
uint8 isCollateral; // 0 = debt, 1 = collateral
}
}
abstract contract ViewStructs {
struct TokenMetadata {
uint8 pauseState;
uint8 tokenType;
uint8 decimals;
uint8 flagsBitmap;
}
struct SourcesWithRates {
MemoryStructs.SourceConfig source1;
MemoryStructs.SourceConfig source2;
MemoryStructs.SourceConfig source3;
uint256 rate1;
uint256 rate2;
uint256 rate3;
uint256 price;
}
struct ConfiguredTokenOracle {
address token;
string symbol;
uint256 eMode;
bool isOperate;
bool isCollateral;
uint8 priceMode;
SourcesWithRates primary;
SourcesWithRates alt;
/// @dev `_additionalTokenSources` (market price for PEG tokens). Zero when unset.
SourcesWithRates additionalPrimary;
SourcesWithRates additionalAlt;
uint8 sourceCapMode;
uint8 overallCapMode;
uint16 overallCapOperand;
uint24 maxDeviationBPS;
bool isFallback;
bool isCrossFallback;
bool governanceApproved;
}
}
abstract contract Structs is ViewStructs, StorageStructs, MemoryStructs {}
contracts/oracleV2/usdOracle/variables.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.36;
import { Structs } from "./structs.sol";
abstract contract SourceTypes {
uint8 internal constant SOURCE_NOT_SET = 0;
uint8 internal constant SOURCE_CAPPED_RATE = 1;
uint8 internal constant SOURCE_CHAINLINK = 2;
uint8 internal constant SOURCE_STABLE = 3; // constant $1 price, no external source needed
uint8 internal constant SOURCE_REDSTONE = 4; // Chainlink-compatible aggregator same read path as SOURCE_CHAINLINK
/// @dev Fluid oracle with debt getters (`IFluidOracleWithDebt`), e.g. CLX stock oracles. No `centerPrice()`.
uint8 internal constant SOURCE_FLUID_ORACLE = 5;
}
abstract contract PriceModes {
uint8 internal constant PRICE_MODE_NOT_SET = 0;
uint8 internal constant PRICE_MODE_MARKET = 1;
uint8 internal constant PRICE_MODE_PEG = 2;
}
abstract contract TokenTypes {
/// @dev Default before `setTokenType`; token is not listed.
uint8 internal constant TOKEN_TYPE_NOT_SET = 0;
uint8 internal constant TOKEN_TYPE_PEG = 1;
uint8 internal constant TOKEN_TYPE_STABLE = 2;
uint8 internal constant TOKEN_TYPE_VOLATILE = 3;
}
abstract contract SourceCapModes {
uint8 internal constant SOURCE_CAP_NONE = 0;
uint8 internal constant SOURCE_CAP_MIN = 1; // min(rate, capOperand)
uint8 internal constant SOURCE_CAP_MAX = 2; // max(rate, capOperand)
}
abstract contract OverallCapModes {
uint8 internal constant OVERALL_CAP_NONE = 0;
uint8 internal constant OVERALL_CAP_MIN_CROSS_PATH = 1; // min(price, ref). PEG: other mapping; else altSrc.
uint8 internal constant OVERALL_CAP_MAX_CROSS_PATH = 2; // max(price, ref). PEG: other mapping; else altSrc.
uint8 internal constant OVERALL_CAP_MIN_OPERAND = 3; // min(price, overallCapOperand * 1e25)
uint8 internal constant OVERALL_CAP_MAX_OPERAND = 4; // max(price, overallCapOperand * 1e25)
}
abstract contract TokenFlagsBitmap {
/// @dev flagsBitmap bits for `TokenSourceConfig` metadata.
/// These flags allow the read path to skip SLOADs for mappings that have no data.
uint8 internal constant FLAG_HAS_ALT_SOURCE = 1; // bit 0: alt sources exist in _tokenSources
uint8 internal constant FLAG_HAS_ADDITIONAL_SOURCES = 2; // bit 1: _additionalTokenSources has primary sources
uint8 internal constant FLAG_HAS_ADDITIONAL_ALT_SOURCES = 4; // bit 2: _additionalTokenSources has alt sources
uint8 internal constant FLAG_GOVERNANCE_APPROVED = 8; // bit 3: gov-approved token sources (+ MS eMode shadow-create freeze); setTokenConfigGovernanceApproved
}
abstract contract OracleKeyFlagsBitmap {
/// @dev flagsBitmap bits for OracleKeyConfig
uint8 internal constant KEY_FLAG_FALLBACK = 1; // bit 0: fallback enabled
uint8 internal constant KEY_FLAG_CROSS_FALLBACK = 2; // bit 1: cross mapping may fall back to its own alt
}
abstract contract Constants is
SourceTypes,
PriceModes,
TokenTypes,
SourceCapModes,
OverallCapModes,
TokenFlagsBitmap,
OracleKeyFlagsBitmap
{
uint8 internal constant PAUSED_OPERATE = 1; // bit 0: operate calls paused
uint8 internal constant PAUSED_LIQUIDATE = 2; // bit 1: liquidate calls paused
int8 internal constant MAX_MULTIPLIER = 21; // a source rate with less than 6 decimals precision is not known to exist
int8 internal constant MIN_MULTIPLIER = -12; // a source rate with more than 39 decimals precision is not known to exist
/// @dev Bump with any storage-layout change; `FluidUsdOracle`'s constructor rejects a `MAIN_VIEWS` reporting another value.
uint256 internal constant MAIN_VIEWS_LAYOUT_VERSION = 1;
uint256 internal constant ORACLE_PRECISION = 1e27;
uint256 internal constant CAP_OPERAND_PRECISION = 1e2;
uint256 internal constant CAP_PRECISION = ORACLE_PRECISION / CAP_OPERAND_PRECISION; // 1e25
/// @dev 10_000 basis points = 100%. Used for deviation ratio scaling and max `maxDeviationBPS` bound.
uint256 internal constant BPS_DENOMINATOR = 10_000;
/// @dev address that is mapped to the chain native token at Liquidity
address internal constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Maximum allowed timespan for Chainlink oracles in operate() mode (25 hours)
uint256 internal constant MAX_UPDATE_TIMESPAN_OPERATE = 25 hours;
/// @dev Maximum allowed timespan for Chainlink oracles in liquidate() mode (7 days)
uint256 internal constant MAX_UPDATE_TIMESPAN_LIQUIDATE = 7 days;
/// This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
/// The exact slot which stored the admin address in infinite proxy of liquidity contracts
bytes32 internal constant LIQUIDITY_GOVERNANCE_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Team multisig allowed to trigger certain config changes
address public constant TEAM_MULTISIG = 0x4F6F977aCDD1177DCD81aB83074855EcB9C2D49e;
}
abstract contract TransientVariables {
/// @dev Registered OracleKey for the current admin session (auto-cleared after transaction).
address internal transient _tToken;
uint256 internal transient _tEMode;
uint256 internal transient _tIsOperate;
uint256 internal transient _tIsCollateral;
/// @dev 1 if multisig just created a new config in this transaction, 0 otherwise.
uint256 internal transient _tIsNewConfig;
}
/// @notice Core protocol addresses set once at deployment (`FluidUsdOracle` constructor).
abstract contract Immutables {
/// @notice Address of the liquidity contract.
address public immutable LIQUIDITY;
/// @notice `FluidUsdOracleMainViews` holding the enumeration views, reached by delegatecall.
address public immutable MAIN_VIEWS;
}
abstract contract Variables is Constants, Structs, TransientVariables, Immutables {
// ----------------------- slot 0 ---------------------------
/// @notice Per-key configs: maps keccak256(abi.encode(token, eMode, isOperate, isCollateral)) => OracleKeyConfig.
/// Each key config is 1 slot, storing priceMode + caps + deviation + fallback flag.
/// This is one of the two hot-path SLOADs for the common `getPrice()` flow.
mapping(bytes32 => OracleKeyConfig) internal _configs;
// ----------------------- slot 1 ---------------------------
/// @notice maps token => array of all configured eMode/isOperate/isCollateral combinations for that token.
/// Used by getConfiguredTokenOracles to enumerate all configs.
mapping(address => ConfigMap[]) public configsMap;
// ----------------------- slot 2 ---------------------------
/// @dev guardian address => 1 if active, 0 if not. Guardians can pause tokens for isOperate calls.
mapping(address => uint256) internal _guardians;
// ----------------------- slot 3 ---------------------------
/// @dev Main per-token source configuration + metadata.
/// This mapping is the second hot-path SLOAD for the common `getPrice()` flow:
/// `_tokenSources[token]` storage slot 0 (`primarySrc` word 0) packs metadata with leg-1 source fields.
///
/// The layout is intentionally optimized so common reads resolve in 2 SLOADs total:
/// 1. `_configs[key]` for key-specific config.
/// 2. `_tokenSources[token]` slot 0 for metadata + `primarySrc` leg 1 (`source1`, `sourceType1-3`, …).
///
/// Without packing metadata into slot 0, token reads would need an extra SLOAD on every price
/// lookup just to fetch pause state / token type / decimals / flags.
///
/// Metadata lives on `primarySrc` (after leg-1 fields, before `__placeholder1` / future slot 0 expansion).
/// `primarySrc` uses storage slots 0-2; `altSrc` uses slots 3-5. `sourceType2` and `sourceType3`
/// stay in slot 0 so the read path can branch without loading slots 1 or 2.
///
/// What this mapping stores depends on token type:
/// - VOLATILE/STABLE: market price sources in the primary leg fields (the only price type for these tokens),
/// keeping those tokens on the 2-SLOAD path.
/// - PEG: peg price sources in `_tokenSources`, while market price sources for PEG tokens are
/// stored separately in `_additionalTokenSources`.
/// Peg is stored as primary because it is the more common lookup, so PEG tokens also stay on
/// the 2-SLOAD path for their primary price reads.
mapping(address => TokenSourceConfig) internal _tokenSources;
// ----------------------- slot 4 ---------------------------
/// @dev Additional per-token source configuration for secondary price types.
/// Reuses `TokenSourceConfig`, but only primary leg fields / `altSrc` are populated here.
/// Metadata bytes remain zero; listing metadata lives in `_tokenSources` so that
/// hot-path reads do not need to touch this mapping unless the requested price type is the
/// uncommon secondary one.
///
/// - PEG tokens: stores market price sources in the primary leg fields (secondary for PEG tokens).
/// Reading this path costs an extra SLOAD versus the common primary read.
/// - VOLATILE/STABLE: unused (these tokens only have market price in `_tokenSources`).
mapping(address => TokenSourceConfig) internal _additionalTokenSources;
}
Compiler settingsShow
{
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 10000000,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.