如何通过以太坊美元价格更新NFT铸币价格?

问题描述 投票:0回答:2

我正在尝试构建一个智能合约,为其他人铸造的每个 NFT 提供固定的美元价格,而他们需要用 ETH 支付。但我发现一个问题是,ETH 的价格总是在变化,每次更新 ETH 的 NFT 价格都需要一些 Gas 费,长期来看维护成本会很高。有没有办法定期更新智能合约内的 ETH 价格,或者手动更新是唯一的方法吗?

或者我可能必须取消 NFT 价格限制并完全依赖前端来处理定价部分。但我认为这太冒险了。

ethereum solidity smartcontracts nft
2个回答
2
投票

您可以使用 Chainlink 数据源返回以美元计的 ETH 价格。

模拟器中没有数据源(例如 Ganache 或 Remix IDE 内置网络),因此您可以在以太坊主网的本地分支上测试此代码段。

pragma solidity 0.8;

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

contract MyContract {
    AggregatorV3Interface priceFeed;
    // 18 decimals
    uint256 requiredPriceInUsd = 1000 * 1e18;

    constructor() {
        // https://etherscan.io/address/0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419#code
        // Chainlink ETH/USD Price Feed for Ethereum Mainnet
        priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
    }

    // returns amount of wei
    function getRequiredPriceInWei() public view returns (uint256) {
        (,int answer,,,) = priceFeed.latestRoundData();

        // returned price is 8 decimals, convert to 18 decimals
        uint256 ethUsdPrice = uint256(answer) * 1e10;

        // 36 decimals / 18 decimals = 18 decimals
        return (requiredPriceInUsd * 1e18) / ethUsdPrice;
    }
}

我的测试输出:

  • answer
    122884000000
    (1228 美元和 8 位小数)
  • getRequiredPriceInWei()
    返回的值为
    813775593242407473
    (wei 的,相当于 1,000 美元约 0.8 ETH)

0
投票

Chainlink 数据源是一个不错的选择。他们每 1 小时更新一次 ETH 价格。您可以导入其 Aggregator V3 接口合约并使用名为priceFeed 的函数。它会返回给你 eth 价格,你可以使用它。 好处是它有查看功能,所以你甚至不需要支付任何汽油费。

© www.soinside.com 2019 - 2024. All rights reserved.