Skip to content
Verified contractPartialLGPL-3.0-only

ChainlinkCompositeOracle

Address0x679852bd4038863da1997bbdb8826daa5f87bc18
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
LGPL-3.0-only
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,377,086
Creation transaction
0x6c6a73c492…e1089ca928

src/oracles/ChainlinkCompositeOracle.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IReferenceOracle} from "../interfaces/oracles/IReferenceOracle.sol";
import {IChainlinkAggregatorV3} from "../interfaces/oracles/IChainlinkAggregatorV3.sol";
import {FullMath} from "../libraries/uniswap/FullMath.sol";

/// @title  ChainlinkCompositeOracle
/// @notice Prices TOKEN0 in TOKEN1 from two AggregatorV3-compatible feeds with independent freshness limits.
/// @dev    Each feed must quote the same numeraire per asset, for example
///         TOKEN0/USD and TOKEN1/USD. The adapter returns TOKEN1-per-TOKEN0:
///         `(TOKEN0/quote) / (TOKEN1/quote)`, scaled 1e18.
contract ChainlinkCompositeOracle is IReferenceOracle {
    // ─── Errors ──────────────────────────────────────────────────────────

    error ChainlinkCompositeOracle_ZeroAddress();
    error ChainlinkCompositeOracle_ZeroMaxAge();
    error ChainlinkCompositeOracle_BadFeedDecimals(uint8 decimals_);
    error ChainlinkCompositeOracle_BadRoundData(address feed, uint80 roundId, int256 answer, uint256 updatedAt);
    error ChainlinkCompositeOracle_AnswerScaleOverflow(address feed, uint256 answer, uint8 decimals_);
    error ChainlinkCompositeOracle_StaleFeed(address feed, uint256 updatedAt, uint256 maxAge);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice Chainlink feed for TOKEN0 quoted in the shared numeraire.
    IChainlinkAggregatorV3 public immutable TOKEN0_FEED;

    /// @notice Chainlink feed for TOKEN1 quoted in the shared numeraire.
    IChainlinkAggregatorV3 public immutable TOKEN1_FEED;

    /// @notice Decimals used by `TOKEN0_FEED`.
    uint8 public immutable TOKEN0_FEED_DECIMALS;

    /// @notice Decimals used by `TOKEN1_FEED`.
    uint8 public immutable TOKEN1_FEED_DECIMALS;

    /// @notice Maximum age of the TOKEN0 feed observation, in seconds (inclusive).
    uint256 public immutable TOKEN0_MAX_AGE;

    /// @notice Maximum age of the TOKEN1 feed observation, in seconds (inclusive).
    uint256 public immutable TOKEN1_MAX_AGE;

    uint256 internal constant PRICE_SCALE = 1e18;
    uint8 internal constant MAX_DECIMALS = 36;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Pin two same-numeraire feeds, answer decimals and independent freshness limits.
    /// @param token0Feed Chainlink feed for TOKEN0 in the shared numeraire.
    /// @param token1Feed Chainlink feed for TOKEN1 in the shared numeraire.
    /// @param token0MaxAge Positive maximum TOKEN0 observation age, in seconds.
    /// @param token1MaxAge Positive maximum TOKEN1 observation age, in seconds.
    constructor(
        IChainlinkAggregatorV3 token0Feed,
        IChainlinkAggregatorV3 token1Feed,
        uint256 token0MaxAge,
        uint256 token1MaxAge
    ) {
        if (address(token0Feed) == address(0) || address(token1Feed) == address(0)) {
            revert ChainlinkCompositeOracle_ZeroAddress();
        }
        if (token0MaxAge == 0 || token1MaxAge == 0) revert ChainlinkCompositeOracle_ZeroMaxAge();

        uint8 token0Decimals = token0Feed.decimals();
        uint8 token1Decimals = token1Feed.decimals();
        if (token0Decimals > MAX_DECIMALS) revert ChainlinkCompositeOracle_BadFeedDecimals(token0Decimals);
        if (token1Decimals > MAX_DECIMALS) revert ChainlinkCompositeOracle_BadFeedDecimals(token1Decimals);

        TOKEN0_FEED = token0Feed;
        TOKEN1_FEED = token1Feed;
        TOKEN0_FEED_DECIMALS = token0Decimals;
        TOKEN1_FEED_DECIMALS = token1Decimals;
        TOKEN0_MAX_AGE = token0MaxAge;
        TOKEN1_MAX_AGE = token1MaxAge;
    }

    // ─── IReferenceOracle ────────────────────────────────────────────────

    /// @inheritdoc IReferenceOracle
    function token0PriceInToken1() external view returns (uint256 priceX18, uint256 updatedAt) {
        (uint256 token0Answer, uint256 token0UpdatedAt) = _readFeed(TOKEN0_FEED, TOKEN0_MAX_AGE);
        (uint256 token1Answer, uint256 token1UpdatedAt) = _readFeed(TOKEN1_FEED, TOKEN1_MAX_AGE);

        uint256 numerator = _scaleAnswer(TOKEN0_FEED, token0Answer, TOKEN1_FEED_DECIMALS);
        uint256 denominator = _scaleAnswer(TOKEN1_FEED, token1Answer, TOKEN0_FEED_DECIMALS);

        priceX18 = FullMath.mulDiv(numerator, PRICE_SCALE, denominator);
        updatedAt = token0UpdatedAt < token1UpdatedAt ? token0UpdatedAt : token1UpdatedAt;
    }

    // ─── Internal helpers ────────────────────────────────────────────────

    /// @notice Read and validate the latest Chainlink round.
    /// @param feed Feed to read.
    /// @param maxAge Maximum observation age, in seconds (inclusive).
    /// @return answer Positive answer as uint256.
    /// @return updatedAt Feed update timestamp.
    function _readFeed(IChainlinkAggregatorV3 feed, uint256 maxAge)
        internal
        view
        returns (uint256 answer, uint256 updatedAt)
    {
        (uint80 roundId, int256 rawAnswer,, uint256 rawUpdatedAt, uint80 answeredInRound) = feed.latestRoundData();
        // Check each leg before selecting the oldest timestamp.
        // forge-lint: disable-next-line(block-timestamp)
        if (rawAnswer <= 0 || rawUpdatedAt == 0 || rawUpdatedAt > block.timestamp || answeredInRound < roundId) {
            revert ChainlinkCompositeOracle_BadRoundData(address(feed), roundId, rawAnswer, rawUpdatedAt);
        }
        // forge-lint: disable-next-line(block-timestamp)
        if (block.timestamp - rawUpdatedAt > maxAge) {
            revert ChainlinkCompositeOracle_StaleFeed(address(feed), rawUpdatedAt, maxAge);
        }
        // Positive `int256` is safe to narrow to uint256.
        // forge-lint: disable-next-line(unsafe-typecast)
        return (uint256(rawAnswer), rawUpdatedAt);
    }

    /// @notice Scale a positive answer by `10 ** decimals_`.
    /// @param feed Feed used for error context.
    /// @param answer Positive answer.
    /// @param decimals_ Decimals to apply.
    /// @return scaled Scaled answer.
    function _scaleAnswer(IChainlinkAggregatorV3 feed, uint256 answer, uint8 decimals_)
        internal
        pure
        returns (uint256 scaled)
    {
        uint256 scale = 10 ** uint256(decimals_);
        if (answer > type(uint256).max / scale) {
            revert ChainlinkCompositeOracle_AnswerScaleOverflow(address(feed), answer, decimals_);
        }
        scaled = answer * scale;
    }
}

src/interfaces/oracles/IChainlinkAggregatorV3.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  IChainlinkAggregatorV3
/// @notice Minimal Chainlink AggregatorV3 interface used by reference adapters.
/// @dev ABI-compatible subset, also implemented by Bound's synthetic share-rate
///      adapter. Round completion alone does not establish positivity or freshness.
interface IChainlinkAggregatorV3 {
    /// @notice Feed decimals.
    /// @return decimals_ Number of decimals used by answers.
    function decimals() external view returns (uint8 decimals_);

    /// @notice Latest feed round data.
    /// @dev Consumers validate the answer and observation age. A synthetic
    ///      adapter may use read time instead of an independently dated report.
    /// @return roundId Round identifier.
    /// @return answer Signed answer in units scaled by `decimals()`.
    /// @return startedAt Round start Unix timestamp.
    /// @return updatedAt Observation Unix timestamp.
    /// @return answeredInRound Round in which the answer was computed.
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

src/interfaces/oracles/IReferenceOracle.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  IReferenceOracle
/// @notice External TOKEN1-per-TOKEN0 reference used for Bound valuations.
/// @dev Prices use whole-token units scaled by 1e18, independent of token atom
///      decimals. The interface exposes no token identity or source methodology;
///      deployment review must establish orientation, units and independence
///      from the execution venue. Composed feeds report their oldest observation.
///      Live-state adapters may report the current block time, which does not
///      establish freshness of the underlying valuation.
interface IReferenceOracle {
    /// @notice Reference price of TOKEN0 in TOKEN1, scaled 1e18.
    /// @dev Consumers validate positivity, non-future timestamps and their own
    ///      maximum observation age. External failures may revert the read.
    /// @return priceX18   TOKEN1-per-TOKEN0, fixed point 1e18 (> 0 when healthy).
    /// @return updatedAt Source observation timestamp, or read time for a documented live-state adapter.
    function token0PriceInToken1() external view returns (uint256 priceX18, uint256 updatedAt);
}

src/libraries/uniswap/FullMath.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an
///         intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division
///      where an intermediate value overflows 256 bits
///
///      Ported from Uniswap v3-core `FullMath` (originally Solidity 0.7, where
///      arithmetic wrapped by default). Under 0.8.x the entire body is wrapped in
///      a single `unchecked` block so the deliberate modular-arithmetic
///      identities (the 512-bit long division) keep their original wrapping
///      semantics. Do NOT "simplify" the bit-twiddling — it is exact by design.
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if
    ///         result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if
    ///         result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.