0Pricing
Blockchain Smart Contracts with Solidity · Lekcja

Integracja z wyroczniami Chainlink

Dowiedz się, jak używać Chainlink do bezpiecznego łączenia smart kontraktów z rzeczywistymi danymi, zdarzeniami i obliczeniami.

Integracja z wyroczniami Chainlink to bezpłatna lekcja Blockchain Smart Contracts with Solidity na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Blockchain Smart Contracts with Solidity, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Welcome to Chainlink Oracles!

In the previous lesson, we learned about the "oracle problem" – how smart contracts can't directly access real-world data.

Chainlink solves this by acting as a bridge, securely bringing off-chain data onto the blockchain. This lesson will show you how to integrate Chainlink into your Solidity contracts.

Bridging On-Chain & Off-Chain

Chainlink is a decentralized oracle network. It allows your smart contracts to reliably connect with external data sources, APIs, and even traditional payment systems.

  • Decentralized: Multiple independent nodes verify data.
  • Secure: Cryptographic proofs ensure data integrity.
  • Reliable: Data is aggregated from many sources.

Power of Data Feeds

One of Chainlink's most popular features is its Data Feeds. These provide continuously updated price data for cryptocurrencies, commodities, and more.

Instead of requesting data on demand (which can be complex), Data Feeds offer a simpler way to access frequently updated information directly within your contract.

Getting Started: The Interface

To interact with Chainlink Data Feeds, your smart contract needs to know how to "talk" to them. Chainlink provides an interface called AggregatorV3Interface.

This interface defines the functions your contract can call to retrieve data. You'll typically import it into your Solidity file like this:

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);
  function description() external view returns (string memory);
  function version() external view returns (uint256);

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

Initializing the Oracle

Your contract needs to know the specific address of the Chainlink Data Feed it wants to use. This is typically set in the contract's constructor.

For example, to get the ETH/USD price on a testnet, you'd provide the corresponding Data Feed address to initialize your priceFeed variable.

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

interface AggregatorV3Interface {
  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

contract PriceConsumer {
  AggregatorV3Interface internal priceFeed;

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

Fetching Price Data

Once connected, you can call the latestRoundData() function on your priceFeed variable. This function returns several pieces of information.

The most important is answer, which is the actual price data. Other values provide context, like when the data was last updated.

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

interface AggregatorV3Interface {
  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
  function decimals() external view returns (uint8);
}

contract PriceConsumer {
  AggregatorV3Interface internal priceFeed;

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

  function getLatestPrice() public view returns (int256) {
    // We only care about the 'answer' here, so other return values are ignored.
    (, int256 price, , , ) = priceFeed.latestRoundData();
    return price;
  }
}

Deciphering the Data

The answer from latestRoundData() is an int256. For example, if ETH/USD is $2000, the answer might be 200000000000.

You need to divide this by 10 ** priceFeed.decimals() to get the human-readable value. The decimals() function from the interface tells you the scaling factor.

Full Example: ETH/USD Price

Here's a complete, runnable example of a contract that fetches the latest ETH/USD price using Chainlink. You can use a common Sepolia testnet address for demonstration.

Copy and paste this into Remix, compile, and deploy it with the correct Chainlink Data Feed address for your network.

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

// Import Chainlink's AggregatorV3Interface
interface AggregatorV3Interface {
  function decimals() external view returns (uint8);
  function description() external view returns (string memory);
  function version() external view returns (uint256);
  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

contract EthPriceConsumer {
  AggregatorV3Interface internal priceFeed;

  // Constructor takes the address of the Chainlink Data Feed
  // Example for Sepolia ETH/USD:
  // 0x694AA1769357215Ee4f0fFf93d2d05d454eBEaB8
  constructor(address _priceFeedAddress) {
    priceFeed = AggregatorV3Interface(_priceFeedAddress);
  }

  // Function to get the latest ETH/USD price
  function getLatestEthUsdPrice() public view returns (int256) {
    // latestRoundData returns (roundId, answer, startedAt, updatedAt, answeredInRound)
    (, int256 price, , , ) = priceFeed.latestRoundData();
    return price; // Price is returned with 8 decimals (e.g., $2000 becomes 200000000000)
  }

  // Function to get the number of decimals for the price feed
  function getDecimals() public view returns (uint8) {
    return priceFeed.decimals();
  }
}

Production Readiness Notes

When using Chainlink in production, always consider:

  • Gas Costs: Reading from Data Feeds is usually cheap (view function), but making custom requests can cost gas.
  • Network Addresses: Use the correct Data Feed address for your target network (e.g., Mainnet, Sepolia).
  • Error Handling: Implement checks for stale data (updatedAt) or zero values from the oracle for robustness.

Test Your Knowledge

You've learned how to integrate Chainlink Data Feeds. Let's check your understanding.

Integrating Chainlink: Recap

Great job! You've learned how to integrate Chainlink Data Feeds into your Solidity smart contracts.

  • Chainlink bridges off-chain data to the blockchain.
  • You use AggregatorV3Interface to interact with Data Feeds.
  • The contract constructor sets the oracle address.
  • latestRoundData() fetches the price and other info.

In the next lesson, we'll dive deeper into more complex data retrieval patterns, including how to make custom requests for data not available in standard Data Feeds.

Często zadawane pytania

Czy lekcja „Integracja z wyroczniami Chainlink” jest bezpłatna?

Tak — pełny tekst „Integracja z wyroczniami Chainlink” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Blockchain Smart Contracts with Solidity, przejdź na CoddyKit PRO. Kurs Blockchain Smart Contracts with Solidity zawiera 4 lekcji w sumie.

Co nauczysz się w „Integracja z wyroczniami Chainlink”?

Dowiedz się, jak używać Chainlink do bezpiecznego łączenia smart kontraktów z rzeczywistymi danymi, zdarzeniami i obliczeniami. Ćwiczysz Blockchain Smart Contracts with Solidity z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Blockchain Smart Contracts with Solidity?

Nie wymagamy żadnego doświadczenia. Blockchain Smart Contracts with Solidity w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Integracja z wyroczniami Chainlink”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Blockchain Smart Contracts with Solidity?

Tak. Każda lekcja Blockchain Smart Contracts with Solidity zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Wyjaśnienie problemu wyroczni
  2. Integracja z wyroczniami Chainlink
  3. Pobieranie danych off-chain
  4. Tworzenie własnych kontraktów oracle
← Powrót do Blockchain Smart Contracts with Solidity