0Pricing
Web3 & DApp Development Fundamentals · Leçon

Récupérer des données hors chaîne

Mettez en œuvre des contrats intelligents qui demandent et reçoivent des données d’oracles Chainlink, comme des flux de prix ou des appels à des API externes.

Récupérer des données hors chaîne est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 3 sur 3. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 3 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Data Beyond the Blockchain

Smart contracts are powerful, but they operate in isolation on the blockchain. They can't directly access information from the 'real world' like current stock prices, weather data, or external API responses.

This limitation is known as the oracle problem. To overcome it, we use oracles.

Chainlink's Data Solution

Chainlink is a decentralized oracle network designed to securely connect smart contracts with off-chain data and services.

  • It acts as a bridge between the blockchain and external systems.
  • Chainlink nodes collect data from various sources.
  • They then deliver this data to smart contracts in a reliable and verifiable way.

Real-Time Price Feeds

One of the most common and critical uses of Chainlink is providing price feeds. These feeds deliver up-to-date market prices for cryptocurrencies, commodities, and other assets directly to your smart contracts.

This is crucial for DeFi applications, lending protocols, and derivatives.

Interacting with Price Feeds

To get data from a Chainlink price feed, your smart contract interacts with a specific data feed contract deployed on the blockchain.

These data feed contracts all implement a standard interface called AggregatorV3Interface. This makes it easy for your contract to read the data.

How to Get Price Data

The primary function we use to fetch the latest price from an AggregatorV3Interface is latestRoundData().

It returns several pieces of information, including the actual price, when it was updated, and the round ID.

Build a Price Reader

Let's write a simple Solidity contract that reads the latest ETH/USD price from a Chainlink price feed. You can try running this in Remix, using the Sepolia testnet.

The address 0x694AA1769357215Ee4f0fFf93d2d05d454e5f5c4 is for the ETH/USD price feed on Sepolia.

pragma solidity ^0.8.0;

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

contract PriceReader {
    AggregatorV3Interface internal priceFeed;

    constructor() {
        // ETH/USD price feed address on Sepolia testnet
        priceFeed = AggregatorV3Interface(0x694AA1769357215Ee4f0fFf93d2d05d454e5f5c4);
    }

    function getLatestPrice() public view returns (
        uint80 roundId,
        int answer,
        uint256 startedAt,
        uint256 updatedAt,
        uint80 answeredInRound
    ) {
        // Get the latest price data from the feed
        (roundId, answer, startedAt, updatedAt, answeredInRound) = priceFeed.latestRoundData();
    }

    function getDecimals() public view returns (uint8) {
        // Get the number of decimals used by the price feed
        return priceFeed.decimals();
    }
}

Decoding Price Data

The answer returned by latestRoundData() is the actual price, but it's an int and scaled by a certain number of decimals.

You must call getDecimals() to know how many decimal places to account for. For example, if answer is 180000000000 and decimals is 8, the price is 1800.00000000.

Beyond Prices: Custom Data

While price feeds are common, Chainlink can also fetch almost any other type of off-chain data, or even generate verifiable randomness.

This requires a more generalized approach where your contract makes a request to a Chainlink node for specific data, and the node responds by calling back your contract.

The Request & Fulfill Pattern

For custom data, Chainlink uses a two-step process:

  1. Request: Your smart contract sends a request to a Chainlink oracle contract, specifying the data source (e.g., an API endpoint) and the job ID.
  2. Fulfill: A Chainlink node processes the request, fetches the off-chain data, and then sends a transaction back to your smart contract, calling a designated 'fulfill' function with the requested data.

This ensures data is delivered securely on-chain.

Oracle Integration Check

Consider a smart contract that needs to get the current weather conditions for a specific city. Which of the following best describes how a Chainlink oracle would typically facilitate this?

Lesson Summary

We've explored how smart contracts fetch off-chain data using Chainlink. You learned about:

  • The oracle problem and Chainlink's solution.
  • Interacting with Chainlink Price Feeds using AggregatorV3Interface.
  • The latestRoundData() function and interpreting its output.
  • The general 'request and fulfill' pattern for custom data requests.

Fetching external data securely is vital for building robust DApps!

Questions Fréquemment Posées

La leçon « Récupérer des données hors chaîne » est-elle gratuite ?

Oui — le texte complet de « Récupérer des données hors chaîne » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 3 leçons au total.

Qu'est-ce que j'apprendrai dans « Récupérer des données hors chaîne » ?

Mettez en œuvre des contrats intelligents qui demandent et reçoivent des données d’oracles Chainlink, comme des flux de prix ou des appels à des API externes. Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?

Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 3.

Combien de temps prend la leçon « Récupérer des données hors chaîne » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?

Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Le problème des oracles
  2. Principes fondamentaux de Chainlink
  3. Récupérer des données hors chaîne
← Retour à Web3 & DApp Development Fundamentals