FxUSDPriceOracle

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "settings": {
    "evmVersion": "cancun",
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "remappings": [
      "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
      "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
      "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
      "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/contracts-upgradeable@5.4.0/"
    ]
  },
  "sources": {
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/access/AccessControlUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

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

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /// @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) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        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) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        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 {
        AccessControlStorage storage $ = _getAccessControlStorage();
        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) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        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) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}
"
    },
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}
"
    },
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/utils/ContextUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}
"
    },
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/utils/introspection/ERC165Upgradeable.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 "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
"
    },
    "npm/@openzeppelin/contracts@5.4.0/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;
}
"
    },
    "npm/@openzeppelin/contracts@5.4.0/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);
}
"
    },
    "project/contracts/core/FxUSDPriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";

import { AggregatorV3Interface } from "../interfaces/Chainlink/AggregatorV3Interface.sol";
import { ICurveStableSwapNG } from "../interfaces/Curve/ICurveStableSwapNG.sol";
import { IFxUSDPriceOracle } from "../interfaces/IFxUSDPriceOracle.sol";

contract FxUSDPriceOracle is AccessControlUpgradeable, IFxUSDPriceOracle {
  /**********
   * Errors *
   **********/

  /// @dev Thrown when the address is zero address.
  error ErrorZeroAddress();

  /*************
   * Constants *
   *************/

  /// @dev The precision used to compute nav.
  uint256 private constant PRECISION = 1e18;

  /***********************
   * Immutable Variables *
   ***********************/

  /// @notice The fxUSD token.
  address public immutable fxUSD;

  /// @notice The Chainlink USDC/USD price feed.
  /// @dev The encoding is below.
  /// ```text
  /// |  32 bits  | 64 bits |  160 bits  |
  /// | heartbeat |  scale  | price_feed |
  /// |low                          high |
  /// ```
  bytes32 public immutable Chainlink_USDC_USD_Spot;

  /*********************
   * Storage Variables *
   *********************/

  /// @notice The curve pool for stable and fxUSD
  address public curvePool;

  /// @notice The fxUSD depeg price threshold.
  uint256 public maxDePegPriceDeviation;

  /// @notice The max price deviation for up peg.
  uint256 public maxUpPegPriceDeviation;

  /***************
   * Constructor *
   ***************/

  /// @notice Constructor.
  /// @param _fxUSD The address of the fxUSD token.
  constructor(address _fxUSD, bytes32 _Chainlink_USDC_USD_Spot) {
    fxUSD = _fxUSD;
    Chainlink_USDC_USD_Spot = _Chainlink_USDC_USD_Spot;
  }

  /// @notice Initialize the contract storage.
  /// @param admin The address of the admin.
  /// @param _curvePool The address of the curve pool.
  function initialize(address admin, address _curvePool) external initializer {
    __Context_init();
    __AccessControl_init();
    __ERC165_init();

    _grantRole(DEFAULT_ADMIN_ROLE, admin);

    _updateCurvePool(_curvePool);
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc IFxUSDPriceOracle
  function getUSDCPrice() external view returns (uint256) {
    return _readUSDCPriceByChainlink();
  }

  /// @inheritdoc IFxUSDPriceOracle
  function getPrice() external view returns (bool isPegged, uint256 price) {
    price = _getFxUSDEmaPrice();
    isPegged = price >= PRECISION - maxDePegPriceDeviation && price <= PRECISION + maxUpPegPriceDeviation;
  }

  /// @inheritdoc IFxUSDPriceOracle
  function isPriceAboveMaxDeviation() external view returns (bool) {
    return _getFxUSDEmaPrice() > PRECISION + maxUpPegPriceDeviation;
  }

  /// @inheritdoc IFxUSDPriceOracle
  function isPriceBelowMaxDeviation() external view returns (bool) {
    return _getFxUSDEmaPrice() < PRECISION - maxDePegPriceDeviation;
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @notice Update the address of curve pool.
  /// @param newPool The address of curve pool.
  function updateCurvePool(address newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateCurvePool(newPool);
  }

  /// @notice Update the value of depeg/uppeg price threshold.
  /// @param newDePegDeviation The value of new depeg price threshold.
  /// @param newUpPegDeviation The value of new up peg price threshold.
  function updateMaxPriceDeviation(
    uint256 newDePegDeviation,
    uint256 newUpPegDeviation
  ) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateMaxPriceDeviation(newDePegDeviation, newUpPegDeviation);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to get curve ema price for fxUSD.
  /// @return price The value of ema price, multiplied by 1e18.
  function _getFxUSDEmaPrice() internal view returns (uint256 price) {
    address cachedCurvePool = curvePool; // gas saving
    address firstCoin = ICurveStableSwapNG(cachedCurvePool).coins(0);
    price = ICurveStableSwapNG(cachedCurvePool).price_oracle(0);
    if (firstCoin == fxUSD) {
      price = (PRECISION * PRECISION) / price;
    }

    // The price is in USDC, so we need to convert it to USD
    price = (_readUSDCPriceByChainlink() * price) / PRECISION;
  }

  /// @dev Internal function to update the address of curve pool.
  /// @param newPool The address of curve pool.
  function _updateCurvePool(address newPool) internal {
    if (newPool == address(0)) revert ErrorZeroAddress();

    address oldPool = curvePool;
    curvePool = newPool;

    emit UpdateCurvePool(oldPool, newPool);
  }

  /// @dev Internal function to update the value of max price deviation.
  /// @param newDePegDeviation The value of new depeg price deviation.
  /// @param newUpPegDeviation The value of new up peg price deviation.
  function _updateMaxPriceDeviation(uint256 newDePegDeviation, uint256 newUpPegDeviation) internal {
    uint256 oldDePegDeviation = maxDePegPriceDeviation;
    uint256 oldUpPegDeviation = maxUpPegPriceDeviation;
    maxDePegPriceDeviation = newDePegDeviation;
    maxUpPegPriceDeviation = newUpPegDeviation;

    emit UpdateMaxPriceDeviation(oldDePegDeviation, oldUpPegDeviation, newDePegDeviation, newUpPegDeviation);
  }

  /// @dev Internal function to read the USDC/USD price from Chainlink.
  function _readUSDCPriceByChainlink() internal view returns (uint256) {
    bytes32 encoding = Chainlink_USDC_USD_Spot;
    address aggregator;
    uint256 scale;
    uint256 heartbeat;
    assembly {
      aggregator := shr(96, encoding)
      scale := and(shr(32, encoding), 0xffffffffffffffff)
      heartbeat := and(encoding, 0xffffffff)
    }
    (, int256 answer, , uint256 updatedAt, ) = AggregatorV3Interface(aggregator).latestRoundData();
    if (answer < 0) revert("invalid");
    if (block.timestamp - updatedAt > heartbeat) revert("expired");
    return uint256(answer) * scale;
  }
}
"
    },
    "project/contracts/interfaces/Chainlink/AggregatorV3Interface.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function latestAnswer() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}
"
    },
    "project/contracts/interfaces/Curve/ICurveStableSwapNG.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ICurveStableSwapNG {
  /*************************
   * Public View Functions *
   *************************/

  function coins(uint256 index) external view returns (address);

  function last_price(uint256 index) external view returns (uint256);

  function ema_price(uint256 index) external view returns (uint256);

  /// @notice Returns the AMM State price of token
  /// @dev if i = 0, it will return the state price of coin[1].
  /// @param i index of state price (0 for coin[1], 1 for coin[2], ...)
  /// @return uint256 The state price quoted by the AMM for coin[i+1]
  function get_p(uint256 i) external view returns (uint256);

  function price_oracle(uint256 index) external view returns (uint256);

  function D_oracle() external view returns (uint256);

  function A() external view returns (uint256);

  function A_precise() external view returns (uint256);

  /// @notice Calculate the current input dx given output dy
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dy Amount of `j` being received after exchange
  /// @return Amount of `i` predicted
  function get_dx(
    int128 i,
    int128 j,
    uint256 dy
  ) external view returns (uint256);

  /// @notice Calculate the current output dy given input dx
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @return Amount of `j` predicted
  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  /// @notice Calculate the amount received when withdrawing a single coin
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @return Amount of coin received
  function calc_withdraw_one_coin(uint256 burn_amount, int128 i) external view returns (uint256);

  /// @notice The current virtual price of the pool LP token
  /// @dev Useful for calculating profits.
  ///      The method may be vulnerable to donation-style attacks if implementation
  ///      contains rebasing tokens. For integrators, caution is advised.
  /// @return LP token virtual price normalized to 1e18
  function get_virtual_price() external view returns (uint256);

  /// @notice Calculate addition or reduction in token supply from a deposit or withdrawal
  /// @param amounts Amount of each coin being deposited
  /// @param is_deposit set True for deposits, False for withdrawals
  /// @return Expected amount of LP tokens received
  function calc_token_amount(uint256[] calldata amounts, bool is_deposit) external view returns (uint256);

  /// @notice Get the current balance of a coin within the
  ///         pool, less the accrued admin fees
  /// @param i Index value for the coin to query balance of
  /// @return Token balance
  function balances(uint256 i) external view returns (uint256);

  function get_balances() external view returns (uint256[] memory);

  function stored_rates() external view returns (uint256[] memory);

  /// @notice Return the fee for swapping between `i` and `j`
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @return Swap fee expressed as an integer with 1e10 precision
  function dynamic_fee(int128 i, int128 j) external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Perform an exchange between two coins
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @return Actual amount of `j` received
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @param receiver Address that receives `j`
  /// @return Actual amount of `j` received
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy,
    address receiver
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins without transferring token in
  /// @dev The contract swaps tokens based on a change in balance of coin[i]. The
  ///      dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
  ///      this method are dex aggregators, arbitrageurs, or other users who do not
  ///      wish to grant approvals to the contract: they would instead send tokens
  ///      directly to the contract and call `exchange_received`.
  ///      Note: This is disabled if pool contains rebasing tokens.
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @return Actual amount of `j` received
  function exchange_received(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins without transferring token in
  /// @dev The contract swaps tokens based on a change in balance of coin[i]. The
  ///      dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
  ///      this method are dex aggregators, arbitrageurs, or other users who do not
  ///      wish to grant approvals to the contract: they would instead send tokens
  ///      directly to the contract and call `exchange_received`.
  ///      Note: This is disabled if pool contains rebasing tokens.
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @param receiver Address that receives `j`
  /// @return Actual amount of `j` received
  function exchange_received(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy,
    address receiver
  ) external returns (uint256);

  /// @notice Deposit coins into the pool
  /// @param amounts List of amounts of coins to deposit
  /// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
  /// @return Amount of LP tokens received by depositing
  function add_liquidity(uint256[] calldata amounts, uint256 min_mint_amount) external returns (uint256);

  /// @notice Deposit coins into the pool
  /// @param amounts List of amounts of coins to deposit
  /// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
  /// @param receiver Address that owns the minted LP tokens
  /// @return Amount of LP tokens received by depositing
  function add_liquidity(
    uint256[] calldata amounts,
    uint256 min_mint_amount,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw a single coin from the pool
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @param min_received Minimum amount of coin to receive
  /// @return Amount of coin received
  function remove_liquidity_one_coin(
    uint256 burn_amount,
    int128 i,
    uint256 min_received
  ) external returns (uint256);

  /// @notice Withdraw a single coin from the pool
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @param min_received Minimum amount of coin to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return Amount of coin received
  function remove_liquidity_one_coin(
    uint256 burn_amount,
    int128 i,
    uint256 min_received,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw coins from the pool in an imbalanced amount
  /// @param amounts List of amounts of underlying coins to withdraw
  /// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
  /// @return Actual amount of the LP token burned in the withdrawal
  function remove_liquidity_imbalance(uint256[] calldata amounts, uint256 max_burn_amount) external returns (uint256);

  /// @notice Withdraw coins from the pool in an imbalanced amount
  /// @param amounts List of amounts of underlying coins to withdraw
  /// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
  /// @param receiver Address that receives the withdrawn coins
  /// @return Actual amount of the LP token burned in the withdrawal
  function remove_liquidity_imbalance(
    uint256[] calldata amounts,
    uint256 max_burn_amount,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(uint256 burn_amount, uint256[] calldata min_amounts) external returns (uint256[] memory);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(
    uint256 burn_amount,
    uint256[] calldata min_amounts,
    address receiver
  ) external returns (uint256[] memory);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(
    uint256 burn_amount,
    uint256[] calldata min_amounts,
    address receiver,
    bool claim_admin_fees
  ) external returns (uint256[] memory);

  /// @notice Claim admin fees. Callable by anyone.
  function withdraw_admin_fees() external;
}
"
    },
    "project/contracts/interfaces/IFxUSDPriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IFxUSDPriceOracle {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the curve pool contract is updated.
  /// @param oldPool The address of previous curve pool contract.
  /// @param newPool The address of current curve pool contract.
  event UpdateCurvePool(address indexed oldPool, address indexed newPool);

  /// @notice Emitted when the max price deviation is updated.
  /// @param oldDePegDeviation The value of previous depeg price deviation
  /// @param oldUpPegDeviation The value of previous up peg price deviation
  /// @param newDePegDeviation The value of current depeg price deviation
  /// @param newUpPegDeviation The value of current up peg price deviation
  event UpdateMaxPriceDeviation(
    uint256 oldDePegDeviation,
    uint256 oldUpPegDeviation,
    uint256 newDePegDeviation,
    uint256 newUpPegDeviation
  );

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Get the current price of USDC
  /// @return price The current price of USDC in USD, multiplied by 1e18
  function getUSDCPrice() external view returns (uint256);

  /// @notice Get the current price of FXUSD
  /// @return isPegged Whether the price is currently pegged to 1 USD
  /// @return price The current price of FXUSD in USD, multiplied by 1e18
  function getPrice() external view returns (bool isPegged, uint256 price);

  /// @notice Check if the current price is above the maximum allowed deviation from 1 USD
  /// @return True if the price is above the maximum deviation threshold, false otherwise
  function isPriceAboveMaxDeviation() external view returns (bool);

  /// @notice Check if the current price is below the maximum allowed deviation from 1 USD
  /// @return True if the price is below the maximum deviation threshold, false otherwise
  function isPriceBelowMaxDeviation() external view returns (bool);
}
"
    }
  }
}}

Tags:
ERC165, Multisig, Swap, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x12be1e1e1f4632f68a78e0ea0247d7e3c2dbc8aa|verified:true|block:23697799|tx:0x2625790bc6237d4e7cc9f8343d74a77020dc83770407442610954fe23d9c682b|first_check:1761922914

Submitted on: 2025-10-31 16:01:55

Comments

Log in to comment.

No comments yet.