Skip to content
Verified contractExactBUSL-1.1

FluidERC4626CappedRate

Address0x05cad896ed76f080bab4da37c407928b994ff9b3
Balance

0 ETH

 

Transactions

2,151

 

Compiler

solc 0.8.21

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.21+commit.d9974bed
Language
solidity
Optimization
Yes, 10,000,000 runs
EVM version
paris
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,238,491
Creation transaction
0xe56a8e5504…f4db9d89a3

contracts/oracle/cappedRates/erc4626CappedRate.sol

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

import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { FluidCappedRate } from "../fluidCappedRate.sol";
import { ErrorTypes } from "../errorTypes.sol";

/// @notice Stores gas optimized and safety up and/or down capped exchange rate for a ERC4626 source, e.g. SUSDE / USDE rate.
///
/// @dev e.g. SUSDE contract; on mainnet 0x9D39A5DE30e57443BfF2A8307A4256c8797A3497
/// @dev e.g. SUSDS contract; on mainnet 0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD
contract FluidERC4626CappedRate is FluidCappedRate {
    constructor(FluidCappedRate.CappedRateConstructorParams memory params_) FluidCappedRate(params_) {
        if (_RATE_MULTIPLIER != 1) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
    }

    function _getNewRateRaw() internal view virtual override returns (uint256 exchangeRate_) {
        return IERC4626(_RATE_SOURCE).convertToAssets(1e27);
    }

    /// @notice Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
    /// scenario where all the conditions are met. see IERC4626
    function convertToShares(uint256 assets) external view returns (uint256 shares) {
        return (uint256(_slot0.rate) * assets) / 1e27;
    }

    /// @notice Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
    /// scenario where all the conditions are met. see IERC4626
    function convertToAssets(uint256 shares) external view returns (uint256 assets) {
        return (shares * 1e27) / uint256(_slot0.rate);
    }
}

@openzeppelin/contracts/interfaces/IERC4626.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);
}

@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);
}

contracts/libraries/liquiditySlotsLink.sol

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

/// @notice library that helps in reading / working with storage slot data of Fluid Liquidity.
/// @dev as all data for Fluid Liquidity is internal, any data must be fetched directly through manual
/// slot reading through this library or, if gas usage is less important, through the FluidLiquidityResolver.
library LiquiditySlotsLink {
    /// @dev storage slot for status at Liquidity
    uint256 internal constant LIQUIDITY_STATUS_SLOT = 1;
    /// @dev storage slot for auths mapping at Liquidity
    uint256 internal constant LIQUIDITY_AUTHS_MAPPING_SLOT = 2;
    /// @dev storage slot for guardians mapping at Liquidity
    uint256 internal constant LIQUIDITY_GUARDIANS_MAPPING_SLOT = 3;
    /// @dev storage slot for user class mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_CLASS_MAPPING_SLOT = 4;
    /// @dev storage slot for exchangePricesAndConfig mapping at Liquidity
    uint256 internal constant LIQUIDITY_EXCHANGE_PRICES_MAPPING_SLOT = 5;
    /// @dev storage slot for rateData mapping at Liquidity
    uint256 internal constant LIQUIDITY_RATE_DATA_MAPPING_SLOT = 6;
    /// @dev storage slot for totalAmounts mapping at Liquidity
    uint256 internal constant LIQUIDITY_TOTAL_AMOUNTS_MAPPING_SLOT = 7;
    /// @dev storage slot for user supply double mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_SUPPLY_DOUBLE_MAPPING_SLOT = 8;
    /// @dev storage slot for user borrow double mapping at Liquidity
    uint256 internal constant LIQUIDITY_USER_BORROW_DOUBLE_MAPPING_SLOT = 9;
    /// @dev storage slot for listed tokens array at Liquidity
    uint256 internal constant LIQUIDITY_LISTED_TOKENS_ARRAY_SLOT = 10;
    /// @dev storage slot for listed tokens array at Liquidity
    uint256 internal constant LIQUIDITY_CONFIGS2_MAPPING_SLOT = 11;

    // --------------------------------
    // @dev stacked uint256 storage slots bits position data for each:

    // ExchangePricesAndConfig
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATE = 0;
    uint256 internal constant BITS_EXCHANGE_PRICES_FEE = 16;
    uint256 internal constant BITS_EXCHANGE_PRICES_UTILIZATION = 30;
    uint256 internal constant BITS_EXCHANGE_PRICES_UPDATE_THRESHOLD = 44;
    uint256 internal constant BITS_EXCHANGE_PRICES_LAST_TIMESTAMP = 58;
    uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_EXCHANGE_PRICE = 91;
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_EXCHANGE_PRICE = 155;
    uint256 internal constant BITS_EXCHANGE_PRICES_SUPPLY_RATIO = 219;
    uint256 internal constant BITS_EXCHANGE_PRICES_BORROW_RATIO = 234;
    uint256 internal constant BITS_EXCHANGE_PRICES_USES_CONFIGS2 = 249;

    // RateData:
    uint256 internal constant BITS_RATE_DATA_VERSION = 0;
    // RateData: V1
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_ZERO = 4;
    uint256 internal constant BITS_RATE_DATA_V1_UTILIZATION_AT_KINK = 20;
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_KINK = 36;
    uint256 internal constant BITS_RATE_DATA_V1_RATE_AT_UTILIZATION_MAX = 52;
    // RateData: V2
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_ZERO = 4;
    uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK1 = 20;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK1 = 36;
    uint256 internal constant BITS_RATE_DATA_V2_UTILIZATION_AT_KINK2 = 52;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_KINK2 = 68;
    uint256 internal constant BITS_RATE_DATA_V2_RATE_AT_UTILIZATION_MAX = 84;

    // TotalAmounts
    uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_WITH_INTEREST = 0;
    uint256 internal constant BITS_TOTAL_AMOUNTS_SUPPLY_INTEREST_FREE = 64;
    uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_WITH_INTEREST = 128;
    uint256 internal constant BITS_TOTAL_AMOUNTS_BORROW_INTEREST_FREE = 192;

    // UserSupplyData
    uint256 internal constant BITS_USER_SUPPLY_MODE = 0;
    uint256 internal constant BITS_USER_SUPPLY_AMOUNT = 1;
    uint256 internal constant BITS_USER_SUPPLY_PREVIOUS_WITHDRAWAL_LIMIT = 65;
    uint256 internal constant BITS_USER_SUPPLY_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_SUPPLY_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_SUPPLY_BASE_WITHDRAWAL_LIMIT = 200;
    uint256 internal constant BITS_USER_SUPPLY_IS_PAUSED = 255;

    // UserBorrowData
    uint256 internal constant BITS_USER_BORROW_MODE = 0;
    uint256 internal constant BITS_USER_BORROW_AMOUNT = 1;
    uint256 internal constant BITS_USER_BORROW_PREVIOUS_BORROW_LIMIT = 65;
    uint256 internal constant BITS_USER_BORROW_LAST_UPDATE_TIMESTAMP = 129;
    uint256 internal constant BITS_USER_BORROW_EXPAND_PERCENT = 162;
    uint256 internal constant BITS_USER_BORROW_EXPAND_DURATION = 176;
    uint256 internal constant BITS_USER_BORROW_BASE_BORROW_LIMIT = 200;
    uint256 internal constant BITS_USER_BORROW_MAX_BORROW_LIMIT = 218;
    uint256 internal constant BITS_USER_BORROW_IS_PAUSED = 255;

    // Configs2
    uint256 internal constant BITS_CONFIGS2_MAX_UTILIZATION = 0;

    // --------------------------------

    /// @notice Calculating the slot ID for Liquidity contract for single mapping at `slot_` for `key_`
    function calculateMappingStorageSlot(uint256 slot_, address key_) internal pure returns (bytes32) {
        return keccak256(abi.encode(key_, slot_));
    }

    /// @notice Calculating the slot ID for Liquidity contract for double mapping at `slot_` for `key1_` and `key2_`
    function calculateDoubleMappingStorageSlot(
        uint256 slot_,
        address key1_,
        address key2_
    ) internal pure returns (bytes32) {
        bytes32 intermediateSlot_ = keccak256(abi.encode(key1_, slot_));
        return keccak256(abi.encode(key2_, intermediateSlot_));
    }
}

contracts/oracle/error.sol

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

contract Error {
    error FluidOracleError(uint256 errorId_);
}

contracts/oracle/errorTypes.sol

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

library ErrorTypes {
    /***********************************|
    |           FluidOracleL2           | 
    |__________________________________*/

    /// @notice thrown when sequencer on a L2 has an outage and grace period has not yet passed.
    uint256 internal constant FluidOracleL2__SequencerOutage = 60000;

    /***********************************|
    |     UniV3CheckCLRSOracle          | 
    |__________________________________*/

    /// @notice thrown when the delta between main price source and check rate source is exceeding the allowed delta
    uint256 internal constant UniV3CheckCLRSOracle__InvalidPrice = 60001;

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant UniV3CheckCLRSOracle__InvalidParams = 60002;

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant UniV3CheckCLRSOracle__ExchangeRateZero = 60003;

    /***********************************|
    |           FluidOracle             | 
    |__________________________________*/

    /// @notice thrown when an invalid info name is passed into a fluid oracle (e.g. not set or too long)
    uint256 internal constant FluidOracle__InvalidInfoName = 60010;

    /***********************************|
    |            sUSDe Oracle           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant SUSDeOracle__InvalidParams = 60102;

    /***********************************|
    |           Pendle Oracle           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant PendleOracle__InvalidParams = 60201;

    /// @notice thrown when the Pendle market Oracle has not been initialized yet
    uint256 internal constant PendleOracle__MarketNotInitialized = 60202;

    /// @notice thrown when the Pendle market does not have 18 decimals
    uint256 internal constant PendleOracle__MarketInvalidDecimals = 60203;

    /// @notice thrown when the Pendle market returns an unexpected price
    uint256 internal constant PendleOracle__InvalidPrice = 60204;

    /***********************************|
    |    CLRS2UniV3CheckCLRSOracleL2    | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant CLRS2UniV3CheckCLRSOracleL2__ExchangeRateZero = 60301;

    /***********************************|
    |    Ratio2xFallbackCLRSOracleL2    | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant Ratio2xFallbackCLRSOracleL2__ExchangeRateZero = 60311;

    /***********************************|
    |            WeETHsOracle           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant WeETHsOracle__InvalidParams = 60321;

    /***********************************|
    |        DexSmartColOracle          | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant DexSmartColOracle__InvalidParams = 60331;

    /// @notice thrown when smart col is not enabled
    uint256 internal constant DexSmartColOracle__SmartColNotEnabled = 60332;

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant DexSmartColOracle__ExchangeRateZero = 60333;

    /***********************************|
    |        DexSmartDebtOracle         | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant DexSmartDebtOracle__InvalidParams = 60341;

    /// @notice thrown when smart debt is not enabled
    uint256 internal constant DexSmartDebtOracle__SmartDebtNotEnabled = 60342;

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant DexSmartDebtOracle__ExchangeRateZero = 60343;

    /***********************************|
    |            CappedRate           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant CappedRate__InvalidParams = 60351;

    /// @notice thrown when caller is not authorized
    uint256 internal constant CappedRate__Unauthorized = 60352;

    /// @notice thrown when minimum diff for triggering update on the stared rate is not reached
    uint256 internal constant CappedRate__MinUpdateDiffNotReached = 60353;

    /// @notice thrown when the external rate source returns 0 for the new rate
    uint256 internal constant CappedRate__NewRateZero = 60354;

    /// @notice thrown when the new rate source does not fit in 192 bit storage uint, should never happen.
    uint256 internal constant CappedRate__StorageOverflow = 60355;

    /***********************************|
    |            sUSDs Oracle           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant SUSDsOracle__InvalidParams = 60361;

    /***********************************|
    |            Peg Oracle             | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant PegOracle__InvalidParams = 60371;

    /***********************************|
    |              DexOracle            | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant DexOracle__InvalidParams = 60381;

    /// @notice thrown when the exchange rate is zero, even after all possible fallbacks depending on config
    uint256 internal constant DexOracle__ExchangeRateZero = 60382;

    /***********************************|
    |           GenericOracle           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant GenericOracle__InvalidParams = 60401;

    /// @notice thrown when reaching an unexepcted config state
    uint256 internal constant GenericOracle__UnexpectedConfig = 60402;

    /// @notice thrown when the exchange rate is zero
    uint256 internal constant GenericOracle__RateZero = 60403;

    /***********************************|
    |             CenterPrice           | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant CenterPrice__InvalidParams = 60421;

    /***********************************|
    |          Chainlink Oracle         | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant ChainlinkOracle__InvalidParams = 61001;

    /***********************************|
    |          UniswapV3 Oracle         | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant UniV3Oracle__InvalidParams = 62001;

    /// @notice thrown when constructor is called with invalid ordered seconds agos values
    uint256 internal constant UniV3Oracle__InvalidSecondsAgos = 62002;

    /// @notice thrown when constructor is called with invalid delta values > 100%
    uint256 internal constant UniV3Oracle__InvalidDeltas = 62003;

    /***********************************|
    |            WstETh Oracle          | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant WstETHOracle__InvalidParams = 63001;

    /***********************************|
    |           Redstone Oracle         | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant RedstoneOracle__InvalidParams = 64001;

    /***********************************|
    |          Fallback Oracle          | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant FallbackOracle__InvalidParams = 65001;

    /***********************************|
    |       FallbackCLRSOracle          | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even for the fallback oracle source (if enabled)
    uint256 internal constant FallbackCLRSOracle__ExchangeRateZero = 66001;

    /***********************************|
    |         WstETHCLRSOracle          | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even for the fallback oracle source (if enabled)
    uint256 internal constant WstETHCLRSOracle__ExchangeRateZero = 67001;

    /***********************************|
    |        CLFallbackUniV3Oracle      | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even for the uniV3 rate
    uint256 internal constant CLFallbackUniV3Oracle__ExchangeRateZero = 68001;

    /***********************************|
    |  WstETHCLRS2UniV3CheckCLRSOracle  | 
    |__________________________________*/

    /// @notice thrown when the exchange rate is zero, even for the uniV3 rate
    uint256 internal constant WstETHCLRS2UniV3CheckCLRSOracle__ExchangeRateZero = 69001;

    /***********************************|
    |             WeETh Oracle          | 
    |__________________________________*/

    /// @notice thrown when an invalid parameter is passed to a method
    uint256 internal constant WeETHOracle__InvalidParams = 70001;
}

contracts/oracle/fluidCappedRate.sol

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

import { IFluidOracle } from "./interfaces/iFluidOracle.sol";
import { IFluidCappedRate } from "./interfaces/iFluidCappedRate.sol";
import { FluidCenterPrice } from "./fluidCenterPrice.sol";

import { LiquiditySlotsLink } from "../libraries/liquiditySlotsLink.sol";

import { Error as OracleError } from "./error.sol";
import { ErrorTypes } from "./errorTypes.sol";

interface IFluidLiquidity {
    function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
}

abstract contract Events {
    /// @notice emitted when rebalancer successfully changes the contract rate
    event LogRebalanceRate(uint256 oldRate, uint256 newRate, uint256 oldMaxRate, uint256 newMaxRate);

    /// @notice emitted when the external rate is currently lower than the previous maximum rate by at least `_maxDownFromMaxReachedPercent`
    event LogRateBelowMaxReached();

    /// @notice emitted when the external rate increased faster than `_maxAPRPercent` allows
    event LogRateMaxAPRCapped();

    /// @notice Emitted when avoidForcedLiquidations col is updated
    event LogUpdateAvoidForcedLiquidationsCol(bool oldAvoidForcedLiquidations, bool newAvoidForcedLiquidations);

    /// @notice Emitted when avoidForcedLiquidations debt is updated
    event LogUpdateAvoidForcedLiquidationsDebt(bool oldAvoidForcedLiquidations, bool newAvoidForcedLiquidations);

    /// @notice Emitted when maxAPRPercent is updated
    event LogUpdateMaxAPRPercent(uint256 oldMaxAPRPercent, uint256 newMaxAPRPercent);

    /// @notice Emitted when _maxDownFromMaxReachedPercentCol is updated
    event LogUpdateMaxDownFromMaxReachedPercentCol(
        uint256 oldMaxDownFromMaxReachedPercent,
        uint256 newMaxDownFromMaxReachedPercent
    );

    /// @notice Emitted when _maxDownFromMaxReachedPercentDebt is updated
    event LogUpdateMaxDownFromMaxReachedPercentDebt(
        uint256 oldMaxDownFromMaxReachedPercent,
        uint256 newMaxDownFromMaxReachedPercent
    );

    /// @notice Emitted when max reached rate is reset to `_rate`
    event LogForceResetMaxRate(uint256 oldMaxRate, uint256 newMaxRate);

    /// @notice Emitted when _maxDebtUpCapPercent is updated
    event LogUpdateMaxDebtUpCapPercent(uint256 oldMaxDebtUpCapPercent, uint256 newMaxDebtUpCapPercent);

    /// @notice Emitted when _minHeartbeat is updated
    event LogUpdateMinHeartbeat(uint256 oldMinHeartbeat, uint256 newMinHeartbeat);

    /// @notice Emitted when _minUpdateDiffPercent is updated
    event LogUpdateMinUpdateDiffPercent(uint256 oldMinUpdateDiffPercent, uint256 newMinUpdateDiffPercent);
}

abstract contract Constants {
    /// @dev Ignoring leap years
    uint256 internal constant _SECONDS_PER_YEAR = 365 days;

    /// @dev 100% precision
    uint256 internal constant _SIX_DECIMALS = 1e6;

    uint256 internal constant _X3 = 7;

    /// @dev liquidity layer address
    address internal immutable _LIQUIDITY;

    /// @dev external exchange rate source contract
    address internal immutable _RATE_SOURCE;

    /// @dev flag if fetched rate should be inverted
    bool internal immutable _INVERT_CENTER_PRICE;

    /// @dev external exchange rate source multiplier to get to 1e27 decimals
    uint256 internal immutable _RATE_MULTIPLIER;
}

abstract contract Variables is Constants {
    // slot 0 flag bitmasks
    uint8 internal constant _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED = 1;
    uint8 internal constant _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED = 2;
    uint8 internal constant _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL = 4;
    uint8 internal constant _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT = 8;
    uint8 internal constant _FLAG_BITMASK_ALLOW_MAX_YIELD_JUMPS = 0xE0; // 1110 0000

    struct Slot0 {
        /// @dev exchange rate as fetched from external rate source in 1e27 decimals. max value 3.74e50
        uint168 rate;
        /// @dev time when last update for rate happened
        uint40 lastUpdateTime;
        /// @dev flags bitmap:
        /// Bit 1: true if the `_rate` value is currently < _maxReachedAPRCappedRate
        ///        bool internal _isRateBelowMaxReached;

        /// Bit 2: true if the `_rate` value is currently > _maxReachedAPRCappedRate, so capped because of the maxAPR limit
        ///        bool internal _isUpMaxAPRCapped;

        /// Bit 3: Col side: config flag to signal whether to protect users vs protect protocol depending on asset reliability (accept temporary bad debt if trusting peg).
        ///        flag should only be active for trusted assets where we assume any peg can only be temporary as when this flag is on
        ///        it can lead to bad debt until asset repeg is reached. For not 100% trusted assets better to liquidate on depeg and avoid any bad debt
        ///        Configurable by Governance and Liquidity guardians
        ///        bool internal _avoidForcedLiquidationsCol;

        /// Bit 4: same as Bit 3, but for debt side
        ///        bool internal _avoidForcedLiquidationsDebt;

        /// Bit 5: ----- empty -------

        /// Bits 6,7,8: uint3 -> allowed max yield jumps. each heartbeat update where minUpdateDiff is not reached increases this by 1,
        ///                      up to a maximum of 7. Reset to 0 for any update that is > min update diff.
        ///                      For any price update, the maximum price increase is:
        ///                      normal max yield increase since lastUpdateTime + maxYieldJumps * maxYield / HeartBeatDuration
        uint8 flags;
        /// @dev Minimum time after which an update can trigger, even if it does not reach `_minUpdateDiffPercent`. Max value = 16_777_215 -> ~194 days
        ///      Configurable by Governance.
        uint24 minHeartbeat;
        /// @dev Minimum difference to trigger update in percent 1e4 decimals, 10000 = 1%. Max value = 6,5535%
        ///      Configurable by Governance.
        uint16 minUpdateDiffPercent;
    }

    struct Slot1 {
        /// @dev tracks the maximum ever reached rate with respect of maxAPR percent (a temporary 100x spike does not increase this value beyond max apr increase).
        /// this is only updated IF `_rate` is not == `_maxReachedAPRCappedRate`, i.e. if `_isRateBelowMaxReached || _isUpMaxAPRCapped`. max value 3.74e50
        ///
        /// Can be reset synced to match `_rate` by Govnernance and Liquidity guardians, when wanting to force skip max APR or forcing reset after rate reduced
        uint168 maxReachedAPRCappedRate;
        /// @dev maximum yield APR that exchange rate can increase in each update
        /// in 1e2 precision, 1% = 100. max value-> 167_772,15%, can be set to 0 to force no rate increase possible for upwards cap
        ///
        /// Configurable by Governance and Liquidity guardians.
        uint24 maxAPRPercent;
        /// @dev Col side: maximum down percent reduction of `_maxReachedAPRCappedRate` for rates with downward cap protection.
        /// in 1e4 precision, 1% = 1e4. max value-> 1_677,7215 % (so max configurable value = _SIX_DECIMALS which is 100% -> removing downward cap entirely)
        ///
        /// Configurable by Governance and Liquidity guardians
        uint24 maxDownFromMaxReachedPercentCol;
        /// @dev same as above but for debt
        uint24 maxDownFromMaxReachedPercentDebt;
        /// @dev Debt side: maximum up percent cap on top of `_maxReachedAPRCappedRate`, only relevant when avoid forced liquidations attack for debt side is active,
        /// when _avoidForcedLiquidationsDebt flag is true. in 1e2 precision, 1% = 100. max value-> 655,35%, can be set to 0 to have same cap as on col side.
        ///
        /// Configurable by Governance and Liquidity guardians.
        uint16 maxDebtUpCapPercent;
    }

    Slot0 internal _slot0; // Used in default view methods

    Slot1 internal _slot1; // Used only in special cases, storage updates or admin related
}

abstract contract CappedRateInternals is Variables, Events, OracleError {
    /// @dev read the exchange rate from the external contract e.g. wstETH or rsETH exchange rate, yet to be scaled to 1e27
    /// To be implemented by inheriting contract
    function _getNewRateRaw() internal view virtual returns (uint256 exchangeRate_);

    /// @dev gets the percentage difference between `oldValue_` and `newValue_` in relation to `oldValue_` in percent (10000 = 1%, 1 = 0.0001%).
    function _percentDiffForValue(
        uint256 oldValue_,
        uint256 newValue_
    ) internal pure returns (uint256 configPercentDiff_) {
        unchecked {
            if (oldValue_ > newValue_) {
                configPercentDiff_ = ((oldValue_ - newValue_) * _SIX_DECIMALS) / oldValue_;
            } else if (newValue_ > oldValue_) {
                configPercentDiff_ = ((newValue_ - oldValue_) * _SIX_DECIMALS) / oldValue_;
            }
        }
    }

    /// @dev get new rate from external source and return updated related parameters.
    function _getUpdateRates(
        uint256 maxReachedRate_,
        Slot0 memory slot0_,
        uint256 maxAPRPercent_
    )
        internal
        view
        virtual
        returns (uint256 newRate_, uint256 maxRate_, bool isUpMaxAPRCapped_, bool isRateBelowMaxReached_)
    {
        newRate_ = _getNewRateRaw() * _RATE_MULTIPLIER;
        if (newRate_ == 0) {
            revert FluidOracleError(ErrorTypes.CappedRate__NewRateZero);
        }

        maxRate_ = _calcMaxAPRCappedRate(newRate_, maxReachedRate_, slot0_, maxAPRPercent_);
        isUpMaxAPRCapped_ = newRate_ > maxRate_;
        isRateBelowMaxReached_ = newRate_ < maxRate_;
    }

    /// @dev updates the values in storage according to the newly fetched rate from external source.
    function _updateRates(bool forceUpdate_) internal virtual returns (uint256 newRate_) {
        Slot0 memory slot0_ = _slot0;
        Slot1 memory slot1_ = _slot1;

        uint256 newMaxReachedRate_;
        bool isUpMaxAPRCapped_;
        bool isRateBelowMaxReached_;

        uint256 maxReachedAPRCappedRate_ = uint256(slot1_.maxReachedAPRCappedRate);

        (newRate_, newMaxReachedRate_, isUpMaxAPRCapped_, isRateBelowMaxReached_) = _getUpdateRates(
            maxReachedAPRCappedRate_,
            slot0_,
            uint256(slot1_.maxAPRPercent)
        );

        if (newRate_ > type(uint168).max || newMaxReachedRate_ > type(uint168).max) {
            revert FluidOracleError(ErrorTypes.CappedRate__StorageOverflow);
        }

        uint256 curRate_ = uint256(slot0_.rate);

        uint256 allowedMaxYieldJumps_ = 0;
        if (
            _percentDiffForValue(curRate_, newRate_) < uint256(slot0_.minUpdateDiffPercent) &&
            _percentDiffForValue(maxReachedAPRCappedRate_, newMaxReachedRate_) < uint256(slot0_.minUpdateDiffPercent)
        ) {
            if (forceUpdate_) {
                // min update diff not reached but update is forced anyway via heartbeat -> increase allowed max yield jumps
                allowedMaxYieldJumps_ = (uint256(slot0_.flags & _FLAG_BITMASK_ALLOW_MAX_YIELD_JUMPS) + 1) & _X3; // force max value possible 7
            } else {
                revert FluidOracleError(ErrorTypes.CappedRate__MinUpdateDiffNotReached);
            }
        }

        if (isUpMaxAPRCapped_) {
            // if this flag is true then the rate is always effectively upwards capped
            emit LogRateMaxAPRCapped();
        }
        if (isRateBelowMaxReached_) {
            uint256 downPercent_ = ((newMaxReachedRate_ - newRate_) * _SIX_DECIMALS) / newMaxReachedRate_;
            if (
                downPercent_ > slot1_.maxDownFromMaxReachedPercentCol ||
                downPercent_ > slot1_.maxDownFromMaxReachedPercentDebt
            ) {
                // only log this if the decrease is by more than `_maxDownFromMaxReachedPercent` so if the returned rate actually ends up getting
                // downwards capped (for either col or debt)
                emit LogRateBelowMaxReached();
            }
        }

        // storage slot 1 ALWAYS gets updated because of timestamp so no need to optimize much here
        slot0_.lastUpdateTime = uint40(block.timestamp);
        slot0_.rate = uint168(newRate_);
        slot0_.flags =
            (slot0_.flags & 0x1C) | // 0001 1100
            (isRateBelowMaxReached_ ? _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED : 0) |
            (isUpMaxAPRCapped_ ? _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED : 0) |
            (uint8(allowedMaxYieldJumps_) << 5);
        _slot0 = slot0_; // write to storage

        // storage slot 2 might not always change, only if max rate changes, which could be not needed e.g. if rate decreased
        if (maxReachedAPRCappedRate_ < newMaxReachedRate_) {
            _slot1.maxReachedAPRCappedRate = uint168(newMaxReachedRate_);
        }

        emit LogRebalanceRate(curRate_, newRate_, maxReachedAPRCappedRate_, newMaxReachedRate_);
    }

    /// @dev returns the downwards capped rate max(downCappedRate_, rate_), where downCappedRate_ is capped at maxReachedAPRCappedRate_ - _maxDownFromMaxReachedPercent %.
    function _calcDownCappedRate(
        uint256 rate_,
        uint256 maxReachedRate_,
        uint256 maxDownPercent_
    ) internal pure returns (uint256 downCappedRate_) {
        unchecked {
            downCappedRate_ = (maxReachedRate_ * (_SIX_DECIMALS - maxDownPercent_)) / _SIX_DECIMALS;
        }

        if (rate_ > downCappedRate_) {
            downCappedRate_ = rate_;
        }
    }

    /// @dev returns the upwards capped rate min(upCappedRate_, rate_), where upCappedRate_ is capped at maxReachedAPRCappedRate_ + _maxAPRPercent %
    /// adjusted for passed time since last update time.
    function _calcMaxAPRCappedRate(
        uint256 rate_,
        uint256 maxReachedRate_,
        Slot0 memory slot0_,
        uint256 maxAPRPercent_
    ) internal view returns (uint256 maxRate_) {
        unchecked {
            maxRate_ =
                (maxAPRPercent_ * uint256(100) * (block.timestamp - uint256(slot0_.lastUpdateTime))) /
                _SECONDS_PER_YEAR; // maxRate_ = max APR for passed time since last update time
            maxRate_ = (maxReachedRate_ * (_SIX_DECIMALS + maxRate_)) / _SIX_DECIMALS;

            // add allowed max yield jumps from any heartbeat update that did not marginally increase the rate but increased the timestamp
            uint256 allowedMaxYieldJumps_ = (slot0_.flags & _FLAG_BITMASK_ALLOW_MAX_YIELD_JUMPS);
            if (allowedMaxYieldJumps_ > 0) {
                uint256 maxAPRPerHeartbeat_ = (maxAPRPercent_ * uint256(100) * slot0_.minHeartbeat) / _SECONDS_PER_YEAR;
                maxRate_ = (maxRate_ * (_SIX_DECIMALS + allowedMaxYieldJumps_ * maxAPRPerHeartbeat_)) / _SIX_DECIMALS;
            }
        }

        if (rate_ > maxRate_) {
            // rate increase is capped at max rate
            return maxRate_;
        }
        if (rate_ < maxReachedRate_) {
            // if rate is lower than previous max reached rate, then previous max reached rate is the max rate
            return maxReachedRate_;
        }

        // rate is > maxReachedRate and < max allowed rate
        return rate_;
    }

    /// @dev returns true if last update timestamp is too long ago so heartbeat update should trigger
    function _isHeartbeatTrigger(Slot0 memory slot0_) internal view returns (bool) {
        unchecked {
            return ((uint256(slot0_.lastUpdateTime) + slot0_.minHeartbeat) < block.timestamp);
        }
    }

    /// @dev returns inverted rate if needed (when _INVERT_CENTER_PRICE flag is set to true)
    function _invertRateIfNeeded(uint256 exchangeRate_) internal view returns (uint256) {
        if (exchangeRate_ == 0) {
            return 0;
        }
        unchecked {
            return _INVERT_CENTER_PRICE ? 1e54 / exchangeRate_ : exchangeRate_;
        }
    }
}

abstract contract CappedRateAdmin is Variables, Events, OracleError {
    /// This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1 where current liquidity owner on proxy is stored
    bytes32 internal constant GOVERNANCE_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /// @dev only Liquidity Layer owner (governance) and guardians access modifier
    modifier onlyGuardians() {
        bool isGuardian_ = (IFluidLiquidity(_LIQUIDITY).readFromStorage(
            LiquiditySlotsLink.calculateMappingStorageSlot(
                LiquiditySlotsLink.LIQUIDITY_GUARDIANS_MAPPING_SLOT,
                msg.sender
            )
        ) & 1) == 1;

        bool isGovernance_ = address(uint160(IFluidLiquidity(_LIQUIDITY).readFromStorage(GOVERNANCE_SLOT))) ==
            msg.sender;

        if (!isGuardian_ && !isGovernance_) {
            revert FluidOracleError(ErrorTypes.CappedRate__Unauthorized);
        }
        _;
    }

    /// @dev only Liquidity Layer owner (governance) access modifier
    modifier onlyGovernance() {
        if (address(uint160(IFluidLiquidity(_LIQUIDITY).readFromStorage(GOVERNANCE_SLOT))) != msg.sender) {
            revert FluidOracleError(ErrorTypes.CappedRate__Unauthorized);
        }
        _;
    }

    /// @notice Updates the avoidForcedLiquidations_ col side config flag. Only callable by Liquidity Layer guardians
    function updateAvoidForcedLiquidationsCol(bool avoid_) external onlyGuardians {
        bool oldAvoidForcedLiquidations_ = _slot0.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL ==
            _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL;
        _slot0.flags = (_slot0.flags & 0xFB) | (avoid_ ? _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL : 0); // mask F1011
        emit LogUpdateAvoidForcedLiquidationsCol(oldAvoidForcedLiquidations_, avoid_);
    }

    /// @notice Updates the avoidForcedLiquidations_ debt side config flag. Only callable by Liquidity Layer guardians
    function updateAvoidForcedLiquidationsDebt(bool avoid_) external onlyGuardians {
        bool oldAvoidForcedLiquidations_ = _slot0.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT ==
            _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT;
        _slot0.flags = (_slot0.flags & 0xF7) | (avoid_ ? _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT : 0); // mask F0111
        emit LogUpdateAvoidForcedLiquidationsDebt(oldAvoidForcedLiquidations_, avoid_);
    }

    /// @notice resets max reached rate to current `_rate` value. Only callable by Liquidity Layer guardians
    function forceResetMaxRate() external onlyGuardians {
        uint256 oldMaxRate_ = uint256(_slot1.maxReachedAPRCappedRate);
        _slot1.maxReachedAPRCappedRate = _slot0.rate;
        emit LogForceResetMaxRate(oldMaxRate_, uint256(_slot1.maxReachedAPRCappedRate));
    }

    /// @notice Updates the maxAPRPercent_ config, in 1e4 percent (1% = 1e4). Only callable by Governance
    function updateMaxAPRPercent(uint256 newMaxAPRPercent_) external onlyGuardians {
        if (newMaxAPRPercent_ > type(uint24).max * uint256(100)) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMaxAPRPercent_ = uint256(_slot1.maxAPRPercent) * uint256(100);
        _slot1.maxAPRPercent = uint24(newMaxAPRPercent_ / uint256(100));
        emit LogUpdateMaxAPRPercent(oldMaxAPRPercent_, newMaxAPRPercent_);
    }

    /// @notice Updates the _maxDownFromMaxReachedPercentCol config. Only callable by Liquidity Layer guardians.
    ///         Set to 100% (1e6) to completely remove down peg (same as updateAvoidForcedLiquidationsCol = false)
    function updateMaxDownFromMaxReachedPercentCol(uint256 newMaxDownFromMaxReachedPercent_) external onlyGuardians {
        if (newMaxDownFromMaxReachedPercent_ > _SIX_DECIMALS) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMaxDownFromMaxReachedPercent_ = uint256(_slot1.maxDownFromMaxReachedPercentCol);
        _slot1.maxDownFromMaxReachedPercentCol = uint24(newMaxDownFromMaxReachedPercent_);
        emit LogUpdateMaxDownFromMaxReachedPercentCol(
            oldMaxDownFromMaxReachedPercent_,
            newMaxDownFromMaxReachedPercent_
        );
    }

    /// @notice Updates the _maxDownFromMaxReachedPercentDebt config. Only callable by Liquidity Layer guardians.
    ///         Set to 100% (1e6) to completely remove down peg.
    function updateMaxDownFromMaxReachedPercentDebt(uint256 newMaxDownFromMaxReachedPercent_) external onlyGuardians {
        if (newMaxDownFromMaxReachedPercent_ > _SIX_DECIMALS) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMaxDownFromMaxReachedPercent_ = uint256(_slot1.maxDownFromMaxReachedPercentDebt);
        _slot1.maxDownFromMaxReachedPercentDebt = uint24(newMaxDownFromMaxReachedPercent_);
        emit LogUpdateMaxDownFromMaxReachedPercentDebt(
            oldMaxDownFromMaxReachedPercent_,
            newMaxDownFromMaxReachedPercent_
        );
    }

    /// @notice Updates the _maxDebtUpCapPercent config. Only callable by Liquidity Layer guardians.
    function updateMaxDebtUpCapPercent(uint256 newMaxDebtUpCapPercent_) external onlyGuardians {
        if (newMaxDebtUpCapPercent_ > type(uint16).max * uint256(100)) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMaxDebtUpCapPercent_ = uint256(_slot1.maxDebtUpCapPercent) * uint256(100);
        _slot1.maxDebtUpCapPercent = uint16(newMaxDebtUpCapPercent_ / uint256(100));
        emit LogUpdateMaxDebtUpCapPercent(oldMaxDebtUpCapPercent_, newMaxDebtUpCapPercent_);
    }

    /// @notice Updates the _minHeartbeat config. Only callable by Governance.
    function updateMinHeartbeat(uint256 newMinHeartbeat_) external onlyGovernance {
        if (newMinHeartbeat_ > type(uint24).max || newMinHeartbeat_ == 0) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMinHeartbeat_ = uint256(_slot0.minHeartbeat);
        _slot0.minHeartbeat = uint24(newMinHeartbeat_);
        emit LogUpdateMinHeartbeat(oldMinHeartbeat_, newMinHeartbeat_);
    }

    /// @notice Updates the _minUpdateDiffPercent config. Only callable by Governance.
    function updateMinUpdateDiffPercent(uint256 newMinUpdateDiffPercent_) external onlyGovernance {
        if (newMinUpdateDiffPercent_ > type(uint16).max || newMinUpdateDiffPercent_ == 0) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        uint256 oldMinUpdateDiffPercent_ = uint256(_slot0.minUpdateDiffPercent);
        _slot0.minUpdateDiffPercent = uint16(newMinUpdateDiffPercent_);
        emit LogUpdateMinUpdateDiffPercent(oldMinUpdateDiffPercent_, newMinUpdateDiffPercent_);
    }
}

/// @notice This contract stores an exchange rate with caps in intervals to optimize gas cost.
/// @notice Properly implements all interfaces for use as IFluidCenterPrice and IFluidOracle.
abstract contract FluidCappedRateBase is CappedRateInternals, CappedRateAdmin, IFluidCappedRate {
    /// @dev Validates that an address is not the zero address
    modifier validAddress(address value_) {
        if (value_ == address(0)) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        _;
    }

    struct CappedRateConstructorParams {
        string infoName;
        address liquidity;
        address rateSource;
        uint256 rateMultiplier;
        bool invertCenterPrice;
        uint256 minUpdateDiffPercent;
        uint256 minHeartbeat;
        bool avoidForcedLiquidationsCol;
        bool avoidForcedLiquidationsDebt;
        uint256 maxAPRPercent;
        uint256 maxDownFromMaxReachedPercentCol;
        uint256 maxDownFromMaxReachedPercentDebt;
        uint256 maxDebtUpCapPercent;
    }

    constructor(
        CappedRateConstructorParams memory params_
    ) validAddress(params_.liquidity) validAddress(params_.rateSource) {
        if (
            params_.rateMultiplier == 0 ||
            params_.rateMultiplier > 1e21 ||
            params_.minUpdateDiffPercent == 0 ||
            params_.minUpdateDiffPercent > type(uint16).max ||
            params_.minHeartbeat == 0 ||
            params_.minHeartbeat > type(uint24).max ||
            params_.maxDownFromMaxReachedPercentCol > _SIX_DECIMALS ||
            params_.maxDownFromMaxReachedPercentDebt > _SIX_DECIMALS ||
            params_.maxAPRPercent > type(uint24).max * uint256(100) ||
            params_.maxDebtUpCapPercent > type(uint16).max * uint256(100)
        ) {
            revert FluidOracleError(ErrorTypes.CappedRate__InvalidParams);
        }
        _LIQUIDITY = params_.liquidity;
        _RATE_SOURCE = params_.rateSource;
        _RATE_MULTIPLIER = params_.rateMultiplier;
        _INVERT_CENTER_PRICE = params_.invertCenterPrice;

        _slot0.rate = uint168(_getNewRateRaw() * _RATE_MULTIPLIER);
        _slot0.lastUpdateTime = uint40(block.timestamp);

        _slot0.minUpdateDiffPercent = uint16(params_.minUpdateDiffPercent);
        _slot0.minHeartbeat = uint24(params_.minHeartbeat);

        _slot0.flags =
            (params_.avoidForcedLiquidationsCol ? _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL : 0) |
            (params_.avoidForcedLiquidationsDebt ? _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT : 0);

        _slot1.maxAPRPercent = uint24(params_.maxAPRPercent / uint256(100));
        _slot1.maxDownFromMaxReachedPercentCol = (params_.maxDownFromMaxReachedPercentCol == 0 &&
            !params_.avoidForcedLiquidationsCol)
            ? uint24(_SIX_DECIMALS) // set to 100% by default when this config is not active
            : uint24(params_.maxDownFromMaxReachedPercentCol);
        _slot1.maxDownFromMaxReachedPercentDebt = uint24(params_.maxDownFromMaxReachedPercentDebt);
        _slot1.maxDebtUpCapPercent = uint16(params_.maxDebtUpCapPercent / uint256(100));
        _slot1.maxReachedAPRCappedRate = _slot0.rate;
    }

    /// @inheritdoc IFluidOracle
    function getExchangeRate() public view virtual returns (uint256 exchangeRate_) {
        // deprecated legacy support method -> Should not be used anywhere anymore.
        Slot0 memory slot0_ = _slot0;

        if (_isHeartbeatTrigger(slot0_)) {
            Slot1 memory slot1_ = _slot1;
            (exchangeRate_, , , ) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
            return exchangeRate_;
        }
        return uint256(slot0_.rate);
    }

    /// @inheritdoc IFluidOracle
    function getExchangeRateOperate() public view virtual returns (uint256 exchangeRate_) {
        // for col -> up APR capped (avoid overpricing exploit), down no cap
        Slot0 memory slot0_ = _slot0;

        if (_isHeartbeatTrigger(slot0_)) {
            Slot1 memory slot1_ = _slot1;
            uint256 maxReachedRate_;
            bool isUpMaxAPRCapped_;
            (exchangeRate_, maxReachedRate_, isUpMaxAPRCapped_, ) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
            return isUpMaxAPRCapped_ ? maxReachedRate_ : exchangeRate_;
        }

        return
            (slot0_.flags & _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED == _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED) // is _isUpMaxAPRCapped
                ? uint256(_slot1.maxReachedAPRCappedRate)
                : uint256(slot0_.rate);
    }

    /// @inheritdoc IFluidOracle
    function getExchangeRateLiquidate() public view virtual returns (uint256 exchangeRate_) {
        // for col -> up max APR cap, down capped (avoid forced liquidations attack)
        Slot0 memory slot0_ = _slot0;

        Slot1 memory slot1_; // only read if needed

        uint256 maxReachedRate_;
        bool isUpMaxAPRCapped_;
        bool isRateBelowMaxReached_;

        if (_isHeartbeatTrigger(slot0_)) {
            slot1_ = _slot1;
            (exchangeRate_, maxReachedRate_, isUpMaxAPRCapped_, isRateBelowMaxReached_) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
        } else {
            isUpMaxAPRCapped_ = slot0_.flags & _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED == _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED;
            isRateBelowMaxReached_ =
                slot0_.flags & _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED == _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED;
            exchangeRate_ = uint256(slot0_.rate);
        }

        if (isUpMaxAPRCapped_) {
            return maxReachedRate_ > 0 ? maxReachedRate_ : uint256(_slot1.maxReachedAPRCappedRate);
        }

        if (
            isRateBelowMaxReached_ &&
            (slot0_.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL == _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL)
        ) {
            // is _avoidForcedLiquidationsCol
            if (slot1_.maxReachedAPRCappedRate == 0) {
                slot1_ = _slot1;
            }

            return
                _calcDownCappedRate(
                    exchangeRate_,
                    maxReachedRate_ > 0 ? maxReachedRate_ : uint256(slot1_.maxReachedAPRCappedRate),
                    uint256(slot1_.maxDownFromMaxReachedPercentCol)
                );
        }

        return exchangeRate_;
    }

    /// @inheritdoc IFluidCappedRate
    function getExchangeRateOperateDebt() public view virtual returns (uint256 exchangeRate_) {
        // for debt -> up no cap, down capped (avoid underpricing exploit)
        Slot0 memory slot0_ = _slot0;

        Slot1 memory slot1_; // only read if needed

        uint256 maxReachedRate_;
        bool isRateBelowMaxReached_;

        if (_isHeartbeatTrigger(slot0_)) {
            slot1_ = _slot1;
            (exchangeRate_, maxReachedRate_, , isRateBelowMaxReached_) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
        } else {
            exchangeRate_ = uint256(slot0_.rate);
            isRateBelowMaxReached_ =
                slot0_.flags & _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED == _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED;
        }

        if (!isRateBelowMaxReached_) {
            return exchangeRate_;
        }

        if (slot1_.maxReachedAPRCappedRate == 0) {
            slot1_ = _slot1;
        }

        return
            _calcDownCappedRate(
                exchangeRate_,
                maxReachedRate_ > 0 ? maxReachedRate_ : uint256(slot1_.maxReachedAPRCappedRate),
                uint256(slot1_.maxDownFromMaxReachedPercentDebt)
            );
    }

    /// @inheritdoc IFluidCappedRate
    function getExchangeRateLiquidateDebt() public view virtual returns (uint256 exchangeRate_) {
        // for debt -> up max APR capped (avoid forced liquidations attack), down capped
        Slot0 memory slot0_ = _slot0;
        Slot1 memory slot1_; // only read if needed

        uint256 maxReachedRate_;
        bool isRateBelowMaxReached_;
        bool isUpMaxAPRCapped_;

        if (_isHeartbeatTrigger(slot0_)) {
            slot1_ = _slot1;
            (exchangeRate_, maxReachedRate_, isUpMaxAPRCapped_, isRateBelowMaxReached_) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
        } else {
            exchangeRate_ = uint256(slot0_.rate);
            isRateBelowMaxReached_ =
                slot0_.flags & _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED == _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED;
            isUpMaxAPRCapped_ = slot0_.flags & _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED == _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED;
        }

        if (
            isUpMaxAPRCapped_ &&
            (slot0_.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT ==
                _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT)
        ) {
            // is _avoidForcedLiquidationsDebt
            // case _rate > _maxReachedAPRCappedRate
            if (maxReachedRate_ == 0) {
                slot1_ = _slot1;
                maxReachedRate_ = uint256(slot1_.maxReachedAPRCappedRate);
            }
            // add max up cap percent on top
            maxReachedRate_ =
                (maxReachedRate_ * (_SIX_DECIMALS + uint256(slot1_.maxDebtUpCapPercent) * uint256(100))) /
                _SIX_DECIMALS;

            // return max(exchangeRate_, maxReachedRate_) where maxReachedRate_ is maxAPRReachedRate + maxDebtUpCapPercent on top
            return exchangeRate_ > maxReachedRate_ ? maxReachedRate_ : exchangeRate_;
        }

        if (!isRateBelowMaxReached_) {
            return exchangeRate_;
        }

        if (slot1_.maxReachedAPRCappedRate == 0) {
            slot1_ = _slot1;
        }

        return
            _calcDownCappedRate(
                exchangeRate_,
                maxReachedRate_ > 0 ? maxReachedRate_ : uint256(slot1_.maxReachedAPRCappedRate),
                uint256(slot1_.maxDownFromMaxReachedPercentDebt)
            );
    }

    /// @notice Rebalance the stored rates according to the newly fetched rate from the external source.
    /// @dev The rate is only updated if the difference between the current rate and the new rate is greater than or
    ///      equal to the minimum update difference percentage for either rate or maxRate OR if the heartbeat is reached
    function rebalance() external {
        _updateRates(_isHeartbeatTrigger(_slot0));
    }

    /// @notice Returns rates: capped and uncapped, and current cap status
    /// @return rate_ The rate_ value: last fetched value from external source with no cap up and no cap down as in storage
    /// @return maxReachedRate_ The maximum reached upward capped rate for col: within APR percent limit as in storage
    /// @return maxUpCappedRateDebt_ The maximum reached upward capped rate for debt: up to `maxReachedRate_` + `maxDebtUpCapPercent` on top
    /// @return isRateBelowMaxReached_ Indicates if the rate is currently below the maximum reached APR capped rate flag as in storage
    /// @return isUpMaxAPRCapped_ Indicates if the rate is currently capped due to exceeding the maximum APR limit flag as in storage
    /// @return downCappedRateCol_ The capped downward rate on col side
    /// @return downCappedRateDebt_ The capped downward rate on debt side
    /// @return isDownCappedCol_ Indicates if the rate is currently getting downward capped on col side
    /// @return isDownCappedDebt_ Indicates if the rate is currently getting downward capped on debt side
    /// @return isUpCapped_ Indicates if the rate is currently getting upward capped
    function getRatesAndCaps()
        public
        view
        returns (
            uint256 rate_,
            uint256 maxReachedRate_,
            uint256 maxUpCappedRateDebt_,
            bool isRateBelowMaxReached_,
            bool isUpMaxAPRCapped_,
            uint256 downCappedRateCol_,
            uint256 downCappedRateDebt_,
            bool isDownCappedCol_,
            bool isDownCappedDebt_,
            bool isUpCapped_
        )
    {
        Slot0 memory slot0_ = _slot0;
        Slot1 memory slot1_ = _slot1;

        if (_isHeartbeatTrigger(slot0_)) {
            (rate_, maxReachedRate_, isUpMaxAPRCapped_, isRateBelowMaxReached_) = _getUpdateRates(
                uint256(slot1_.maxReachedAPRCappedRate),
                slot0_,
                uint256(slot1_.maxAPRPercent)
            );
        } else {
            rate_ = uint256(slot0_.rate);
            maxReachedRate_ = uint256(slot1_.maxReachedAPRCappedRate);
            isRateBelowMaxReached_ =
                slot0_.flags & _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED == _FLAG_BITMASK_IS_RATE_BELOW_MAX_REACHED;
            isUpMaxAPRCapped_ = slot0_.flags & _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED == _FLAG_BITMASK_IS_UP_MAX_APR_CAPPED;
        }

        downCappedRateCol_ = _calcDownCappedRate(0, maxReachedRate_, uint256(slot1_.maxDownFromMaxReachedPercentCol));
        downCappedRateDebt_ = _calcDownCappedRate(0, maxReachedRate_, uint256(slot1_.maxDownFromMaxReachedPercentDebt));

        maxUpCappedRateDebt_ =
            (maxReachedRate_ * (_SIX_DECIMALS + uint256(slot1_.maxDebtUpCapPercent) * uint256(100))) /
            _SIX_DECIMALS;
        if (rate_ > maxReachedRate_ && rate_ < maxUpCappedRateDebt_) {
            // maxUpCappedRateDebt_ capped at + maxDebtUpCapPercent, but less if rate is less
            maxUpCappedRateDebt_ = rate_;
        }

        isDownCappedCol_ = rate_ < downCappedRateCol_;
        isDownCappedDebt_ = rate_ < downCappedRateDebt_;
        isUpCapped_ = rate_ > maxReachedRate_;
    }

    /// @notice returns how much the new rate OR new max rate would be different from current value in storage in percent (10000 = 1%, 1 = 0.0001%).
    function configPercentDiff() public view virtual returns (uint256 configPercentDiff_) {
        Slot0 memory slot0_ = _slot0;
        Slot1 memory slot1_ = _slot1;

        (uint256 newRate_, uint256 newMaxReachedRate_, , ) = _getUpdateRates(
            uint256(slot1_.maxReachedAPRCappedRate),
            slot0_,
            uint256(slot1_.maxAPRPercent)
        );

        uint256 rateDiff_ = _percentDiffForValue(uint256(slot0_.rate), newRate_);
        uint256 maxRateDiff_ = _percentDiffForValue(uint256(slot1_.maxReachedAPRCappedRate), newMaxReachedRate_);

        return rateDiff_ > maxRateDiff_ ? rateDiff_ : maxRateDiff_;
    }

    /// @notice returns all config vars, last update timestamp, and external rate source oracle address
    function configData()
        external
        view
        returns (
            address liquidity_,
            uint16 minUpdateDiffPercent_,
            uint24 minHeartbeat_,
            uint40 lastUpdateTime_,
            address rateSource_,
            bool invertCenterPrice_,
            bool avoidForcedLiquidationsCol_,
            bool avoidForcedLiquidationsDebt_,
            uint256 maxAPRPercent_,
            uint24 maxDownFromMaxReachedPercentCol_,
            uint24 maxDownFromMaxReachedPercentDebt_,
            uint256 maxDebtUpCapPercent_
        )
    {
        Slot0 memory slot0_ = _slot0;
        Slot1 memory slot1_ = _slot1;
        return (
            _LIQUIDITY,
            slot0_.minUpdateDiffPercent,
            slot0_.minHeartbeat,
            slot0_.lastUpdateTime,
            _RATE_SOURCE,
            _INVERT_CENTER_PRICE,
            (slot0_.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL) == _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_COL,
            (slot0_.flags & _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT) ==
                _FLAG_BITMASK_AVOID_FORCED_LIQUIDATIONS_DEBT,
            uint256(slot1_.maxAPRPercent) * uint256(100),
            slot1_.maxDownFromMaxReachedPercentCol,
            slot1_.maxDownFromMaxReachedPercentDebt,
            uint256(slot1_.maxDebtUpCapPercent) * uint256(100)
        );
    }

    /// @notice returns true if last update timestamp is > min heart time update time ago so heartbeat update should trigger
    function isHeartbeatTrigger() public view returns (bool) {
        return _isHeartbeatTrigger(_slot0);
    }
}

/// @notice This contract stores an exchange rate in intervals to optimize gas cost.
/// @notice Properly implements all interfaces for use as IFluidCenterPrice and IFluidOracle.
abstract contract FluidCappedRate is FluidCappedRateBase, FluidCenterPrice {
    constructor(
        CappedRateConstructorParams memory params_
    ) FluidCappedRateBase(params_) FluidCenterPrice(params_.infoName) {}

    /// @inheritdoc FluidCenterPrice
    function centerPrice() external override(IFluidCappedRate, FluidCenterPrice) returns (uint256 price_) {
        // for centerPrice -> no up cap, no down cap
        Slot0 memory slot0_ = _slot0;
        if (_isHeartbeatTrigger(slot0_)) {
            return _invertRateIfNeeded(_updateRates(true));
        }

        return _invertRateIfNeeded(uint256(slot0_.rate));
    }

    /// @inheritdoc FluidCenterPrice
    function infoName() public view override(IFluidOracle, FluidCenterPrice) returns (string memory) {
        return super.infoName();
    }

    /// @inheritdoc IFluidOracle
    function targetDecimals() public pure override(IFluidOracle, FluidCenterPrice) returns (uint8) {
        return _TARGET_DECIMALS;
    }
}

contracts/oracle/fluidCenterPrice.sol

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

import { IFluidCenterPrice } from "./interfaces/iFluidCenterPrice.sol";
import { ErrorTypes } from "./errorTypes.sol";
import { Error as OracleError } from "./error.sol";

/// @title   FluidCenterPrice
/// @notice  Base contract that any Fluid Center Price must implement
abstract contract FluidCenterPrice is IFluidCenterPrice, OracleError {
    /// @dev short helper string to easily identify the center price oracle. E.g. token symbols
    //
    // using a bytes32 because string can not be immutable.
    bytes32 private immutable _infoName;

    uint8 internal constant _TARGET_DECIMALS = 27; // target decimals for center price and contract rates is always 27

    constructor(string memory infoName_) {
        if (bytes(infoName_).length > 32 || bytes(infoName_).length == 0) {
            revert FluidOracleError(ErrorTypes.FluidOracle__InvalidInfoName);
        }

        // convert string to bytes32
        bytes32 infoNameBytes32_;
        assembly {
            infoNameBytes32_ := mload(add(infoName_, 32))
        }
        _infoName = infoNameBytes32_;
    }

    /// @inheritdoc IFluidCenterPrice
    function targetDecimals() public pure virtual returns (uint8) {
        return _TARGET_DECIMALS;
    }

    /// @inheritdoc IFluidCenterPrice
    function infoName() public view virtual returns (string memory) {
        // convert bytes32 to string
        uint256 length_;
        while (length_ < 32 && _infoName[length_] != 0) {
            length_++;
        }
        bytes memory infoNameBytes_ = new bytes(length_);
        for (uint256 i; i < length_; i++) {
            infoNameBytes_[i] = _infoName[i];
        }
        return string(infoNameBytes_);
    }

    /// @inheritdoc IFluidCenterPrice
    function centerPrice() external virtual returns (uint256 price_);
}

contracts/oracle/interfaces/iFluidCappedRate.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IFluidOracle } from "./iFluidOracle.sol";

interface IFluidCappedRate is IFluidOracle {
    /// @notice Get the operate() exchange rate for debt asset side, with no cap upwards and capped decrease
    function getExchangeRateOperateDebt() external view returns (uint256 exchangeRate_);

    /// @notice Get the liquidate() exchange rate for debt asset side, with max APR cap upwards, and capped decrease
    function getExchangeRateLiquidateDebt() external view returns (uint256 exchangeRate_);

    /// @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/oracle/interfaces/iFluidCenterPrice.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IFluidCenterPrice {
    /// @notice Retrieves the center price for the 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_);

    /// @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 rate. for center price contracts it is always 27
    function targetDecimals() external view returns (uint8);
}

contracts/oracle/interfaces/iFluidOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IFluidOracle {
    /// @dev Deprecated. Use `getExchangeRateOperate()` and `getExchangeRateLiquidate()` instead. Only implemented for
    ///      backwards compatibility.
    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 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);
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 10000000,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.