0Pricing
Web3 & DApp Development Fundamentals · 课时

获取链下数据

实现能够向 Chainlink 预言机请求并接收数据的智能合约,例如价格馈送或外部 API 调用结果。

获取链下数据 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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:

  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!

常见问题解答

「获取链下数据」课时是免费的吗?

是的 — 「获取链下数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 3 节课。

「获取链下数据」这节课中我会学到什么?

实现能够向 Chainlink 预言机请求并接收数据的智能合约,例如价格馈送或外部 API 调用结果。 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「获取链下数据」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 预言机问题
  2. Chainlink 基础
  3. 获取链下数据
← 返回 Web3 & DApp Development Fundamentals