> For the complete documentation index, see [llms.txt](https://docs.chiliz.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chiliz.com/vi/phat-trien/nang-cao/nguon-gia-on-chain/doc-gia.md).

# Đọc giá

## Bước 1: Tìm Địa Chỉ Oracle

Ba cách để tìm địa chỉ hợp đồng `PriceFeed` cho một cặp nhất định:

* **Price Oracle Tracker** (dễ nhất trong khi phát triển): [price-oracle-tracker.vercel.app](https://price-oracle-tracker.vercel.app/?network=mainnet) — hiển thị tất cả các cặp đã triển khai, giá trực tiếp, decimals, heartbeat, và địa chỉ.
* **On-chain qua OracleFactory**: gọi `pairToOracle(string pair)`. Ký hiệu cặp phải được truyền bằng chữ hoa (ví dụ: `"PSG/USDT"`) — factory không chuẩn hóa đầu vào khi đọc.
* **Bulk on-chain qua OracleFactoryReader**: gọi `getActiveOracles()` để lấy tất cả các cặp đang hoạt động và địa chỉ của chúng trong một lần gọi.

```solidity
interface IOracleFactory {
    function pairToOracle(string memory pair) external view returns (address);
    function getOracleCount() external view returns (uint256);
}

function resolveFeed(address factory, string memory pair)
    external view returns (address)
{
    // Pair symbol must be passed in uppercase (e.g. "PSG/USDT").
    return IOracleFactory(factory).pairToOracle(pair);
}
```

## Bước 2: Kết Nối Bằng Giao Diện

Hợp đồng `PriceFeed` triển khai `IAggregatorV3Interface` chuẩn của Chainlink, cộng với các phần mở rộng riêng của Chiliz cho trạng thái sức khỏe và tạm dừng.

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

interface IAggregatorV3Interface {
    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
        );
}

interface IChilizPriceFeed is IAggregatorV3Interface {
    function paused() external view returns (bool);
    function updateInterval() external view returns (uint256);
    function healthFactor() external view returns (uint80);
    function getHealthStatus()
        external view
        returns (
            uint256 lastUpdateTimestamp,
            uint256 totalRounds,
            uint256 timeSinceLastUpdate,
            bool isHealthy
        );
}
```

## Bước 3: Đọc Giá

{% hint style="warning" %}
**Nguồn giá không revert khi ở trạng thái stale hoặc bị tạm dừng — đây là có chủ ý.** `latestRoundData()` revert với `NoDataAvailable()` nếu chưa có round nào, nhưng không kiểm tra xem nguồn giá có bị tạm dừng hay stale không. Điều này phù hợp với thiết kế Chainlink AggregatorV3Interface: người dùng có trách nhiệm kiểm tra `paused()` và `getHealthStatus()` trước khi sử dụng giá. Lưu ý: các hàm helper scalar (`latestAnswer()`, `latestTimestamp()`, `getAnswer()`, `getTimestamp()`) trả về `0` thay vì revert khi không có dữ liệu. Xem [Thực Hành Tốt Nhất](/vi/phat-trien/nang-cao/nguon-gia-on-chain/thuc-hanh-tot-nhat.md) để biết mẫu xác thực đầy đủ.
{% endhint %}

Hàm chính là `latestRoundData()`, trả về giá hiện tại cùng với metadata round và timestamp.

```solidity
contract LendingOracleConsumer {
    IChilizPriceFeed public priceFeed;

    constructor(address _feed) {
        priceFeed = IChilizPriceFeed(_feed);
    }

    function getSafePrice() public view returns (uint256 price18) {
        // 1. Check feed is not paused
        require(!priceFeed.paused(), "Feed paused");

        // 2. Read latest data (reverts with NoDataAvailable() if no rounds exist)
        (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();

        // 3. Basic sanity checks
        require(answer > 0, "Invalid price");

        // 4. Optional: use explicit health check for staleness
        (, , , bool isHealthy) = priceFeed.getHealthStatus();
        require(isHealthy, "Stale price");

        // 5. Normalize to 18 decimals for internal math
        uint8 decimals_ = priceFeed.decimals();
        uint256 scale = 10 ** uint256(decimals_);
        price18 = uint256(answer) * 1e18 / scale; // This is the actual price of an asset
    }
}
```

Nếu giao thức của bạn sử dụng decimals gốc của nguồn giá thay vì chuẩn hóa về 18:

```solidity
function getRawPriceWithMeta()
    external view
    returns (int256 price, uint8 decimals_, uint256 updatedAt)
{
    require(!priceFeed.paused(), "Feed paused");

    (, int256 answer, , uint256 _updatedAt, ) =
        priceFeed.latestRoundData();
    require(answer > 0, "Invalid price");

    (, , , bool isHealthy) = priceFeed.getHealthStatus();
    require(isHealthy, "Stale price");

    decimals_ = priceFeed.decimals();
    price = answer;
    updatedAt = _updatedAt;
}
```

## Dữ Liệu Lịch Sử

Oracle lưu trữ tất cả dữ liệu round lịch sử on-chain. Mỗi lần cập nhật giá tạo ra một round mới với `roundId` tăng dần.

```solidity
(uint80 roundId, int256 answer, , uint256 updatedAt, ) =
    priceFeed.getRoundData(targetRoundId);
```

Các hàm helper view bổ sung được cung cấp bởi Chiliz feed:

| Hàm                                | Trả về                                      |
| ---------------------------------- | ------------------------------------------- |
| `latestAnswer()`                   | Giá mới nhất, hoặc `0` nếu không có         |
| `latestTimestamp()`                | `updatedAt` mới nhất, hoặc `0` nếu không có |
| `latestRound()`                    | ID round hiện tại                           |
| `getAnswer(uint80 roundId)`        | Giá cho một round cụ thể, hoặc `0`          |
| `getTimestamp(uint80 roundId)`     | Timestamp cho một round cụ thể, hoặc `0`    |
| `getRoundsData(uint80[] roundIds)` | Mảng `RoundData` hàng loạt                  |
| `roundExists(uint80 roundId)`      | `true` nếu `updatedAt > 0`                  |

## Sự Kiện

Mỗi hợp đồng `PriceFeed` phát ra:

* **`AnswerUpdated(int256 indexed current, uint80 indexed roundId, uint256 updatedAt)`**: phát ra mỗi lần cập nhật giá. Lọc theo giá hoặc round.
* **`NewRound(uint80 indexed roundId, address indexed startedBy, uint256 startedAt)`**: phát ra khi bắt đầu một round mới. Lọc theo round hoặc theo địa chỉ đã bắt đầu nó.

## Hàm Khám Phá (OracleFactoryReader)

| Hàm                                     | Mô tả                                                             |
| --------------------------------------- | ----------------------------------------------------------------- |
| `getActiveOracles()`                    | Trả về tất cả các cặp đang hoạt động với địa chỉ oracle của chúng |
| `getAllOracles()`                       | Trả về tất cả oracle, bao gồm cả các oracle không hoạt động       |
| `getOraclesByPairs(string[] pairs)`     | Phân giải nhiều tên cặp thành địa chỉ oracle trong một lần gọi    |
| `getOracleHealthStatus(address oracle)` | Trạng thái sức khỏe cho một oracle duy nhất                       |
| `getAllOracleHealthStatus()`            | Trạng thái sức khỏe cho mọi oracle trong hệ thống                 |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.chiliz.com/vi/phat-trien/nang-cao/nguon-gia-on-chain/doc-gia.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
