การจัดการการดึงข้อมูลนอกเชน
นำรูปแบบการร้องขอและรับข้อมูลจาก API ภายนอกผ่าน Chainlink มาใช้ พร้อมรับประกันความถูกต้องครบถ้วนของข้อมูล
การจัดการการดึงข้อมูลนอกเชน เป็นบทเรียน Blockchain Smart Contracts with Solidity ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Blockchain Smart Contracts with Solidity และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Blockchain Smart Contracts with Solidity มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Bridging On-chain & Off-chain
Smart contracts live on the blockchain, isolated from the outside world. But what if your contract needs real-time data, like a cryptocurrency price or a weather report?
This is where oracles come in. In this lesson, we'll learn how to implement patterns for requesting and receiving external data from APIs using Chainlink, ensuring the data is secure and reliable.
The Oracle Request-Response Model
Chainlink acts as a bridge, allowing your smart contract to securely interact with off-chain (external) data sources. It works using a request-response cycle:
- Your smart contract sends a request to a Chainlink oracle network.
- A Chainlink node fetches the data from the specified API.
- The Chainlink node then sends a response back to your contract by calling a specific 'callback' function.
Your Contract: A Chainlink Client
To interact with Chainlink, your Solidity contract needs to inherit from the ChainlinkClient contract provided by Chainlink.
This base contract gives you access to essential functions for building and sending data requests, as well as security features for receiving responses.
Initiating a Data Request
To ask for data, you'll use functions like buildChainlinkRequest and sendChainlinkRequestTo.
buildChainlinkRequest: Prepares the request, specifying details like the Chainlink job ID, your contract's address, and the callback function the oracle should call.sendChainlinkRequestTo: Sends the prepared request to the Chainlink oracle, along with the LINK token fee.
Code: Requesting Live Price Data
Here's a simplified contract showing how to initiate a Chainlink request for external data, like a cryptocurrency price. This contract would be deployed to a test network.
The requestEthPrice function builds the request, specifies the API to call, and sends it to the oracle.
/*
This is a simplified example for explanation.
For a real deployment, replace placeholders like
oracle address, LINK address, jobId, and fee
with values for your chosen Chainlink network.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
contract PriceConsumer is ChainlinkClient {
bytes32 public lastRequestId; // Stores the ID of our last request
uint256 public currentPrice; // Where we'll store the fetched price
address private immutable i_oracle; // Chainlink oracle address
bytes32 private immutable i_jobId; // Specific job ID for the data source
uint256 private immutable i_fee; // Amount of LINK to pay for the request
constructor(address _oracle, address _link, bytes32 _jobId, uint256 _fee) {
setChainlinkToken(_link); // Set the LINK token address
i_oracle = _oracle;
i_jobId = _jobId;
i_fee = _fee;
}
// Function to request a price from a Chainlink oracle
function requestEthPrice() public returns (bytes32) {
// 1. Build the Chainlink request
Chainlink.Request memory request = buildChainlinkRequest(
i_jobId, // The job ID for the oracle
address(this), // Our contract's address
this.fulfillEthPrice.selector // The function the oracle will call back
);
// 2. Add parameters for the Chainlink node (e.g., API URL, path to data)
request.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
request.add("path", "USD"); // Extract the USD value from the JSON response
request.addInt("times", 100000000); // Multiply by 10^8 for fixed-point math
// 3. Send the request to the oracle
lastRequestId = sendChainlinkRequestTo(i_oracle, request, i_fee);
return lastRequestId;
}
// The fulfillEthPrice function will be defined later!
}Tracking Requests with IDs
When you call sendChainlinkRequestTo, it returns a unique identifier: a bytes32 value called the requestId.
- This ID acts like a tracking number for your data request.
- It's essential because multiple requests might be pending, and the
requestIdensures that when the data comes back, your contract knows which request it belongs to.
Always store this requestId in a state variable!
Fulfilling the Data Request
Once the Chainlink node successfully fetches the data, it calls the callback function you specified (e.g., fulfillEthPrice) in your contract.
This function's purpose is to:
- Receive the
requestId(to match it with the original request). - Receive the actual data fetched by the oracle (e.g.,
uint256 _price). - Process and store the data within your contract's state.
Code: Implementing the Callback
Let's complete our PriceConsumer contract by adding the fulfillEthPrice function. This is the function that the Chainlink oracle will call back to with the fetched price.
The recordChainlinkFulfillment modifier and the requestId check are crucial for security and data integrity.
/*
This is a simplified example for explanation.
For a real deployment, replace placeholders like
oracle address, LINK address, jobId, and fee
with values for your chosen Chainlink network.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
contract PriceConsumer is ChainlinkClient {
bytes32 public lastRequestId; // Stores the ID of our last request
uint256 public currentPrice; // Where we'll store the fetched price
address private immutable i_oracle; // Chainlink oracle address
bytes32 private immutable i_jobId; // Specific job ID for the data source
uint256 private immutable i_fee; // Amount of LINK to pay for the request
constructor(address _oracle, address _link, bytes32 _jobId, uint256 _fee) {
setChainlinkToken(_link); // Set the LINK token address
i_oracle = _oracle;
i_jobId = _jobId;
i_fee = _fee;
}
// Function to request a price from a Chainlink oracle
function requestEthPrice() public returns (bytes32) {
Chainlink.Request memory request = buildChainlinkRequest(
i_jobId,
address(this),
this.fulfillEthPrice.selector // Callback function
);
request.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
request.add("path", "USD");
request.addInt("times", 100000000); // Multiply by 10^8
lastRequestId = sendChainlinkRequestTo(i_oracle, request, i_fee);
return lastRequestId;
}
// This is the callback function called by the Chainlink oracle
function fulfillEthPrice(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId) // Security modifier
{
// Crucial: Check if the requestId matches our last sent request
require(lastRequestId == _requestId, "Request ID mismatch!");
currentPrice = _price; // Store the fetched price
}
}Enhancing Data Integrity
Ensuring the integrity of off-chain data is paramount. Chainlink employs several mechanisms, and you should use them:
recordChainlinkFulfillment(_requestId): This modifier (fromChainlinkClient) verifies that the caller is the authorized Chainlink oracle for that specificrequestId.requestIdMatching: Always include arequire(lastRequestId == _requestId, ...)check in your callback. This prevents accidental or malicious fulfillment of an old or unrelated request.- Error Handling: Consider what happens if the oracle fails or returns invalid data. Implement checks and revert if necessary.
Quick Check: Oracle Flow
You've learned about requesting and receiving data from Chainlink oracles.
Consider the following steps involved in a Chainlink request-response cycle:
Recap: Off-chain Data Retrieval
In this lesson, we explored how to enable your smart contracts to interact with external data using Chainlink oracles.
- We learned about the request-response model, where your contract requests data and an oracle node delivers it.
- You saw how to use the
ChainlinkClientbase contract to build and send requests. - We implemented a callback function (e.g.,
fulfillEthPrice) to receive the data. - Finally, we discussed the importance of
requestIdmatching and therecordChainlinkFulfillmentmodifier for data integrity and security.
You can now build contracts that react to real-world events!
คำถามที่พบบ่อย
บทเรียน “การจัดการการดึงข้อมูลนอกเชน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การจัดการการดึงข้อมูลนอกเชน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Blockchain Smart Contracts with Solidity ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Blockchain Smart Contracts with Solidity มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การจัดการการดึงข้อมูลนอกเชน”
นำรูปแบบการร้องขอและรับข้อมูลจาก API ภายนอกผ่าน Chainlink มาใช้ พร้อมรับประกันความถูกต้องครบถ้วนของข้อมูล คุณปฏิบัติ Blockchain Smart Contracts with Solidity ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Blockchain Smart Contracts with Solidity หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Blockchain Smart Contracts with Solidity บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การจัดการการดึงข้อมูลนอกเชน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Blockchain Smart Contracts with Solidity นี้ได้ไหม
ได้ บทเรียน Blockchain Smart Contracts with Solidity ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- อธิบายปัญหาออราเคิล
- การผสานรวมออราเคิล Chainlink
- การจัดการการดึงข้อมูลนอกเชน
- การสร้างสัญญาออราเคิลแบบกำหนดเอง