如何使用JavaScript或Solidity在前端展示加密通证和法币价格

在这里插入图片描述
原文链接:https://blog.chain.link/how-to-display-crypto-and-fiat-prices-on-a-frontend/

Web3开发者经常选择在前端显示平台或协议的原生加密通证,而不是显示与法币的转换结果。虽然这样做容易让用户聚焦原生通证,但显示法币转换结果可能是一个更好的选择。为加密通证定价要求对通证当前价值有了解,而通证的价值往往是波动的,而且还为新用户创造了一个不太受欢迎的体验,许多人对参考美元或他们的本地货币感到更舒服。

幸运的是,通过Chainlink Data Feeds,ETH和美元等货币之间的转换非常简单,这意味着开发者只需几个简单的步骤就能为用户提供更好的体验。本技术教程阐述了如何使用ETH/USD Chainlink Price Feed在前端显示加密通证和法币价格。

什么是Chainlink Data Feeds?

Chainlink Data Feeds是一套提供安全和可靠的真实世界数据源的智能合约。它们由独立的、高信誉的和地理上分布的节点运营商提供支持,这有助于确保返回数据的可靠性。例如,ETH/USD,目前利用31个独立的预言机,或者说信息来源,用于确定当前ETH对美元的价格的可信答案。

为什么我们需要31个信息源来获取相同的信息?使用多个来源来汇总一个有效的响应,意味着不可能有单点故障问题,并防止数据被篡改。

关于提供者(Provider)的说明

当与智能合约互动时,必须有一个Web3连接的提供者。通常,这可以通过用户的钱包连接获得。如果没有,或者你不需要连接用户的钱包,你可以通过以下方式完成同样的功能:

const provider = new ethers.providers.JsonRpcProvider('RPC_URL_HERE');

RPC_URL_HERE可以从一个节点提供商那里获得,如Alchemy, Infura, MoralisQuickNode。提供者(provider)是我们通往区块链的 “网关”。

本教程的另一个要求是一个以太坊JavaScript库。在这个例子中,我使用的是ethers库。你需要安装它,才能让本文案例工作。

npm install --save ethers

使用JavaScript部署ETH/USD转换

现在是需要在前端显示ETH/USD价格的代码。

如果你想跟着做,这个例子的代码可以在例子库中找到。按照README.md中的说明,在本地运行这个例子。这个例子使用Svelte,但同样的概念应该适用于任何前端JavaScript框架,如React或Vue。在SmartContract的GitHub仓库中,你还可以使用其他几个入门套件。

这段代码可以通过导入语句在前端使用:

import { getETHPrice } from '../utils/getETHPrice';

然后,将结果存储为以美元计算的ETH价格:

value = await getETHPrice();

假设ethAmount是要转换的ETH数额,则使用此值从ETH转为美元。

usdValue = Number(ethAmount * value).toFixed(2);

这里是完整的文件:

~/utils/getEthPrice.js

import { ethers } from 'ethers';


export async function getETHPrice() {
    const provider = new ethers.providers.JsonRpcProvider('RPC_URL_HERE');

    // This constant describes the ABI interface of the contract, which will provide the price of ETH
    // It looks like a lot, and it is, but this information is generated when we compile the contract
    // We need to let ethers know how to interact with this contract.
    const aggregatorV3InterfaceABI = [
        {
            inputs: [],
            name: 'decimals',
            outputs: [{ internalType: 'uint8', name: '', type: 'uint8' }],
            stateMutability: 'view',
            type: 'function'
        },
        {
            inputs: [],
            name: 'description',
            outputs: [{ internalType: 'string', name: '', type: 'string' }],
            stateMutability: 'view',
            type: 'function'
        },
        {
            inputs: [{ internalType: 'uint80', name: '_roundId', type: 'uint80' }],
            name: 'getRoundData',
            outputs: [
                { internalType: 'uint80', name: 'roundId', type: 'uint80' },
                { internalType: 'int256', name: 'answer', type: 'int256' },
                { internalType: 'uint256', name: 'startedAt', type: 'uint256' },
                { internalType: 'uint256', name: 'updatedAt', type: 'uint256' },
                { internalType: 'uint80', name: 'answeredInRound', type: 'uint80' }
            ],
            stateMutability: 'view',
            type: 'function'
        },
        {
            inputs: [],
            name: 'latestRoundData',
            outputs: [
                { internalType: 'uint80', name: 'roundId', type: 'uint80' },
                { internalType: 'int256', name: 'answer', type: 'int256' },
                { internalType: 'uint256', name: 'startedAt', type: 'uint256' },
                { internalType: 'uint256', name: 'updatedAt', type: 'uint256' },
                { internalType: 'uint80', name: 'answeredInRound', type: 'uint80' }
            ],
            stateMutability: 'view',
            type: 'function'
        },
        {
            inputs: [],
            name: 'version',
            outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
            stateMutability: 'view',
            type: 'function'
        }
    ];
    // The address of the contract which will provide the price of ETH
    const addr = '0x8A753747A1Fa494EC906cE90E9f37563A8AF630e';
    // We create an instance of the contract which we can interact with
    const priceFeed = new ethers.Contract(addr, aggregatorV3InterfaceABI, provider);
    // We get the data from the last round of the contract 
    let roundData = await priceFeed.latestRoundData();
    // Determine how many decimals the price feed has (10**decimals)
    let decimals = await priceFeed.decimals();
    // We convert the price to a number and return it
    return Number((roundData.answer.toString() / Math.pow(10, decimals)).toFixed(2));
}

我们需要的代码中大部分是aggregatorV3InterfaceABI或ABI。这是我们将与之互动的合约的数据结构,我们需要让ethers知道这些。通常,你可能会在前端项目中把这些存储在单独的JSON文件中。在本例中,它被包含在utils文件中,这样是把所有内容都放在一起。

// The address of the contract which will provide the price of ETH
const addr = '0x8A753747A1Fa494EC906cE90E9f37563A8AF630e';

这个合约地址将根据网络或价格对的变化而变化;你可以使用这些Data Feed合约地址中的任何一个。

// We get the data from the last round of the contract 
let roundData = await priceFeed.latestRoundData();
// Determine how many decimals the price feed has (10**decimals)
let decimals = await priceFeed.decimals();
// We convert the price to a number and return it
return Number((roundData.answer.toString() / Math.pow(10, decimals)).toFixed(2));

与合约的交互是直接的。我们调用latestRoundData,它返回:
roundId:轮次ID。
answer: 价格。
startedAt:该轮次开始的时间戳。
updatedAt:这一轮更新的时间戳。
answeredInRound:计算结果的轮次ID。我们对answer感兴趣。这将是ETH的价格,有一个小的警告。我们需要知道答案中包含的小数点的数量。这就是decimals的作用。它返回要包含的小数位数。

我们使用answerdecimal来返回ETH的价格:

return Number((roundData.answer.toString() / Math.pow(10, decimals)).toFixed(2));

利用价格数据

一旦我们有了单个ETH的价格,我们可以用它来轻松地将ETH转换成美元价格。在下面的例子中,rawETH是一个合约的余额返回的字符串。

<!-- Display the raw ETH -->
{Number(rawETH).toFixed(8)} ETH
<!-- Display the ETH converted to USD -->
$ {(Number(rawETH) * value).toFixed(2)} USD

Chainlink Data Feeds提供了一个可靠的解决方案,它使用安全的方法将资产价值从ETH转换为美元。

使用Solidity

到目前为止,在一个前端应用程序中创建一个实用功能似乎很简单。但是,如果我们能够消除前端开发者对价格的担心,并为他们处理价格问题呢?

只要对你的合约做一些修改,你就可以向终端用户提供当前的价格数据–他们需要担心的是连接到你的合约。这就简化了所需的前端工作。让我们来看看一个合约的例子。

pragma solidity ^0.8.0;
// Import the chainlink Aggregator Interface
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

// Create the contract
contract YourAwesomeContract { 
// Declare the priceFeed as an Aggregator Interface
    AggregatorV3Interface internal priceFeed;

    constructor() {
/** Define the priceFeed
* Network: Rinkeby
    * Aggregator: ETH/USD
      * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
      */
        priceFeed = AggregatorV3Interface(
            0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
        );
    } 

// OTHER CONTRACT LOGIC HERE

    /**
    * Returns the latest price and # of decimals to use
    */
    function getLatestPrice() public view returns (int256, uint8) {
// Unused returned values are left out, hence lots of ","s
        (, int256 price, , , ) = priceFeed.latestRoundData();
        uint8 decimals = priceFeed.decimals();
        return (price, decimals);
    }
}

首先,我们导入我们在上述前端版本中使用的相同的聚合器接口。

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

然后,我们需要让聚合器知道我们感兴趣的Price Feed的合约地址。

priceFeed = AggregatorV3Interface(
            0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
        );

在我们的getLatestPrice()函数中,我们调用priceFeed.latestRoundData()。priceFeed引用的是我们在上面的getETHPrice利用中使用的同一个合约。它返回:

roundId:轮次ID。
answer: 价格。
startedAt:该轮次开始的时间戳。
updatedAt:这一轮更新的时间戳。
answeredInRound:计算答案的那一轮的ID。

这里的代码可能看起来有点奇怪。我们唯一感兴趣的值是answer字段。因此,我们不把其他的值分配给变量。把它们跳过,可以防止储存未使用的数据。

(, int256 price, , , ) = priceFeed.latestRoundData();

对前端的改变

现在,价值数据已经包含在你的智能合约中,我们只需要从前端访问合约中该价值数据。

async function getETHPrice() {
        let [ethPrice, decimals] = await 
yourAwesomeContract.getLatestPrice();
        ethPrice = Number(ethPrice / Math.pow(10, 
decimals)).toFixed(2);
        return ethPrice;
    }

这将为我们合约的消费者创造一个更简单的界面,因为他们不需要了解预言机或导入一个单独的ABI。

总结

在这个技术教程中,我们展示了如何轻松地将Chainlink数据源集成到你的DApp中,使用户能够轻松使用USD/ETH价格转换。有大量适用于加密通证和法定货币的Chainlink Price Feeds,开发者们可以调整上面的使用步骤使用适用于他们的价格数据。
获取更多关于Chainlink的信息,请访问chain.link或在docs.chain.link阅读文档。要讨论集成问题,请联系专家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个简单投票dapp的实现步骤,包括solidity的编写、智能合约的部署、前端JavaScript和HTML的实现。 1. Solidity代码 首先,我们需要编写一个solidity合约来实现投票功能。以下是一个简单的投票合约: ``` pragma solidity ^0.8.0; contract Voting { mapping (bytes32 => uint8) public votesReceived; bytes32[] public candidateList; constructor(bytes32[] memory candidateNames) { candidateList = candidateNames; } function voteForCandidate(bytes32 candidate) public { require(validCandidate(candidate)); votesReceived[candidate] += 1; } function totalVotesFor(bytes32 candidate) public view returns (uint8) { require(validCandidate(candidate)); return votesReceived[candidate]; } function validCandidate(bytes32 candidate) public view returns (bool) { for(uint i = 0; i < candidateList.length; i++) { if(candidateList[i] == candidate) { return true; } } return false; } } ``` 该合约包括一个候选人列表,以及一个投票功能。候选人列表作为构造函数的参数传入,投票功能接受一个候选人的名称,如果该名称在候选人列表中,就将该候选人的投票数加一。 2. 部署智能合约 我们需要将该合约部署到以太坊网络上,以便我们在dapp中使用。可以使用Remix等工具来编译和部署智能合约。 3. 前端JavaScript和HTML代码 接下来,我们需要使用JavaScript和HTML来构建一个简单的前端界面,以便用户可以在网页上进行投票。 以下是一个简单的HTML代码,它包括一个表单,可以让用户输入投票的候选人名称: ``` <!DOCTYPE html> <html> <head> <title>Voting Dapp</title> </head> <body> <h1>Voting Dapp</h1> <form> <label for="candidate">Candidate:</label> <input type="text" id="candidate" name="candidate"><br><br> <input type="button" value="Vote" onclick="vote()"> </form> <div id="result"></div> <script src="web3.min.js"></script> <script src="voting.js"></script> </body> </html> ``` 在该HTML页面中,我们引入了web3.js库和voting.js脚本。web3.js库可以让我们与以太坊网络进行交互,voting.js脚本则包含了与智能合约交互的代码。 以下是一个简单的JavaScript代码,它过web3.js库连接到以太坊网络,并与智能合约进行交互: ``` var web3 = new Web3(Web3.givenProvider); var contractInstance; $(document).ready(function() { contractInstance = new web3.eth.Contract(abi, contractAddress); }); function vote() { var candidate = $("#candidate").val(); contractInstance.methods.voteForCandidate(web3.utils.asciiToHex(candidate)).send({from: eth.accounts[0]}) .then(function() { return contractInstance.methods.totalVotesFor(web3.utils.asciiToHex(candidate)).call(); }) .then(function(result) { $("#result").html("Total votes for " + candidate + ": " + result); }); } ``` 该代码首先使用web3.js库创建一个web3实例,并过智能合约的abi和地址创建了一个contractInstance。然后,当用户点击“投票”按钮时,它会获取用户输入的候选人名称,并调用智能合约的voteForCandidate方法。投票完成后,该代码还会调用智能合约的totalVotesFor方法,以获取该候选人的总票数,并将其显示在页面上。 综上所述,我们可以过上述代码实现一个简单的投票dapp。当然,这只是一个简单的示例,实际上在实现一个完整的dapp时,还需要考虑安全性、用户体验、性能等方面的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值