Để lấy dữ liệu từ các data feed, chúng ta chỉ cần đọc dữ liệu từ oracle contract được cung cấp bởi Chainlink.
Importing
Chúng ta giao tiếp với oracle contract bằng cách sử dụng interface AggregatorV3Interface
. Interface này có thể được import trực tiếp từ GitHub (nếu dùng Remix) hoặc thông qua NPM (nếu dùng các IDE khác).
Cú pháp import:
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
AggregatorV3Interface
Sau khi import interface thì ta cần biết địa chỉ của oracle contract cần sử dụng1. Chẳng hạn nếu ta muốn biết tỷ giá giữa ETH và USD của mạng Sepolia thì địa chỉ của contract sẽ là: 0x694AA1769357215DE4FAC081bf1f309aDC325306
.
Ta tạo ra một consumer contract như sau:
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceConsumerV3 {
AggregatorV3Interface internal priceFeed;
constructor() {
priceFeed = AggregatorV3Interface(0x694AA1769357215DE4FAC081bf1f309aDC325306);
}
}
Price Feed
Để lấy tỷ giá từ price feed, ta cần gọi sử dụng hàm latestRoundData
. Hàm này sẽ trả về một tuple gồm những thông tin sau đây:
function latestRoundData() external view returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
Trong đó, answer
chính là tỷ giá.
Ta viết một hàm để lấy tỷ giá mới nhất và lưu vào biến price
như sau:
function getLatestPrice() public view returns (int) {
(
/* uint80 roundId */,
int price,
/*uint startedAt*/,
/*uint updatedAt*/,
/*uint80 answeredInRound*/
) = dataFeed.latestRoundData();
return price;
}
Giá trị nhận được khi gọi hàm có thể là:
186164000000
Có thể thấy, giá trị này không chứa dấu phẩy hay dấu chấm nên ta không biết được phần nào là phần nguyên và phần nào là phần thập phân.
Ta có thể gọi sử dụng hàm decimals
của price feed để biết được có bao nhiêu chữ số sau ở phần thập phân như sau:
function getDecimals() public view returns (uint8) {
uint8 decimals = priceFeed.decimals();
return decimals;
}
Nếu kết quả là 8
thì ta biết được 1 ETH tương đương với 1861
USD.
Footnotes
-
Tham khảo thêm Chainlink Data Feeds | Chainlink Documentation. ↩