오프체인 데이터 가져오기
가격 피드나 외부 API 호출과 같은 데이터를 Chainlink 오라클에 요청하고 수신하는 스마트 계약을 구현합니다.
오프체인 데이터 가져오기은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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:
- 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.
- 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!
자주 묻는 질문
“오프체인 데이터 가져오기” 강의는 무료인가요?
네 — “오프체인 데이터 가져오기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
“오프체인 데이터 가져오기”에서 뭘 배우나요?
가격 피드나 외부 API 호출과 같은 데이터를 Chainlink 오라클에 요청하고 수신하는 스마트 계약을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.
“오프체인 데이터 가져오기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 오라클 문제
- Chainlink 기초
- 오프체인 데이터 가져오기