Created
May 26, 2026 03:53
-
-
Save zouzanyan/3a3b7f4d1028ca3bb5bbcb4a72fd237f to your computer and use it in GitHub Desktop.
chainlink中获取btc价格示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // SPDX-License-Identifier: MIT | |
| pragma solidity ^0.8.20; | |
| /* | |
| Chainlink BTC/USD Price Feed | |
| Network: Sepolia | |
| */ | |
| 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 BTCPriceFullData { | |
| AggregatorV3Interface internal dataFeed; | |
| constructor() { | |
| // BTC / USD feed on Sepolia | |
| dataFeed = AggregatorV3Interface( | |
| 0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43 | |
| ); | |
| } | |
| /* | |
| 获取基础信息 | |
| */ | |
| function getFeedInfo() | |
| public | |
| view | |
| returns ( | |
| string memory description, | |
| uint8 decimals, | |
| uint256 version | |
| ) | |
| { | |
| description = dataFeed.description(); | |
| decimals = dataFeed.decimals(); | |
| version = dataFeed.version(); | |
| } | |
| /* | |
| 获取完整价格数据 | |
| */ | |
| function getLatestRoundData() | |
| public | |
| view | |
| returns ( | |
| uint80 roundId, | |
| int256 answer, | |
| uint256 startedAt, | |
| uint256 updatedAt, | |
| uint80 answeredInRound | |
| ) | |
| { | |
| ( | |
| roundId, | |
| answer, | |
| startedAt, | |
| updatedAt, | |
| answeredInRound | |
| ) = dataFeed.latestRoundData(); | |
| } | |
| /* | |
| 获取处理后的BTC价格 | |
| 去掉8位小数 | |
| */ | |
| function getReadablePrice() | |
| public | |
| view | |
| returns (int256) | |
| { | |
| ( | |
| , | |
| int256 answer, | |
| , | |
| , | |
| ) = dataFeed.latestRoundData(); | |
| return answer / int256(10 ** uint256(dataFeed.decimals())); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment