本文最后更新于 2024-04-24,本文发布时间距今超过 90 天, 文章内容可能已经过时。最新内容请以官方内容为准

Chainlink Data Feed

Static Badge
Static Badge

The Chainlink Data Feed is a decentralized oracle network that provides real-time data feeds for a variety of assets. It is designed to be used by smart contracts to fetch data from external sources such as weather, stock prices, and other data sources.

Chainlink Data Feeds 又称喂价,这项服务可以让用户的智能合约以最快的方式获得特定资产标的价格,不论你使用的是链上的智能合约和还是链下应用,都可以通过单一请求,从 Chainlink Data Feeds 获得资产的价格数据。

2. Usage

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

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract DataFeedTask {
    AggregatorV3Interface internal linkPriceFeed;
    AggregatorV3Interface internal btcPriceFeed;
    AggregatorV3Interface internal ethPriceFeed;
    address public owner;

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }

    /**
     * 通过 Remix 部署在非本地环境中时
     * 通过 https://docs.chain.link/data-feeds/price-feeds/addresses,获得 Aggregator Sepolia 测试网合约地址
     *
     */
    constructor(address _linkPriceFeed, address _btcPriceFeed, address _ethPriceFeed) {
        owner = msg.sender;
        // from web
        // LINK / USD: 0xc59E3633BAAC79493d908e63626716e204A45EdF
        // BTC / USD 0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43
        // ETH / USD: 0x694AA1769357215DE4FAC081bf1f309aDC325306
        linkPriceFeed = AggregatorV3Interface(address(_linkPriceFeed));
        btcPriceFeed = AggregatorV3Interface(address(_btcPriceFeed));
        ethPriceFeed = AggregatorV3Interface(address(_ethPriceFeed));
    }

    /**
     * 获得 link/usd 的价格数据
     */
    function getLinkLatestPrice() public view returns (int256) {
        (,int256 answer,,,) = linkPriceFeed.latestRoundData();
        return answer;
    }

    /**
     * 获得 btc/usd 的价格数据
     */
    function getBtcLatestPrice() public view returns (int256) {
        (,int256 answer,,,) = btcPriceFeed.latestRoundData();
        return answer;
    }

    /**
     * 获得 eth/usd 的价格数据
     */
    function getEthLatestPrice() public view returns (int256) {
        (,int256 answer,,,) = ethPriceFeed.latestRoundData();
        return answer;
    }

    /**
     * 获取 link/usd, btc/usd, eth/usd 价格
     */
    function getLinkPriceFeed() public view returns (AggregatorV3Interface) {
        return linkPriceFeed;
    }

    function getBtcPriceFeed() public view returns (AggregatorV3Interface) {
        return btcPriceFeed;
    }

    function getEthPriceFeed() public view returns (AggregatorV3Interface) {
        return ethPriceFeed;
    }
}

4. More about Token conversion

  • BTC / USD = 10 ** 8
  • ETH / USD = 10 ** 8
  • LINK / USD = 10 ** 8