0Pricing
Blockchain Smart Contracts with Solidity · 강의

Chainlink 오라클 통합

Chainlink를 사용하여 스마트 계약을 실제 세계의 데이터, 이벤트, 계산에 안전하게 연결하는 방법을 학습합니다.

Chainlink 오라클 통합은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“Chainlink 오라클 통합” 강의는 무료인가요?

네 — “Chainlink 오라클 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

“Chainlink 오라클 통합”에서 뭘 배우나요?

Chainlink를 사용하여 스마트 계약을 실제 세계의 데이터, 이벤트, 계산에 안전하게 연결하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Chainlink 오라클 통합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 오라클 문제 이해하기
  2. Chainlink 오라클 통합
  3. 오프체인 데이터 조회 처리
  4. 사용자 지정 오라클 컨트랙트 구축
← Blockchain Smart Contracts with Solidity(으)로 돌아가기