Creating a Smart Contract with Pyth Oracle Integration
Blockchains are self contained networks that cannot directly access external data, such as asset prices or market trends from the web. This limitation makes oracles essential as they serve as a bridge between on-chain smart contracts and off-chain real world information.
The Pyth Network is a decentralized oracle that provides real-time, high frequency price feeds for assets like cryptocurrencies, stocks, and commodities. This guide will walk you through integrating Pyth's price feed data into your smart contracts and also querying the data from a frontend dapp.
Pyth Contracts
Pyth deploys contracts on supported chains, enabling smart contracts on those networks to access pricing data through its decentralized system. You can find the Pyth contract address for XION's networks here.
Xion Testnet 2
xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl
Price Feeds
Pyth provides price feeds for various assets. Each feed has a unique feed ID, which is required to query the data. You can find the complete list of available feeds for XION chains here.
Fetching Price Data
A variety of queries can be made to the Pyth contract, including:
PriceFeed
GetUpdateFeeForDenom
GetUpdateFee
GetValidTimePeriod
For our use case, the key query is PriceFeed, as it retrieves the most recent price data for a given asset pair. This query requires only the feed ID, which you can find here.
Query Price Feed from Contract
To query a price feed from the Pyth oracle in a your smart contract, you need to send a WasmQuery::Smart
request to the Pyth contract with the correct feed_id
. Below is an example:
Query Price Feed from Frontend
Below is JavaScript code to query the price feed from the Pyth contract using cosmjs
:
queryContractSmart(PYTH_CONTRACT, queryMsg)
: Sends a query to the Pyth contract to fetch the price feed.
Last updated
Was this helpful?