> 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/pl/tworzenie/zaawansowane/on-chain-feedy-cenowe/odczytywanie-cen.md).

# Odczytywanie cen

Znajdź adres kontraktu PriceFeed, połącz się za pomocą interfejsu Chainlink i odczytaj aktualną cenę z właściwą walidacją.

## Krok 1: Znajdź adres oracle

Trzy sposoby na znalezienie adresu kontraktu `PriceFeed` dla danej pary:

* **Price Oracle Tracker** (najłatwiejszy podczas developmentu): [price-oracle-tracker.vercel.app](https://price-oracle-tracker.vercel.app/?network=mainnet) (pokazuje wszystkie wdrożone pary, ceny na żywo, decimals, heartbeat i adresy).
* **On-chain przez OracleFactory**: wywołaj `pairToOracle(string pair)`. Symbole par muszą być przekazane wielkimi literami (np. `"PSG/USDT"`): fabryka nie normalizuje danych wejściowych przy odczycie.
* **Zbiorowo on-chain przez OracleFactoryReader**: wywołaj `getActiveOracles()`, aby pobrać wszystkie aktywne pary i ich adresy jednym wywołaniem.

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

## Krok 2: Połącz się za pomocą interfejsu

Kontrakt `PriceFeed` implementuje standardowy Chainlink `IAggregatorV3Interface`, plus rozszerzenia specyficzne dla Chiliz dotyczące stanu zdrowia i statusu pauzy.

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

## Krok 3: Odczytaj cenę

{% hint style="warning" %}
**Feed nie revertuje przy nieaktualnym lub wstrzymanym stanie: jest to celowe.** `latestRoundData()` revertuje z `NoDataAvailable()`, jeśli jeszcze nie istnieją żadne rundy, ale nie sprawdza, czy feed jest wstrzymany lub nieaktualny. Odpowiada to projektowi Chainlink AggregatorV3Interface: konsumenci są odpowiedzialni za sprawdzenie `paused()` i `getHealthStatus()` przed skonsumowaniem ceny. Uwaga: skalarne funkcje pomocnicze (`latestAnswer()`, `latestTimestamp()`, `getAnswer()`, `getTimestamp()`) zwracają `0` zamiast revertować, gdy nie ma danych. Zobacz [Najlepsze praktyki](/pl/tworzenie/zaawansowane/on-chain-feedy-cenowe/najlepsze-praktyki.md) po pełny wzorzec walidacji.
{% endhint %}

Podstawową funkcją jest `latestRoundData()`, która zwraca aktualną cenę wraz z metadanymi rundy i znacznikiem czasu.

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

Jeśli Twój protokół używa natywnych dziesiętnych feedu zamiast normalizacji do 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;
}
```

## Dane historyczne

Oracle przechowuje wszystkie historyczne dane rund on-chain. Każda aktualizacja ceny tworzy nową rundę z rosnącym `roundId`.

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

Dodatkowe funkcje pomocnicze widoku udostępniane przez feed Chiliz:

| Funkcja                            | Zwraca                                         |
| ---------------------------------- | ---------------------------------------------- |
| `latestAnswer()`                   | Ostatnia cena lub `0`, jeśli brak danych       |
| `latestTimestamp()`                | Ostatni `updatedAt` lub `0`, jeśli brak danych |
| `latestRound()`                    | Aktualny identyfikator rundy                   |
| `getAnswer(uint80 roundId)`        | Cena dla konkretnej rundy lub `0`              |
| `getTimestamp(uint80 roundId)`     | Znacznik czasu dla konkretnej rundy lub `0`    |
| `getRoundsData(uint80[] roundIds)` | Zbiorcza tablica `RoundData`                   |
| `roundExists(uint80 roundId)`      | `true`, jeśli `updatedAt > 0`                  |

## Zdarzenia

Każdy kontrakt `PriceFeed` emituje:

* **`AnswerUpdated(int256 indexed current, uint80 indexed roundId, uint256 updatedAt)`**: emitowane przy każdej aktualizacji ceny. Filtruj według ceny lub rundy.
* **`NewRound(uint80 indexed roundId, address indexed startedBy, uint256 startedAt)`**: emitowane po rozpoczęciu nowej rundy. Filtruj według rundy lub adresu, który ją rozpoczął.

## Funkcje odkrywania (OracleFactoryReader)

| Funkcja                                 | Opis                                                         |
| --------------------------------------- | ------------------------------------------------------------ |
| `getActiveOracles()`                    | Zwraca wszystkie aktywne pary z ich adresami oracle          |
| `getAllOracles()`                       | Zwraca wszystkie oracle, łącznie z nieaktywnymi              |
| `getOraclesByPairs(string[] pairs)`     | Rozwiązuje wiele nazw par na adresy oracle jednym wywołaniem |
| `getOracleHealthStatus(address oracle)` | Stan zdrowia dla pojedynczego oracle                         |
| `getAllOracleHealthStatus()`            | Stan zdrowia każdego oracle w systemie                       |


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chiliz.com/pl/tworzenie/zaawansowane/on-chain-feedy-cenowe/odczytywanie-cen.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
