> 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/pt-br/desenvolver/avancado/feeds-de-preco-on-chain/lendo-precos.md).

# Lendo preços

## Passo 1: Encontrar o Endereço do Oracle

Três maneiras de encontrar o endereço de um contrato `PriceFeed` para um determinado par:

* **Price Oracle Tracker** (mais fácil durante o desenvolvimento): [price-oracle-tracker.vercel.app](https://price-oracle-tracker.vercel.app/?network=mainnet) — exibe todos os pares implantados, preços ao vivo, decimais, heartbeat e endereços.
* **On-chain via OracleFactory**: chame `pairToOracle(string pair)`. Os símbolos dos pares devem ser passados em maiúsculas (ex.: `"PSG/USDT"`) — a factory não normaliza a entrada nas leituras.
* **Em lote on-chain via OracleFactoryReader**: chame `getActiveOracles()` para recuperar todos os pares ativos e seus endereços em uma única chamada.

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

## Passo 2: Conectar Usando a Interface

O contrato `PriceFeed` implementa a `IAggregatorV3Interface` padrão do Chainlink, além de extensões específicas da Chiliz para status de saúde e pausa.

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

## Passo 3: Ler o Preço

{% hint style="warning" %}
**O feed não reverte em estado desatualizado ou pausado — isso é intencional.** `latestRoundData()` reverte com `NoDataAvailable()` se ainda não existirem rounds, mas não verifica se o feed está pausado ou desatualizado. Isso corresponde ao design da Chainlink AggregatorV3Interface: os consumidores são responsáveis por verificar `paused()` e `getHealthStatus()` antes de consumir um preço. Observação: os helpers escalares (`latestAnswer()`, `latestTimestamp()`, `getAnswer()`, `getTimestamp()`) retornam `0` em vez de reverter quando não há dados disponíveis. Consulte as [Melhores Práticas](/pt-br/desenvolver/avancado/feeds-de-preco-on-chain/melhores-praticas.md) para o padrão completo de validação.
{% endhint %}

A função principal é `latestRoundData()`, que retorna o preço atual junto com metadados de round e 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
    }
}
```

Se o seu protocolo utilizar os decimais nativos do feed em vez de normalizar para 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;
}
```

## Dados Históricos

O oracle armazena todos os dados históricos de rounds on-chain. Cada atualização de preço cria um novo round com um `roundId` incremental.

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

Views auxiliares adicionais expostas pelo feed da Chiliz:

| Função                             | Retorna                                    |
| ---------------------------------- | ------------------------------------------ |
| `latestAnswer()`                   | Preço mais recente, ou `0` se nenhum       |
| `latestTimestamp()`                | `updatedAt` mais recente, ou `0` se nenhum |
| `latestRound()`                    | ID do round atual                          |
| `getAnswer(uint80 roundId)`        | Preço de um round específico, ou `0`       |
| `getTimestamp(uint80 roundId)`     | Timestamp de um round específico, ou `0`   |
| `getRoundsData(uint80[] roundIds)` | Array de `RoundData` em lote               |
| `roundExists(uint80 roundId)`      | `true` se `updatedAt > 0`                  |

## Eventos

Cada contrato `PriceFeed` emite:

* **`AnswerUpdated(int256 indexed current, uint80 indexed roundId, uint256 updatedAt)`**: emitido a cada atualização de preço. Filtre por preço ou round.
* **`NewRound(uint80 indexed roundId, address indexed startedBy, uint256 startedAt)`**: emitido quando um novo round começa. Filtre por round ou pelo endereço que o iniciou.

## Funções de Descoberta (OracleFactoryReader)

| Função                                  | Descrição                                                                      |
| --------------------------------------- | ------------------------------------------------------------------------------ |
| `getActiveOracles()`                    | Retorna todos os pares ativos com seus endereços de oracle                     |
| `getAllOracles()`                       | Retorna todos os oracles, incluindo os inativos                                |
| `getOraclesByPairs(string[] pairs)`     | Resolve múltiplos nomes de pares para endereços de oracle em uma única chamada |
| `getOracleHealthStatus(address oracle)` | Status de saúde de um único oracle                                             |
| `getAllOracleHealthStatus()`            | Status de saúde de todos os oracles no sistema                                 |


---

# 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/pt-br/desenvolver/avancado/feeds-de-preco-on-chain/lendo-precos.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.
