Skip to content
Verified contractExactMIT

OracleAggregator

Address0x0425572d9b8bc48fe282d4fcdadbd39a02371d87
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,022,851
Creation transaction
0x70dc9ac91e…cf4ef14e82

ZSystemFlorGain.sol/OracleAgg.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./Interfaces.sol";

contract OracleAggregator is Initializable, IOracleAggregator {
    uint256 public constant WAD = 1e18;
    uint256 public constant ORACLE_STALENESS_THRESHOLD = 15 minutes;

    AggregatorV3Interface public primaryOracle;
    AggregatorV3Interface public secondaryOracle;

    uint256 public oracleToleranceWad;
    uint256 public cachedEthPrice18;
    uint256 public cachedEthPriceUpdatedAt;
    uint256 public cacheExpiry;
    uint256 public priceHaircutWad;

    event OracleState(PriceConfidence confidence, uint256 price18, uint256 age);

    function initialize(
        address _primary,
        address _secondary,
        uint256 _oracleToleranceWad,
        uint256 _cacheExpiry,
        uint256 _priceHaircutWad
    ) external initializer {
        require(_primary != address(0) && _secondary != address(0), "zero");
        require(_oracleToleranceWad <= 0.05e18, "tol");
        require(_cacheExpiry >= 10 minutes, "cache");
        require(_priceHaircutWad <= WAD, "haircut");

        primaryOracle = AggregatorV3Interface(_primary);
        secondaryOracle = AggregatorV3Interface(_secondary);
        oracleToleranceWad = _oracleToleranceWad;
        cacheExpiry = _cacheExpiry;
        priceHaircutWad = _priceHaircutWad;
    }

    function getEthPriceSafe() external returns (uint256 price18, PriceConfidence confidence, uint256 age) {
        uint256 nowTs = block.timestamp;

        uint256 p1_18; uint256 t1; bool ok1;
        uint256 p2_18; uint256 t2; bool ok2;

        try primaryOracle.latestRoundData() returns (uint80, int256 p1Raw, uint256, uint256 t1Raw, uint80) {
            if (p1Raw > 0) {
                uint8 dec1 = primaryOracle.decimals();
                uint256 p1n = dec1 > 18 ? uint256(p1Raw) / (10 ** (dec1 - 18)) : uint256(p1Raw) * (10 ** (18 - dec1));
                p1_18 = p1n; t1 = t1Raw; ok1 = true;
            }
        } catch {}

        try secondaryOracle.latestRoundData() returns (uint80, int256 p2Raw, uint256, uint256 t2Raw, uint80) {
            if (p2Raw > 0) {
                uint8 dec2 = secondaryOracle.decimals();
                uint256 p2n = dec2 > 18 ? uint256(p2Raw) / (10 ** (dec2 - 18)) : uint256(p2Raw) * (10 ** (18 - dec2));
                p2_18 = p2n; t2 = t2Raw; ok2 = true;
            }
        } catch {}

        bool fresh1 = ok1 && (nowTs - t1 <= ORACLE_STALENESS_THRESHOLD);
        bool fresh2 = ok2 && (nowTs - t2 <= ORACLE_STALENESS_THRESHOLD);

        if (fresh1 && fresh2) {
            uint256 diff = p1_18 > p2_18 ? p1_18 - p2_18 : p2_18 - p1_18;
            uint256 tol = (p1_18 * oracleToleranceWad) / WAD;
            if (diff <= tol) {
                price18 = (p1_18 + p2_18) / 2;
                confidence = PriceConfidence.Strong;
            } else {
                price18 = p1_18;
                confidence = PriceConfidence.Weak;
            }
            cachedEthPrice18 = price18;
            cachedEthPriceUpdatedAt = nowTs;
            age = 0;
            emit OracleState(confidence, price18, age);
            return (price18, confidence, age);
        }

        if (fresh1 || fresh2) {
            price18 = fresh1 ? p1_18 : p2_18;
            confidence = PriceConfidence.Weak;
            cachedEthPrice18 = price18;
            cachedEthPriceUpdatedAt = nowTs;
            age = 0;
            emit OracleState(confidence, price18, age);
            return (price18, confidence, age);
        }

        if (cachedEthPrice18 != 0 && (nowTs - cachedEthPriceUpdatedAt) <= cacheExpiry) {
            price18 = (cachedEthPrice18 * (WAD - priceHaircutWad)) / WAD;
            confidence = PriceConfidence.Degraded;
            age = nowTs - cachedEthPriceUpdatedAt;
            emit OracleState(confidence, price18, age);
            return (price18, confidence, age);
        }

        revert("price unavailable");
    }

    function getUsdcEquivalent(
        address coin,
        address token,
        uint8 tokenDecimals,
        address tokenOracle,
        uint256 amount
    ) external view returns (uint256 usdcEq6) {
        if (token == address(0)) {
            if (cachedEthPrice18 == 0) return 0;
            usdcEq6 = ((amount * cachedEthPrice18) / 1e18) / 1e12;
            return usdcEq6;
        }
        if (token == coin) {
            return amount;
        }
        AggregatorV3Interface oracle = AggregatorV3Interface(tokenOracle);
        (, int256 pRaw, , uint256 updatedAt, ) = oracle.latestRoundData();
        require(pRaw > 0, "bad price");
        require(block.timestamp - updatedAt <= ORACLE_STALENESS_THRESHOLD, "stale");

        uint8 decOracle = oracle.decimals();
        uint256 price18;
        if (decOracle > 18) {
            uint256 scaleDown = 10 ** (decOracle - 18);
            price18 = uint256(pRaw) / scaleDown;
        } else {
            uint256 scaleUp = 10 ** (18 - decOracle);
            price18 = uint256(pRaw) * scaleUp;
        }

        uint256 amount18 = amount * (10 ** (18 - tokenDecimals));
        usdcEq6 = ((amount18 * price18) / 1e18) / 1e12;
    }
}

@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol

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

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// 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
        }
    }
}

ZSystemFlorGain.sol/Interfaces.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IKamara {
    function notifyDeposit(address user, uint256 amount6) external;
    function notifyWithdraw(address user, uint256 amount6) external;
}

interface IPerpsV3MarketProxy {
    // Margin amount is 18-decimals.
    function modifyCollateral(address account, int256 amount) external;
    // maxPriceImpact assumed to be wad ratio [0, 1e18].
    function commitOrder(address account, uint128 marketId, int256 sizeDelta, uint256 maxPriceImpact) external;
    function getPosition(address account) external view returns (int256 size, uint256 margin, uint256 price, uint256 funding);
    function getFundingRate(uint128 marketId) external view returns (int256);
}

interface IOracleAggregator {
    enum PriceConfidence { None, Strong, Weak, Degraded }
    function getEthPriceSafe() external returns (uint256 price18, PriceConfidence confidence, uint256 age);
    function getUsdcEquivalent(address coin, address token, uint8 tokenDecimals, address tokenOracle, uint256 amount) external view returns (uint256 usdcEq6);
}

interface IPerpsStrategy {
    function rebalance() external;
    function compound() external;
    function ensureHealthyWithdrawal(uint256 price18, uint256 shortfall6) external;
    function updateKeeperReward(uint256 keeperReward18) external;
    function getLeverage(uint256 price18) external view returns (uint256 leverageWad);
    function currentState() external view returns (int256 size, uint256 margin18);
}

interface IKeeperManager {
    function setKeeper(address keeper, bool enabled) external;
    function isKeeper(address keeper) external view returns (bool);
    function payKeeper(address keeper, uint256 amount6, address coin) external;
}

interface IDarja {
    function mint(address to, uint256 amount) external;
    function burnFrom(address account, uint256 amount) external;
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.