# 📖 Introduction

Welcome to the official documentation for **QIE Oracle** — a decentralized, secure, and efficient price feed system built for the **QIE Layer 1 blockchain**.

QIE Oracle bridges the gap between **off-chain data** (such as asset prices) and **on-chain smart contracts**, enabling developers to build powerful decentralized applications (dApps) that rely on **accurate, real-time market data**.


# ❓ What is QIE Oracle?

**QIE Oracle** is a decentralized data feed system designed to bring real-world asset prices onto the **QIE Layer 1 blockchain**.

Blockchains are inherently closed systems—they cannot directly access external data. Oracles solve this limitation by acting as a secure bridge between off-chain data and on-chain smart contracts.

QIE Oracle enables developers to access **secure, reliable, and tamper-resistant price feeds** for a wide range of assets. This foundational infrastructure supports powerful on-chain applications, including:

* **DeFi protocols** (e.g., lending, borrowing, synthetic assets)
* **Gaming platforms**
* **Decentralized trading**
* **Stablecoins**
* **Tokenized real-world assets (RWA)**

By leveraging QIE Oracle, developers can build applications that interact safely with real-world data—ensuring accuracy, trust, and transparency across the QIE ecosystem.


# ❓ Why Do We Need Oracles?

Smart contracts, by design, **cannot access live market data** on their own. This creates a critical limitation for many decentralized applications.

For example, a **lending protocol** built on QIE may need the **current price of BTC or ETH** to calculate collateral ratios. Without an oracle, this data is simply **not available on-chain**, making it impossible to execute accurate or safe logic.

#### How QIE Oracle Solves This

QIE Oracle addresses this limitation by:

* **Fetching real-time price data** from trusted and verifiable off-chain sources.
* **Publishing price feeds on-chain** via verified Oracle contracts.
* **Providing a unified standard** for smart contracts to query asset prices with minimal integration effort.

This ensures that decentralized financial products on QIE are:

* ✅ **Accurate** — reflecting real-world asset values
* ✅ **Transparent** — data sources and update mechanisms are publicly auditable
* ✅ **Secure** — tamper-resistant infrastructure prevents manipulation, even in volatile markets

By bridging off-chain data to on-chain logic, QIE Oracle plays a critical role in enabling safe, scalable, and reliable applications across the QIE ecosystem.


# 📦 Supported Assets & Scope

QIE Oracle currently supports **seven key assets** through deployed smart contracts on the **QIE Layer 1 blockchain**.

These Oracle contracts serve as the **official price reference** for their respective assets on the QIE network.

| Asset        | Symbol | Contract Address                             |
| ------------ | ------ | -------------------------------------------- |
| Bitcoin      | BTC    | `0x9E596d809a20A272c788726f592c0d1629755440` |
| Ethereum     | ETH    | `0x4bb7012Fbc79fE4Ae9B664228977b442b385500d` |
| Ripple       | XRP    | `0x804582B1f8Fea73919e7c737115009f668f97528` |
| Solana       | SOL    | `0xe86999c8e6C8eeF71bebd35286bCa674E0AD7b21` |
| QIE Native   | QIE    | `0x3Bc617cF3A4Bb77003e4c556B87b13D556903D17` |
| Tether Gold  | XAUt   | `0x9aD0199a67588ee293187d26bA1BE61cb07A214c` |
| Binance Coin | BNB    | `0x775A56117Fdb8b31877E75Ceeb68C96765b031e6` |

#### 🔹 Developer Access

Developers can **directly call these contracts** to retrieve **live, on-chain price data** for supported assets—enabling real-time interaction in DeFi protocols, trading platforms, and more.

### 🚀 Future Scope

QIE Oracle is continuously evolving to support a wider range of data sources and assets. Upcoming enhancements include:

* **More cryptocurrencies**\
  → *LTC, DOT, MATIC, and others*
* **Real-world assets**\
  → *Stocks, commodities (e.g., gold, oil), and FX pairs*
* **Cross-chain data integration**\
  → *Support for fetching and verifying data across multiple blockchain networks*

These planned upgrades will expand the capabilities of the QIE ecosystem, making it a robust platform for building advanced, data-driven decentralized applications.


# ⚙️ How QIE Oracle Works

QIE Oracle is designed to deliver **accurate and reliable price data** from the real world onto the QIE blockchain. This section explains how the Oracle works internally — from **fetching off-chain data** to making it accessible for smart contracts.


# 📡 Data Sourcing (Off-Chain Price Feeds → On-Chain)

The first step in the QIE Oracle system is **data collection from external sources**. To ensure accuracy and reliability, QIE Oracle sources price data from **trusted and reputable providers**, including:

* **Cryptocurrency exchanges**\
  → *e.g., Binance, Coinbase, Kraken*
* **Financial market data providers**\
  → *e.g., XAUt (Tether Gold) and other real-world asset feeds*

***

#### 🔄 Data Flow Overview

The Oracle follows a standardized process to collect, process, and publish asset prices:

1. **Fetch price data**\
   A backend service regularly queries external APIs to retrieve the latest price information.
2. **Transform data**\
   The raw data is normalized to match the required precision and format used by the blockchain (e.g., converting float values to fixed-point integers).
3. **Submit to Oracle contract**\
   The processed data is submitted to QIE Oracle smart contracts via **signed transactions**, ensuring authenticity and data integrity.

***

#### ✅ Key Benefits

* **Structured** — Data is consistently formatted for easy consumption by smart contracts
* **Accurate** — Pulled from trusted, high-liquidity sources
* **Tamper-proof** — Signed and verified before being published on-chain

This system ensures that all on-chain price feeds are reliable, secure, and compatible with QIE-based applications.


# 🧮 Aggregation and Validation

To ensure **reliability**, **accuracy**, and **resistance to manipulation**, QIE Oracle implements a robust **data aggregation mechanism**.

#### 🔗 Aggregation Process

1. **Multi-source data collection**\
   Price data is fetched simultaneously from multiple trusted sources.
2. **Aggregation logic**\
   A **median** or **weighted average** is calculated to determine the final price value.
3. **Outlier detection & filtering**\
   Anomalous or outlier values are automatically identified and excluded from the final calculation.

***

#### ✅ Why This Matters

This aggregation mechanism ensures that:

* A single faulty or malicious data source **cannot compromise** the overall system.
* The Oracle publishes a **consensus-based price** that accurately reflects real market conditions.
* The resulting data is **more stable**, **trustworthy**, and **manipulation-resistant**, especially during high volatility.


# 📦 Smart Contract Integration

This section explains how developers can integrate the `AggregatorV3` oracle contract into their own decentralized applications (dApps) to access off-chain or externally-fed data within smart contracts.

Your dApp can consume reliable, on-chain data using our `AggregatorV3` oracle, which is compatible with the standard Chainlink AggregatorV3 interface — making integration simple and familiar for many Web3 developers.

***

### 🔗 Integration Overview

To use the oracle in your dApp:

1. **Import the AggregatorV3Interface**
2. **Set the oracle contract address**
3. **Call the oracle’s functions (`latestRoundData`, `getRoundData`, etc.)**
4. **Handle data appropriately in your business logic**

***

### 🛠️ Step-by-Step Guide

#### 1. Import the AggregatorV3Interface

If you're using Solidity:

```
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
```

Note: This works because our oracle implements the same interface as Chainlink, so it's fully compatible.

***

#### 2. Declare the Oracle Interface

Declare a reference to the oracle in your consuming contract:

```
AggregatorV3Interface public priceFeed;
```

You’ll initialize this reference in the constructor or a setup function.

***

#### 3. Initialize with the Oracle Address

```
constructor(address _oracleAddress) {
    priceFeed = AggregatorV3Interface(_oracleAddress);
}
```

> Replace `_oracleAddress` with the actual deployed address of the `AggregatorV3` oracle contract.

***

#### 4. Read the Latest Data

To get the most recent answer:

```
function getLatestAnswer() public view returns (int256) {
    (
        , 
        int256 answer,
        , 
        , 
    ) = priceFeed.latestRoundData();
    return answer;
}

```

You can also access timestamps and round information if needed:

```
function getLatestData() public view returns (
    uint80 roundId,
    int256 answer,
    uint256 startedAt,
    uint256 updatedAt,
    uint80 answeredInRound
) {
    return priceFeed.latestRoundData();
}

```

***

#### 5. Read Specific Round Data (Optional)

If your use case requires historical data, you can retrieve data from a specific round:

```
function getHistoricalAnswer(uint80 roundId) public view returns (int256) {
    (
        , 
        int256 answer,
        , 
        , 
    ) = priceFeed.getRoundData(roundId);
    return answer;
}

```

> ⚠️ Ensure the round exists — otherwise, the call will revert.

***

### 🧠 Use Cases

Here are a few example use cases where your dApp might benefit from this oracle:

* **Price Feeds:** Display the current price of a token or asset.
* **Stablecoin Collateralization:** Check price before minting/burning.
* **Betting & Prediction Markets:** Resolve outcomes based on real-world values.
* **Rebasing Tokens:** Use oracle data for supply adjustments.

***

### ⚠️ Best Practices

* **Validate Oracle Output:** Ensure the returned data is not stale or zero.
* **Handle Errors:** If no data is available, `latestRoundData()` will revert. Use `try/catch` in higher-level frameworks or check availability on-chain.
* **Secure the Oracle Address:** Set the oracle address only once or via a governance mechanism to avoid manipulation.

***

### 🧪 Testing Integration

When testing locally or in staging:

* You can deploy a mock oracle using the same interface (`AggregatorV3Interface`) and manually update values using the `updateAnswer(int256)` function.
* This is useful for simulating real-world scenarios and testing dApp logic against different oracle values.

```
// Call this in your tests from the oracle owner's account
mockOracle.updateAnswer(12345); // sets new answer

```

### ✅ Summary

By following the standard `AggregatorV3Interface`, our oracle contract allows seamless integration into any dApp that supports Chainlink-style data feeds.

Integration steps are straightforward:

1. Import the interface
2. Set the oracle address
3. Call `latestRoundData()` or `getRoundData()`
4. Use the result in your business logic

With this, your smart contracts can interact with externally-fed data reliably and efficiently.


# 🔒 Security Measures

### 🔐 Oracle Security

Security is a critical component of any oracle system, as it acts as the bridge between off-chain data and on-chain smart contracts. The **QIE Oracle** is designed with multiple layers of protection to ensure the accuracy, integrity, and reliability of the data it delivers.

***

#### ✅ Security Features

**🔏 Signed Transactions**

Only **authorized nodes** are permitted to update the QIE Oracle contracts. All updates are executed via **signed transactions**, ensuring that only trusted entities can push data on-chain.

**🔁 Redundant Data Sources**

QIE Oracle aggregates data from **multiple independent exchanges**. This redundancy helps:

* Prevent manipulation from a single source
* Increase data reliability
* Smooth out anomalies from low-liquidity markets

**⏱️ Timely Updates**

Price feeds are refreshed at **regular intervals**, ensuring that on-chain consumers always access **up-to-date information**. This reduces the risk of using stale data in critical financial applications.

**🧠 On-Chain Sanity Checks**

Smart contracts integrating with QIE Oracle can implement **custom validation logic**, such as:

* Maximum deviation thresholds from the last known price
* Time-based freshness checks
* Reversion on abnormal spikes or gaps

These **on-chain safeguards** allow dApps to reject suspicious or potentially manipulated updates proactively.

***

#### 🛡️ Why This Matters

With these security mechanisms in place, QIE Oracle offers:

* **Robust protection** against malicious actors
* **High availability** and **accuracy** of external data
* **Trustworthy integration** for financial, DeFi, and data-driven smart contracts

***

QIE Oracle is built with security and resilience in mind — ensuring developers can confidently rely on it for mission-critical on-chain applications.


# 📄 Deployed Contracts

QIE Oracle publishes **live price data on-chain** via dedicated smart contracts for each supported asset. These contracts serve as the **official reference points** for dApps, DeFi protocols, and other smart contracts across the QIE blockchain.


# 📊 Table of Assets → Contract Mapping

| Asset        | Symbol | Oracle Contract Address                      |
| ------------ | ------ | -------------------------------------------- |
| Bitcoin      | BTC    | `0x9E596d809a20A272c788726f592c0d1629755440` |
| Ethereum     | ETH    | `0x4bb7012Fbc79fE4Ae9B664228977b442b385500d` |
| Ripple       | XRP    | `0x804582B1f8Fea73919e7c737115009f668f97528` |
| Solana       | SOL    | `0xe86999c8e6C8eeF71bebd35286bCa674E0AD7b21` |
| QIE Native   | QIE    | `0x3Bc617cF3A4Bb77003e4c556B87b13D556903D17` |
| Tether Gold  | XAUt   | `0x9aD0199a67588ee293187d26bA1BE61cb07A214c` |
| Binance Coin | BNB    | `0x775A56117Fdb8b31877E75Ceeb68C96765b031e6` |

> ⚡ Note: These are the **official Oracle contracts** on QIE Layer 1. Always reference these addresses when fetching price data in your smart contracts.


# 📥 Query Examples

This section provides practical examples of how to query the **QIE Oracle** from both JavaScript (frontend/backend using `ethers.js`) and Solidity (on-chain smart contracts). These examples help developers easily integrate the oracle into dApps and smart contracts.

***

#### 🟨 Solidity Example

Use this example to read the latest price from the oracle **inside a smart contract**.

```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumer {
    AggregatorV3Interface public priceFeed;

    constructor(address oracleAddress) {
        priceFeed = AggregatorV3Interface(oracleAddress);
    }

    function getLatestPrice() public view returns (int256) {
        (
            , // roundId
            int256 price,
            , // startedAt
            , // updatedAt
            // answeredInRound
        ) = priceFeed.latestRoundData();

        return price;
    }
}

```

> Replace `oracleAddress` with the deployed address of the QIE Oracle contract on your network.

***

#### 🟦 JavaScript Example (ethers.js)

Use this example in your frontend or backend to query the oracle using **ethers.js**.

```
const { ethers } = require("ethers");

const provider = new ethers.JsonRpcProvider("<rpc_url>");

//  Price Feed contract address (example: BNB/USD on QIE Mainnet)
const priceFeedAddress = "0xYourOracleAddress"; // BNB/USD (8 decimals)

// ABI fragment to read latestRoundData
const aggregatorV3InterfaceABI = [
  {
    "inputs": [],
    "name": "latestRoundData",
    "outputs": [
      { "internalType": "uint80", "name": "roundId", "type": "uint80" },
      { "internalType": "int256", "name": "answer", "type": "int256" },
      { "internalType": "uint256", "name": "startedAt", "type": "uint256" },
      { "internalType": "uint256", "name": "updatedAt", "type": "uint256" },
      { "internalType": "uint80", "name": "answeredInRound", "type": "uint80" }
    ],
    "stateMutability": "view",
    "type": "function"
  }
];

async function getPrice() {
  const priceFeed = new ethers.Contract(priceFeedAddress, aggregatorV3InterfaceABI, provider);
  
  const roundData = await priceFeed.latestRoundData();
  const price = roundData.answer;

  // Normalize 8 decimals
  const normalizedPrice = Number(price) / 1e8;

  console.log(`BNB/USD Price: $${normalizedPrice}`);
}

getPrice().catch(console.error);

```

> ⚠️ Don’t forget to replace `0xYourOracleAddress` and `your_rpc_url` with the correct values for your deployment.

***

#### 📌 Additional Query: Get Historical Data

You can also query a specific round by ID to fetch past data.

**Solidity:**

```
function getHistoricalPrice(uint80 roundId) public view returns (int256) {
    (
        , 
        int256 price,
        , 
        , 
    ) = priceFeed.getRoundData(roundId);
    return price;
}

```

JavaScript:

```
async function fetchHistoricalPrice(roundId) {
  const [ , price ] = await priceFeed.getRoundData(roundId);
  const decimals = await priceFeed.decimals();

  const normalizedPrice = Number(price) / (10 ** decimals);
  console.log(`Price at round ${roundId}: ${normalizedPrice}`);
}

```

#### 🧪 Tip: Mocking in Local Development

For local testing, you can deploy your own instance of the `AggregatorV3` contract and call `updateAnswer(int256)` to simulate real-world updates.


# 🚀 Getting Started

This section will guide you through the **initial setup** needed to interact with QIE Oracle, connect to the QIE blockchain, and fetch live asset prices.


# 🚀 Prerequisites

Before you begin integrating the QIE Oracle, make sure you have the following tools and knowledge in place:

***

#### 👛 QIE Wallet or MetaMask

You will need a wallet that supports **QIE Layer 1** in order to:

* Sign transactions
* Interact with Oracle contracts

✅ **MetaMask is supported** and can be configured to connect to QIE using a custom RPC.

***

#### 🌐 QIE RPC URL

This is the endpoint your application uses to connect to the QIE blockchain network.

* **RPC URL:** `https://rpc5mainnet.qie.digital`

📌 Use this URL in MetaMask, Ethers.js, Hardhat, or any Web3-compatible tool to connect to the QIE mainnet.

***

#### 🟦 Node.js & Ethers.js (For JavaScript Developers)

To interact with Oracle contracts programmatically via JavaScript:

1. **Install Node.js:**\
   Download from <https://nodejs.org>

```
npm install ethers

```

This setup allows you to fetch oracle data and interact with smart contracts using JavaScript.

***

#### 🧠 Basic Solidity Knowledge (For Smart Contract Developers)

To integrate the oracle in your smart contracts, you should be familiar with:

* Solidity interfaces
* External contract calls
* Reading data from oracle feeds

If you're new to this, refer to the Query Examples


# 🔗 Connecting to the QIE Blockchain

To interact with QIE Oracle contracts, your wallet or application must first connect to the **QIE Layer 1 blockchain**. Below are the steps for connecting using **MetaMask** and **JavaScript (ethers.js)**.

***

#### 🦊 Using MetaMask

You can manually add the QIE network to MetaMask:

1. Open MetaMask
2. Click **"Add Network"**
3. Enter the following network details:

```
Network Name:       QIE Mainnet
RPC URL:            https://rpc5mainnet.qie.digital
Chain ID:           1990       
Currency Symbol:    QIE
Block Explorer URL: https://mainnet.qie.digital

```

4. Click **Save**, then switch your wallet to the newly added QIE Mainnet.

> ✅ Once added, you’ll be able to sign transactions and interact with the QIE Oracle contracts directly from MetaMask.

***

#### 📦 Using JavaScript (ethers.js)

To connect your JavaScript or Node.js application to the QIE blockchain using `ethers.js`:

```
const { ethers } = require("ethers");

// Connect to the QIE blockchain via RPC
const provider = new ethers.JsonRpcProvider("https://rpc5mainnet.qie.digital");

console.log("Connected to QIE blockchain:", provider);

```

> ✅ You can now use the `provider` to interact with smart contracts, read oracle data, send transactions, and more.


# 📡 Reading Data from Oracle

Once connected, you can query Oracle contracts to fetch live prices.

#### Example: Fetch BTC Price

```
interface IQIEOracle {
    function getPrice(string calldata asset) external view returns (uint256);
}

contract FetchPriceExample {
    IQIEOracle oracle = IQIEOracle(0x9E596d809a20A272c788726f592c0d1629755440); // BTC Oracle

    function getBTCPrice() public view returns (uint256) {
        return oracle.getPrice("BTC"); // Returns BTC price in smallest unit
    }
}

```

**JavaScript Example (ethers.js)**

```
const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider("https://rpc.qiechain.io");

const oracleAddress = "0x9E596d809a20A272c788726f592c0d1629755440";
const oracleAbi = ["function getPrice(string asset) view returns (uint256)"];

const oracleContract = new ethers.Contract(oracleAddress, oracleAbi, provider);

async function fetchBTCPrice() {
    const price = await oracleContract.getPrice("BTC");
    console.log("BTC Price:", price.toString());
}

fetchBTCPrice();

```

> ⚡ Tip: Replace `"BTC"` with `"ETH"`, `"XRP"`, or any supported asset symbol to fetch other prices.

This section provides the **foundation for developers** to start interacting with QIE Oracle immediately, whether through smart contracts or scripts.


# 📙 Developer Guide

This section offers **practical guidance** for developers to integrate QIE Oracle into smart contracts, fetch live asset prices, handle errors, and follow best practices for building **secure and reliable** applications.


# ⚙️ How to Integrate QIE Oracle in Smart Contracts

Integrating QIE Oracle into your smart contract is simple and gas-efficient. The oracle contracts are **read-only**, meaning fetching data does not consume significant gas.

***

#### ✅ Integration Steps

**1. Import the Oracle Interface**

Use the standard `AggregatorV3Interface`, which is compatible with the QIE Oracle:

```
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

```

> This interface is supported because QIE Oracle follows the Chainlink AggregatorV3 standard.

***

**2. Instantiate the Oracle**

Set the oracle contract address in your constructor or initializer:

```
AggregatorV3Interface public priceFeed;

constructor(address oracleAddress) {
    priceFeed = AggregatorV3Interface(oracleAddress);
}

```

> Replace `oracleAddress` with the deployed address of the specific QIE Oracle for your asset (e.g., QIE/USD).

***

**3. Call `latestRoundData()` to Get the Price**

Fetch the latest price in your contract logic:

```
function getLatestPrice() public view returns (int256) {
    (
        , 
        int256 price,
        , 
        , 
    ) = priceFeed.latestRoundData();

    return price;
}

```

> This function is read-only (`view`) and consumes minimal gas when called externally or from another contract.

***

#### ⚡️ Gas Efficiency

All price-fetching functions on the QIE Oracle are **non-state-changing** (read-only). This means:

* No transaction needs to be sent
* No gas is spent reading data (unless used inside a transaction)
* Safe to use in frequent or lightweight calls


# 🧾 Example: Fetching BTC & ETH Prices (Solidity)

Here’s a sample Solidity snippet showing how to fetch real-time prices for **BTC** and **ETH** using QIE Oracle contracts. These oracles are based on your custom implementation of `AggregatorV3`.

***

#### 🔍 Assumptions

* You have deployed two oracle contracts using your custom `AggregatorV3` contract:
  * One for BTC (e.g., BTC/USD)
  * One for ETH (e.g., ETH/USD)
* Both contracts implement `AggregatorV3Interface`
* The contract addresses are known and passed during deployment

***

#### 🧱 Sample Solidity Code

```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract AssetPriceConsumer {
    AggregatorV3Interface public btcOracle;
    AggregatorV3Interface public ethOracle;

    constructor(address _btcOracle, address _ethOracle) {
        btcOracle = AggregatorV3Interface(_btcOracle);
        ethOracle = AggregatorV3Interface(_ethOracle);
    }

    function getLatestBTCPrice() public view returns (int256) {
        (
            , 
            int256 price,
            , 
            , 
        ) = btcOracle.latestRoundData();
        return price;
    }

    function getLatestETHPrice() public view returns (int256) {
        (
            , 
            int256 price,
            , 
            , 
        ) = ethOracle.latestRoundData();
        return price;
    }
}

```

#### 🧪 Usage

This contract allows you to:

* Fetch the latest BTC/USD and ETH/USD prices
* Use the prices in further contract logic (e.g., swaps, comparisons, liquidations)

You can call:

```
getLatestBTCPrice(); // Returns the latest BTC price (int256)
getLatestETHPrice(); // Returns the latest ETH price (int256)

```

#### ⚠️ Notes

* Ensure that the oracle contracts are properly updated by the owner before use.
* The returned price is an `int256` and may include decimals (check `decimals()` from the oracle).
* If the oracle has not been updated yet, `latestRoundData()` will revert.

***

#### 📘 Bonus: Get Oracle Metadata

You can also fetch metadata like description and decimals:

```
function getBTCMetadata() public view returns (string memory, uint8) {
    return (btcOracle.description(), btcOracle.decimals());
}
```


# ⚠️ Handling Edge Cases & Best Practices

While the **QIE Oracle** is designed for reliability and consistency, developers should account for potential edge cases and follow recommended best practices to ensure safe integration into smart contracts and dApps.

***

#### 🚫 Handling Common Edge Cases

**🔤 Invalid Asset Symbol**

If your oracle implementation supports asset symbols (e.g., `getPrice("BTC")`), calling the function with an **unsupported or misspelled symbol** will **revert** the transaction.

> ✅ **Tip:** Always validate or whitelist symbols before calling the oracle.

***

**📉 Unexpected Price Values**

Due to market volatility or delayed updates, prices may temporarily **spike** or **crash**. Implement **on-chain sanity checks** to prevent incorrect logic execution.

```
function safeFetchBTCPrice() public view returns (uint256) {
    uint256 price = btcOracle.getPrice("BTC");
    require(price > 0, "Invalid BTC price");
    require(price < 1_000_000_000 ether, "BTC price too high");
    return price;
}

```

> ✅ Set upper and lower bounds for acceptable price ranges.

***

**🕒 Oracle Update Delays**

QIE Oracle updates prices at **regular intervals**, but **not every block**.

> ⚠️ Do not assume price data is real-time within the same block. For sensitive use cases (like flash loans or arbitrage), verify `updatedAt` timestamp from `latestRoundData()`.

***

### ✅ Best Practices

#### 🪙 Use Multiple Assets

If your dApp supports multiple tokens (e.g., DeFi lending or trading), consider fetching **multiple asset prices** to reduce reliance on a single price feed.

***

#### 🧠 Implement Rate Limiting / Caching

Avoid repeatedly calling the oracle in the same transaction or within tight loops.

* **Cache prices on-chain** for a few blocks
* **Store recent price in state**, and refresh only when needed

> This helps **reduce gas costs** and improves efficiency.

***

#### 🧾 Validate External Data

Always include **sanity checks** in your contract logic for:

* Price magnitude
* Max allowed percentage change
* Timestamp freshness

Example:

```
require(block.timestamp - lastUpdated < 300, "Price is outdated");
```

***

#### 🛡️ Do Not Overwrite Oracle Data

Oracle contracts are maintained by the QIE system. Never attempt to manually modify oracle state or push updates.

> 🛑 Direct writes to oracle contracts are restricted to authorized updaters only.

***

#### 🧪 Test on Testnet First

Before deploying to QIE Mainnet:

* Use **QIE Testnet RPC**
* Deploy your contracts
* Connect to deployed **testnet oracle contracts**
* Simulate edge cases and validate behavior

***

### 🔚 Conclusion

By following these practices, developers can:

* Safely consume oracle data
* Protect their dApps from abnormal price behavior
* Ensure secure and efficient usage of QIE Oracle in DeFi and other use cases

> ✅ Good oracle hygiene is critical for building trustworthy, secure Web3 applications.


# 💡 Use Cases

QIE Oracle delivers **secure, reliable, and real-time price data**, empowering developers to build a diverse range of decentralized applications on the QIE blockchain. This section highlights some of the key use cases.


# 🔑 Use Cases for QIE Oracle in DeFi

The **QIE Oracle** plays a crucial role in powering decentralized finance (DeFi) applications by providing **accurate and reliable on-chain asset prices**. Here are some primary use cases where the oracle is essential:

***

#### 🏦 Lending & Borrowing Platforms

* **Purpose:** Determine the value of collateral assets to calculate safe loan-to-value (LTV) ratios.
* **Example:** When a user deposits BTC as collateral, the oracle supplies the current BTC price to accurately compute borrowing limits and liquidation thresholds.

***

#### 🔄 Decentralized Exchanges (DEXs)

* **Purpose:** Facilitate token swaps, liquidity provisioning, and automated market maker (AMM) price calculations using live market data.
* **Example:** Swap ETH for QIE tokens at the current exchange rate fetched from the oracle, ensuring fair and up-to-date pricing for traders.

***

#### 💰 Stablecoins & Synthetic Assets

* **Purpose:** Peg tokens to real-world assets like gold-backed tokens (e.g., XAUt by Tether) or cryptocurrencies.
* **Role of Oracle:** Ensures the peg’s accuracy by providing timely and trustworthy price feeds, maintaining stable and reliable valuations.

***

QIE Oracle’s reliable pricing infrastructure empowers these DeFi building blocks, enabling secure, transparent, and efficient financial products on-chain.


# 🎮 Blockchain Gaming & Play-to-Earn (P2E) Integration

Blockchain-based games can harness **real-time asset prices** from QIE Oracle to enable dynamic, tokenized economies and rewarding gameplay experiences.

***

#### 💎 Key Use Cases

* **In-Game Rewards:**\
  Tie rewards, such as tokens or points, to the current value of cryptocurrencies, allowing players to earn assets with real-world value.
* **Tokenized Assets & NFTs:**\
  Enable trading of in-game assets or NFTs whose prices are dynamically adjusted based on real-world market prices provided by the oracle.

***

#### 🎲 Example

A play-to-earn game could award players with **QIE tokens** whose value corresponds to a fixed USD or BTC amount. The oracle feed continuously updates this value, ensuring fair and transparent rewards aligned with the market.

***

By integrating QIE Oracle price data, game developers can create immersive economies where player rewards and asset valuations reflect real-world market conditions.


# 🏷️ Tokenization of Real-World Assets with QIE Oracle

QIE Oracle empowers secure and reliable **tokenization of real-world assets**, enabling their seamless representation and trading on the blockchain.

***

#### 🥇 Gold & Commodities (e.g., XAUt)

* Provides verified and tamper-resistant price feeds for tokenized gold and other commodities.
* Users can confidently **buy, sell, or trade** tokenized commodities backed by real market data.

***

#### 💵 Fiat-backed Tokens & Real-World Assets (RWA)

* Facilitates tokenization of fiat currencies, bonds, and other financial instruments.
* Ensures **accurate and transparent on-chain valuations** through trusted oracle price feeds.

***

By integrating QIE Oracle, projects can bridge traditional assets and blockchain ecosystems with integrity and precision.


# 🔗 Combining Multiple Use Cases in One Application

Developers can build powerful, multi-functional dApps by integrating several QIE Oracle-powered features into a single platform.

***

#### 🎯 Example

Imagine a DeFi platform where users can:

* **Stake tokenized gold (XAUt)** in lending pools
* **Trade synthetic assets** backed by real-world prices
* **Participate in blockchain gaming rewards**

All these features rely on **QIE Oracle’s reliable price feeds** to ensure accurate and up-to-date asset data.

***

### 📋 Summary

**QIE Oracle** serves as the backbone for all applications that require **accurate, real-time asset prices**. Whether it’s DeFi, gaming, or tokenization, QIE Oracle guarantees data integrity, enabling developers to create **robust, secure, and reliable** applications on **QIE Layer 1**.


# 🔒 Security & Reliability

QIE Oracle guarantees the **accuracy, integrity, and trustworthiness** of on-chain price data through multiple robust mechanisms.


# 🔄 Data Aggregation and Reliability

QIE Oracle aggregates price data from **multiple trusted sources** for each supported asset.

* Outliers and anomalous values are automatically detected and **filtered out**.
* This **redundancy** minimizes the risk of incorrect or manipulated data from any single source affecting on-chain price feeds.

By combining data streams, QIE Oracle ensures **robustness and accuracy** for all consumers of its price feeds.


# 🔐 Security and Data Integrity

* Only **authorized nodes** are permitted to submit updates to the Oracle contracts.
* Each update is **cryptographically signed** to guarantee authenticity and prevent tampering.
* Smart contracts consuming oracle data can implement **sanity checks**, such as limiting the maximum allowed price deviation per update, to reject suspicious or erroneous values.

These measures together ensure the **security, reliability, and trustworthiness** of QIE Oracle price feeds.


# ⏱️ Timely Updates and Transparency

* Prices are updated at **regular intervals** to maintain data freshness.
* Every update is **recorded on-chain** and is publicly verifiable by anyone.
* This transparency allows developers and users to **audit all Oracle updates**, fostering trust in the data feed.

#### ✅ Summary

By combining **redundant data sources**, **strict access controls**, and **transparent update mechanisms**, QIE Oracle delivers a **robust, secure, and reliable** price feed for all on-chain applications.


# ❓ FAQs

This section addresses the most common questions about QIE Oracle, helping developers and users gain a clearer understanding of its functionality.


# ⏳ How Often Does QIE Oracle Update Prices?

QIE Oracle updates asset prices at **regular, configurable intervals**, tailored to the nature of each asset:

* **Cryptocurrencies** (e.g., BTC, ETH, BNB) are updated **every few minutes** to accurately reflect rapid market changes.
* **Real-world assets** (e.g., XAUt – Tether Gold) are updated **every few minutes** or according to the schedule of trusted external data providers.

***

#### 🔍 Ensuring Freshness

Developers can always verify the **timestamp** of the latest price by querying the Oracle contract’s data. This helps confirm the price feed is **up-to-date** before relying on it in smart contract logic.


# ❓ Can Developers Request New Assets?

Yes, developers can request support for additional assets on QIE Oracle.

#### How It Works:

* Requests are **reviewed** based on data source reliability, user demand, and technical feasibility.
* Once approved, a new Oracle contract for the requested asset will be **deployed**, providing secure and reliable on-chain price feeds.

***

#### 🔜 Currently Supported Assets

QIE Oracle currently supports:

* BTC, ETH, XRP, SOL, QIE, XAUt (Tether Gold), and BNB

More assets are planned and will be added according to the project roadmap.

***


# ⛽ What’s the Gas Cost for Fetching Data?

* Fetching prices from QIE Oracle contracts is **read-only** and uses Solidity’s `view` functions.
* When called externally (e.g., via `eth_call`), **no gas** is consumed to read data on-chain.
* Gas is only required if the price data is used inside a **state-changing transaction** (for example, a function that modifies contract storage).

#### 💡 Tips for Gas Optimization

* Use **caching** strategies to minimize repeated oracle calls within the same transaction or block.
* Implement **sanity checks** off-chain or in smart contracts to avoid unnecessary state updates triggered by anomalous data.

#### ✅ Summary

QIE Oracle provides frequent, secure, and **cost-efficient access** to real-time asset prices. Developers can request new assets and trust transparent, auditable updates to power DeFi, gaming, and tokenized asset applications on QIE Layer 1.


