PriceOracle

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/access/AccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

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

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}
"
    },
    "@openzeppelin/contracts/access/IAccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "@openzeppelin/contracts/utils/introspection/ERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
"
    },
    "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "contracts/interfaces/IPriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

struct PriceData {
    uint256 price;
    uint256 timestamp;
    uint256 roundId;
    bool isValid;
}

interface IPriceOracle {
    event ManualPriceSet(uint256 price, uint256 timestamp, address setter);

    function getReliablePrice() external view returns (uint256 price, uint256 timestamp, address source);
    function getPriceFromSource(address source) external view returns (PriceData memory);
    function isSourceHealthy(address source) external view returns (bool);
    function setManualPrice(uint256 price) external;
    function addPriceSource(address source, bool isChainlink) external;
    function removePriceSource(address source) external;
}
"
    },
    "contracts/libraries/PrecisionMath.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

library PrecisionMath {
    uint256 internal constant PRECISION = 10**18;
    
    function toInternal(uint256 value, uint8 decimals) internal pure returns (uint256) {
        if (decimals == 18) return value;
        if (decimals > 18) return value / (10**(decimals - 18));
        return value * (10**(18 - decimals));
    }
    
    function isWithinDeviation(uint256 price1, uint256 price2, uint256 bps) internal pure returns (bool) {
        uint256 higher = price1 > price2 ? price1 : price2;
        uint256 lower = price1 > price2 ? price2 : price1;
        uint256 deviation = ((higher - lower) * 10000) / higher;
        return deviation <= bps;
    }
    
    function mulDiv(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
        return (a * b) / c;
    }
}
"
    },
    "contracts/PriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.20;\r
\r
import "@openzeppelin/contracts/access/AccessControl.sol";\r
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";\r
import "./interfaces/IPriceOracle.sol";\r
import "./libraries/PrecisionMath.sol";\r
\r
interface AggregatorV3Interface {\r
    function latestRoundData() external view returns (\r
        uint80 roundId,\r
        int256 answer,\r
        uint256 startedAt,\r
        uint256 updatedAt,\r
        uint80 answeredInRound\r
    );\r
    function decimals() external view returns (uint8);\r
}\r
\r
interface IUniswapV3Pool {\r
    function observe(uint32[] calldata secondsAgos)\r
        external\r
        view\r
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\r
    \r
    function slot0()\r
        external\r
        view\r
        returns (\r
            uint160 sqrtPriceX96,\r
            int24 tick,\r
            uint16 observationIndex,\r
            uint16 observationCardinality,\r
            uint16 observationCardinalityNext,\r
            uint8 feeProtocol,\r
            bool unlocked\r
        );\r
}\r
\r
/**\r
 * @title PriceOracle\r
 * @dev Multi-source price oracle with fallback mechanisms\r
 * @notice Provides reliable ETH/USD prices with multiple data sources\r
 */\r
contract PriceOracle is IPriceOracle, AccessControl, ReentrancyGuard {\r
    using PrecisionMath for uint256;\r
    \r
    bytes32 public constant ORACLE_ADMIN_ROLE = keccak256("ORACLE_ADMIN_ROLE");\r
    bytes32 public constant PRICE_SETTER_ROLE = keccak256("PRICE_SETTER_ROLE");\r
    \r
    struct PriceSource {\r
        address source;\r
        bool isChainlink;\r
        bool isActive;\r
        uint256 priority; // Lower number = higher priority\r
        uint256 lastUpdate;\r
        uint256 lastPrice;\r
    }\r
    \r
    // Configuration\r
    uint256 public constant MAX_PRICE_DEVIATION_BPS = 1000; // 10% max deviation\r
    uint256 public constant PRICE_STALENESS_THRESHOLD = 3600; // 1 hour\r
    uint256 public constant TWAP_PERIOD = 1800; // 30 minutes\r
    uint256 public constant MIN_PRICE = 100 * 10**18; // $100 minimum\r
    uint256 public constant MAX_PRICE = 10000 * 10**18; // $10,000 maximum\r
    \r
    // State variables\r
    mapping(address => PriceSource) public priceSources;\r
    address[] public sourceList;\r
    uint256 public manualPrice;\r
    uint256 public manualPriceTimestamp;\r
    bool public manualPriceActive;\r
    \r
    // Events\r
    event SourceAdded(address indexed source, bool isChainlink, uint256 priority);\r
    event SourceRemoved(address indexed source);\r
    event SourceStatusChanged(address indexed source, bool isActive);\r
    event PriceDeviationDetected(address indexed source1, address indexed source2, uint256 deviation);\r
    \r
    constructor() {\r
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);\r
        _grantRole(ORACLE_ADMIN_ROLE, msg.sender);\r
        _grantRole(PRICE_SETTER_ROLE, msg.sender);\r
    }\r
    \r
    /**\r
     * @dev Get the most reliable price from available sources\r
     */\r
    function getReliablePrice() external view override returns (uint256 price, uint256 timestamp, address source) {\r
        // Check if manual price is active and recent\r
        if (manualPriceActive && \r
            block.timestamp - manualPriceTimestamp <= PRICE_STALENESS_THRESHOLD) {\r
            return (manualPrice, manualPriceTimestamp, address(this));\r
        }\r
        \r
        // Try to get price from active sources in priority order\r
        PriceData memory primaryPrice;\r
        PriceData memory secondaryPrice;\r
        address primarySource;\r
        address secondarySource;\r
        \r
        // Find two best available prices\r
        for (uint256 i = 0; i < sourceList.length; i++) {\r
            address sourceAddr = sourceList[i];\r
            PriceSource memory sourceInfo = priceSources[sourceAddr];\r
            \r
            if (!sourceInfo.isActive) continue;\r
            \r
            PriceData memory priceData = _getPriceFromSource(sourceAddr, sourceInfo);\r
            \r
            if (!priceData.isValid) continue;\r
            \r
            if (primaryPrice.price == 0) {\r
                primaryPrice = priceData;\r
                primarySource = sourceAddr;\r
            } else if (secondaryPrice.price == 0) {\r
                secondaryPrice = priceData;\r
                secondarySource = sourceAddr;\r
                break;\r
            }\r
        }\r
        \r
        require(primaryPrice.price > 0, "No valid price available");\r
        \r
        // If we have two prices, validate they're within acceptable deviation\r
        if (secondaryPrice.price > 0) {\r
            if (PrecisionMath.isWithinDeviation(\r
                primaryPrice.price, \r
                secondaryPrice.price, \r
                MAX_PRICE_DEVIATION_BPS\r
            )) {\r
                // Use the more recent price\r
                if (primaryPrice.timestamp >= secondaryPrice.timestamp) {\r
                    return (primaryPrice.price, primaryPrice.timestamp, primarySource);\r
                } else {\r
                    return (secondaryPrice.price, secondaryPrice.timestamp, secondarySource);\r
                }\r
            } else {\r
                // Prices deviate too much, use primary (cannot emit in view function)\r
                // Note: Price deviation detected but not logged in view function\r
            }\r
        }\r
        \r
        return (primaryPrice.price, primaryPrice.timestamp, primarySource);\r
    }\r
    \r
    /**\r
     * @dev Get price from specific source\r
     */\r
    function getPriceFromSource(address source) external view override returns (PriceData memory) {\r
        PriceSource memory sourceInfo = priceSources[source];\r
        require(sourceInfo.source != address(0), "Source not found");\r
        return _getPriceFromSource(source, sourceInfo);\r
    }\r
    \r
    /**\r
     * @dev Check if a price source is healthy\r
     */\r
    function isSourceHealthy(address source) external view override returns (bool) {\r
        PriceSource memory sourceInfo = priceSources[source];\r
        if (!sourceInfo.isActive || sourceInfo.source == address(0)) {\r
            return false;\r
        }\r
        \r
        PriceData memory priceData = _getPriceFromSource(source, sourceInfo);\r
        return priceData.isValid;\r
    }\r
    \r
    /**\r
     * @dev Set manual price (emergency use only)\r
     */\r
    function setManualPrice(uint256 price) external override onlyRole(PRICE_SETTER_ROLE) {\r
        require(price >= MIN_PRICE && price <= MAX_PRICE, "Price out of bounds");\r
        \r
        manualPrice = price;\r
        manualPriceTimestamp = block.timestamp;\r
        manualPriceActive = true;\r
        \r
        emit ManualPriceSet(price, block.timestamp, msg.sender);\r
    }\r
    \r
    /**\r
     * @dev Disable manual price\r
     */\r
    function disableManualPrice() external onlyRole(ORACLE_ADMIN_ROLE) {\r
        manualPriceActive = false;\r
    }\r
    \r
    /**\r
     * @dev Add a new price source\r
     */\r
    function addPriceSource(address source, bool isChainlink) external override onlyRole(ORACLE_ADMIN_ROLE) {\r
        require(source != address(0), "Invalid source address");\r
        require(priceSources[source].source == address(0), "Source already exists");\r
        \r
        uint256 priority = sourceList.length;\r
        \r
        priceSources[source] = PriceSource({\r
            source: source,\r
            isChainlink: isChainlink,\r
            isActive: true,\r
            priority: priority,\r
            lastUpdate: 0,\r
            lastPrice: 0\r
        });\r
        \r
        sourceList.push(source);\r
        \r
        emit SourceAdded(source, isChainlink, priority);\r
    }\r
    \r
    /**\r
     * @dev Remove a price source\r
     */\r
    function removePriceSource(address source) external override onlyRole(ORACLE_ADMIN_ROLE) {\r
        require(priceSources[source].source != address(0), "Source not found");\r
        \r
        // Remove from sourceList\r
        for (uint256 i = 0; i < sourceList.length; i++) {\r
            if (sourceList[i] == source) {\r
                sourceList[i] = sourceList[sourceList.length - 1];\r
                sourceList.pop();\r
                break;\r
            }\r
        }\r
        \r
        delete priceSources[source];\r
        \r
        emit SourceRemoved(source);\r
    }\r
    \r
    /**\r
     * @dev Toggle source active status\r
     */\r
    function setSourceStatus(address source, bool isActive) external onlyRole(ORACLE_ADMIN_ROLE) {\r
        require(priceSources[source].source != address(0), "Source not found");\r
        \r
        priceSources[source].isActive = isActive;\r
        \r
        emit SourceStatusChanged(source, isActive);\r
    }\r
    \r
    /**\r
     * @dev Internal function to get price from a source\r
     */\r
    function _getPriceFromSource(address source, PriceSource memory sourceInfo) \r
        internal view returns (PriceData memory) {\r
        \r
        if (sourceInfo.isChainlink) {\r
            return _getChainlinkPrice(source);\r
        } else {\r
            return _getUniswapPrice(source);\r
        }\r
    }\r
    \r
    /**\r
     * @dev Get price from Chainlink aggregator\r
     */\r
    function _getChainlinkPrice(address aggregator) internal view returns (PriceData memory) {\r
        try AggregatorV3Interface(aggregator).latestRoundData() returns (\r
            uint80 roundId,\r
            int256 price,\r
            uint256 /* startedAt */,\r
            uint256 updatedAt,\r
            uint80 answeredInRound\r
        ) {\r
            if (price <= 0 || \r
                answeredInRound < roundId || \r
                block.timestamp - updatedAt > PRICE_STALENESS_THRESHOLD) {\r
                return PriceData(0, 0, 0, false);\r
            }\r
            \r
            // Convert from Chainlink decimals (8) to internal decimals (18)\r
            uint256 priceConverted = PrecisionMath.toInternal(uint256(price), 8);\r
            \r
            return PriceData(priceConverted, updatedAt, roundId, true);\r
            \r
        } catch {\r
            return PriceData(0, 0, 0, false);\r
        }\r
    }\r
    \r
    /**\r
     * @dev Get TWAP price from Uniswap V3 pool\r
     */\r
    function _getUniswapPrice(address pool) internal view returns (PriceData memory) {\r
        try IUniswapV3Pool(pool).observe(_getTwapPeriods()) returns (\r
            int56[] memory tickCumulatives,\r
            uint160[] memory\r
        ) {\r
            int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\r
            int24 tick = int24(tickCumulativesDelta / int56(uint56(TWAP_PERIOD)));\r
            \r
            // Convert tick to price (simplified - would need proper tick math in production)\r
            uint256 price = _tickToPrice(tick);\r
            \r
            if (price < MIN_PRICE || price > MAX_PRICE) {\r
                return PriceData(0, 0, 0, false);\r
            }\r
            \r
            return PriceData(price, block.timestamp, 0, true);\r
            \r
        } catch {\r
            return PriceData(0, 0, 0, false);\r
        }\r
    }\r
    \r
    /**\r
     * @dev Get TWAP observation periods\r
     */\r
    function _getTwapPeriods() internal pure returns (uint32[] memory) {\r
        uint32[] memory periods = new uint32[](2);\r
        periods[0] = uint32(TWAP_PERIOD);\r
        periods[1] = 0;\r
        return periods;\r
    }\r
    \r
    /**\r
     * @dev Convert Uniswap tick to price (simplified implementation)\r
     * @dev In production, use proper tick math library\r
     */\r
    function _tickToPrice(int24 tick) internal pure returns (uint256) {\r
        // Simplified tick to price conversion\r
        // In production, use: price = (1.0001^tick) * (10^(token1Decimals - token0Decimals))\r
        if (tick < 0) {\r
            return MIN_PRICE; // Fallback for negative ticks\r
        }\r
        \r
        // Approximate conversion for demonstration\r
        uint256 price = uint256(uint24(tick)) * 10**15; // Rough approximation\r
        \r
        if (price < MIN_PRICE) return MIN_PRICE;\r
        if (price > MAX_PRICE) return MAX_PRICE;\r
        \r
        return price;\r
    }\r
    \r
    /**\r
     * @dev Calculate deviation between two prices in basis points\r
     */\r
    function _calculateDeviation(uint256 price1, uint256 price2) internal pure returns (uint256) {\r
        uint256 higher = price1 > price2 ? price1 : price2;\r
        uint256 lower = price1 > price2 ? price2 : price1;\r
        \r
        return PrecisionMath.mulDiv(higher - lower, 10000, higher);\r
    }\r
    \r
    /**\r
     * @dev Get all active sources\r
     */\r
    function getActiveSources() external view returns (address[] memory) {\r
        uint256 activeCount = 0;\r
        \r
        // Count active sources\r
        for (uint256 i = 0; i < sourceList.length; i++) {\r
            if (priceSources[sourceList[i]].isActive) {\r
                activeCount++;\r
            }\r
        }\r
        \r
        // Build active sources array\r
        address[] memory activeSources = new address[](activeCount);\r
        uint256 index = 0;\r
        \r
        for (uint256 i = 0; i < sourceList.length; i++) {\r
            if (priceSources[sourceList[i]].isActive) {\r
                activeSources[index] = sourceList[i];\r
                index++;\r
            }\r
        }\r
        \r
        return activeSources;\r
    }\r
}\r
"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "evmVersion": "paris",
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  }
}}

Tags:
ERC165, Proxy, Upgradeable, Factory, Oracle|addr:0xe3742350d6294f2b6a0a14072e11f06e23734860|verified:true|block:23430123|tx:0x950719f5cec63dee084b263ccd4d87c9b49fd86a12b763c3ce1b533ec2bd8172|first_check:1758731866

Submitted on: 2025-09-24 18:37:51

Comments

Log in to comment.

No comments yet.