Decentralized applications (DApps) are at the heart of blockchain innovation, enabling users to interact with decentralized ecosystems seamlessly. In this blog, we’ll walk you through building a DApp on the Conflux eSpace network using Hardhat. We’ll deploy a smart contract and integrate the Pyth oracle to fetch real-time prices of CFX. This guide is perfect for both beginners and developers seeking practical Web3 development experience.
Prerequisites
Before we start, ensure you have the following installed:
-
Node.js and npm
-
Hardhat CLI
-
Metamask wallet with access to Conflux Testnet
-
Basic understanding of Solidity and JavaScript
Step 1: Clone the repo
git clone https://github.com/Vikash-8090-Yadav/Conflux-Tutorial.git
Step 2: install the library
npm install
Step 2: Deploy the smart contract
npx hardhat run scripts/deploy.js
Output
Step 3: Fetch the pricet
Now lets understand the code
Understanding the CFXPrice Smart Contract
This document explains the functionality and purpose of the CFXPrice
smart contract, which integrates the Pyth Network oracle to fetch real-time CFX/USD price data. Below is the code along with a detailed breakdown.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
import "@pythnetwork/pyth-sdk-solidity/IPyth.sol";
import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol";
contract CFXPrice {
IPyth pyth;
bytes32 constant CFX_USD_PRICE_ID = 0x8879170230c9603342f3837cf9a8e76c61791198fb1271bb2552c9af7b33c933;
constructor(address pythContract) {
pyth = IPyth(pythContract);
}
function getCFXPrice(bytes[] calldata priceUpdateData) public payable returns (int64, uint) {
uint fee = pyth.getUpdateFee(priceUpdateData);
pyth.updatePriceFeeds{value: fee}(priceUpdateData);
PythStructs.Price memory price = pyth.getPriceNoOlderThan(CFX_USD_PRICE_ID, 60);
return (price.price, price.conf);
}
}
1. Importing Dependencies
The contract starts by importing necessary libraries from the Pyth SDK:
-
IPyth.sol
: Defines the interface for interacting with the Pyth Network oracle. -
PythStructs.sol
: Provides structured data types for handling price feeds.
2. Key Variables
-
IPyth pyth
: This variable is used to interact with the Pyth oracle contract. -
CFX_USD_PRICE_ID
: A unique identifier for the CFX/USD price feed on the Pyth Network. It ensures the contract retrieves the correct data.
3. Constructor
constructor(address pythContract) {
pyth = IPyth(pythContract);
}
The constructor initializes the Pyth oracle interface with the provided contract address (pythContract
).
4. Function: getCFXPrice
function getCFXPrice(bytes[] calldata priceUpdateData) public payable returns (int64, uint) {
This function retrieves the latest CFX/USD price and its confidence interval from the Pyth Network.
Parameters
-
priceUpdateData
: Encoded data required by the Pyth Network to update its price feeds.
Process
-
Fee Calculation:
uint fee = pyth.getUpdateFee(priceUpdateData);
Calculates the fee required to update the price feeds.
-
Price Feed Update:
pyth.updatePriceFeeds{value: fee}(priceUpdateData);
Sends the calculated fee and updates the price feeds on the Pyth Network.
-
Fetching Price Data:
PythStructs.Price memory price = pyth.getPriceNoOlderThan(CFX_USD_PRICE_ID, 60);
Retrieves the latest price and its confidence interval, ensuring the data is no older than 60 seconds.
-
Return Values:
return (price.price, price.conf);
Returns the fetched price and confidence interval.
Use Case
This smart contract is designed for decentralized applications that require real-time CFX/USD price data. It leverages the Pyth oracle for accurate and reliable information, ensuring up-to-date data within a 60-second window.
Key Benefits
- Accuracy: Ensures real-time and precise price data for DApps.
- Reliability: Uses Pyth Network, a trusted oracle for decentralized data.
- Flexibility: Allows integration with other DApps that require financial data.
Fetch Real-Time CFX Price Using Pyth Oracle and Smart Contract in React
This function demonstrates how to fetch the real-time price of CFX (Conflux Token) using a deployed smart contract on the Conflux eSpace network and the Pyth Oracle. The implementation uses React for state management and ethers.js for blockchain interaction.
Code Snippet
const fetchCFXPrice = async () => {
setLoading(true);
setError(null);
try {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const CFXPrice = new ethers.Contract(
"0x6c5E9F5bFe1399bd0Fe92066347A3a5c2A30A315",
ABI.abi,
signer
);
const connection = new EvmPriceServiceConnection(
"https://hermes.pyth.network"
);
const priceIds = [
"0x8879170230c9603342f3837cf9a8e76c61791198fb1271bb2552c9af7b33c933",
];
const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIds);
const updateFee = ethers.utils.parseEther("0.01");
const tx = await CFXPrice.getCFXPrice(priceUpdateData, {
value: updateFee,
});
setTxHash(tx.hash);
const receipt = await tx.wait();
const [price, confidence] = await CFXPrice.callStatic.getCFXPrice(priceUpdateData, {
value: updateFee,
});
setPrice(ethers.utils.formatUnits(price, 8));
} catch (err) {
console.error("Error occurred:", err);
setError("An error occurred while fetching the price. Please try again.");
} finally {
setLoading(false);
}
};
Conclusion
Integrating a smart contract with an oracle like Pyth enables decentralized applications to access real-time, reliable, and decentralized price feeds. In this tutorial, we demonstrated how to fetch the real-time CFX/USD price using a deployed CFXPrice
smart contract and display it in a React application.
By combining the power of Hardhat for development, ethers.js for blockchain interaction, and Pyth for oracle services, this implementation showcases a seamless workflow for building advanced DApps on the Conflux eSpace network.
This approach opens doors to creating more dynamic and data-driven DApps that can fetch and process real-world data directly on-chain, paving the way for applications like DeFi platforms, NFT marketplaces, and more.
With this foundation, you’re now equipped to explore further and expand your DApp capabilities. Happy coding and welcome to the future of decentralized development!