Solidity
如何在智能合約中獲取 eth 的價格(以 INR 為單位)?
我想創建一個像 DAI 這樣的穩定幣,但我不想將其與美元掛鉤,而是將其與 INR 掛鉤。問題是我無法找到 ETH 到 INR 的連結價格。
有
INR/USD
數據饋送可以讓我們計算ETH/INR
, 使用ETH/USD
. 您可以按照官方文件中的這個範例進行操作。面額公式如下所示:
這是您可以用作起點的範常式式碼:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /** * Network: Mainnet * Base: ETH/USD * Base Address: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 * Quote: INR/USD * Quote Address: 0x605D5c2fBCeDb217D7987FC0951B5753069bC360 * Decimals: 8 */ /** * THIS IS AN EXAMPLE CONTRACT THAT USES HARDCODED VALUES FOR CLARITY. * THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE. * DO NOT USE THIS CODE IN PRODUCTION. */ contract PriceConverter { function getDerivedPrice(address _base, address _quote, uint8 _decimals) public view returns (int256) { require(_decimals > uint8(0) && _decimals <= uint8(18), "Invalid _decimals"); int256 decimals = int256(10 ** uint256(_decimals)); ( , int256 basePrice, , , ) = AggregatorV3Interface(_base).latestRoundData(); uint8 baseDecimals = AggregatorV3Interface(_base).decimals(); basePrice = scalePrice(basePrice, baseDecimals, _decimals); ( , int256 quotePrice, , , ) = AggregatorV3Interface(_quote).latestRoundData(); uint8 quoteDecimals = AggregatorV3Interface(_quote).decimals(); quotePrice = scalePrice(quotePrice, quoteDecimals, _decimals); return basePrice * decimals / quotePrice; } function scalePrice(int256 _price, uint8 _priceDecimals, uint8 _decimals) internal pure returns (int256) { if (_priceDecimals < _decimals) { return _price * int256(10 ** uint256(_decimals - _priceDecimals)); } else if (_priceDecimals > _decimals) { return _price / int256(10 ** uint256(_priceDecimals - _decimals)); } return _price; } }