Web3 developers often prioritize displaying a platform or protocol’s native crypto token on the frontend instead of converting it to fiat currency. While this keeps users focused on the native token, showing fiat conversions can enhance user experience—especially for newcomers who prefer USD or local currency references.
Fortunately, converting ETH to USD (and vice versa) is straightforward with Chainlink Data Feeds. This tutorial demonstrates how to use the ETH/USD Chainlink Price Feed to display crypto and fiat prices on your frontend.
What Are Chainlink Data Feeds?
Chainlink Data Feeds are secure, reliable smart contracts that provide real-world data. They’re powered by decentralized, high-reputation node operators to ensure data integrity. For example, the ETH/USD feed aggregates data from 31 independent oracles to determine ETH’s current USD price.
Why 31 sources? Multiple sources prevent single points of failure and data manipulation.
Provider Setup
To interact with smart contracts, you need a Web3-connected provider. If users aren’t wallet-connected, use:
const provider = new ethers.providers.JsonRpcProvider('RPC_URL_HERE');Replace RPC_URL_HERE with a node provider URL (e.g., Alchemy or Infura).
Required Library: Install ethers.js:
npm install --save ethersETH/USD Conversion with JavaScript
Step 1: Fetch ETH Price
Import the utility function:
import { getETHPrice } from '../utils/getETHPrice';Store the ETH price in USD:
const value = await getETHPrice();Convert ETH amounts to USD:
const usdValue = Number(ethAmount * value).toFixed(2);Full Code Example
// ~/utils/getEthPrice.js
import { ethers } from 'ethers';
export async function getETHPrice() {
const provider = new ethers.providers.JsonRpcProvider('RPC_URL_HERE');
const aggregatorV3InterfaceABI = [
{
inputs: [],
name: 'decimals',
outputs: [{ internalType: 'uint8', name: '', type: 'uint8' }],
stateMutability: 'view',
type: 'function'
},
// ... (ABI truncated for brevity; include full ABI in actual code)
];
const addr = '0x8A753747A1Fa494EC906cE90E9f37563A8AF630e'; // ETH/USD contract address
const priceFeed = new ethers.Contract(addr, aggregatorV3InterfaceABI, provider);
let roundData = await priceFeed.latestRoundData();
let decimals = await priceFeed.decimals();
return Number((roundData.answer.toString() / Math.pow(10, decimals)).toFixed(2));
}Key Notes:
- The
aggregatorV3InterfaceABIdefines the contract’s interface. latestRoundData()returns price data (e.g.,answer= ETH price).- Adjust for decimals to format the price correctly.
Using Solidity for Price Data
Smart Contract Example
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract YourAwesomeContract {
AggregatorV3Interface internal priceFeed;
constructor() {
priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
}
function getLatestPrice() public view returns (int256, uint8) {
(, int256 price, , , ) = priceFeed.latestRoundData();
uint8 decimals = priceFeed.decimals();
return (price, decimals);
}
}Frontend Integration
Fetch prices directly from the contract:
async function getETHPrice() {
let [ethPrice, decimals] = await yourAwesomeContract.getLatestPrice();
ethPrice = Number(ethPrice / Math.pow(10, decimals)).toFixed(2);
return ethPrice;
}Why This Matters
👉 Chainlink Data Feeds simplify crypto-to-fiat conversions, improving UX for decentralized apps. By integrating these feeds, developers can:
- Reduce frontend complexity.
- Ensure accurate, real-time pricing.
- Enhance trust with transparent data sources.
FAQ
1. Can I use other crypto/fiat pairs?
Yes! Chainlink supports feeds for multiple assets. Replace the contract address with your desired pair (e.g., BTC/USD).
2. How often are prices updated?
Feeds update based on market conditions (e.g., every block or minute). Check the feed’s updatedAt timestamp for freshness.
3. Is Chainlink data reliable?
Absolutely. Decentralized oracles and multi-source aggregation minimize risks like tampering or downtime.
Final Thoughts
Displaying fiat values alongside crypto tokens bridges usability gaps for non-native users. Whether using JavaScript or Solidity, Chainlink’s infrastructure makes this seamless.
👉 Explore more Web3 integrations to elevate your DApp’s functionality!