XION
DiscordGithub
  • Welcome to XION
  • XION'S Core
    • Concepts
      • Generalized Chain Abstraction
      • Intro to Account Abstraction
      • XION's Meta Accounts
      • Meta Accounts Design
      • Architecture & Tech Glossary
      • Use Cases
  • developers
    • XION Quick Start
      • Zero to App in 5 Minutes
        • Launch a User Map App on XION in 5 Minutes
        • React Native Mobile App on XION in 5 Minutes
        • Todo App
          • Build a TODO App using the Collection-Document Storage Smart Contract
          • Build a TODO Mobile App using the DocuStore Contract
    • Mobile App Development
      • Set up your XION Mobile Development Environment
      • Build a TODO Mobile App using the DocuStore Contract
      • Create Mobile App and Integrate Meta Account Authentication
      • Building a React Native Mobile App with Abstraxion (Xion.js)
    • Getting Started (Advanced)
      • Set Up Local Environment
        • Setting up your Local Smart Contract Development Environment for XION
          • Setting up your XION Smart Contract Development Environment on Windows (WSL2 + Ubuntu)
        • Set Up an Integrated Development Environment (IDE)
        • Interacting with Xion Chain using Xion Daemon
      • Your First Contract
        • Deploying Your First Smart Contract on XION
      • Gasless UX & Permission Grants
        • Enabling Gasless Transactions with Treasury Contracts
      • App Development
        • Account Abstraction with Gasless Transactions
        • Interact with XION via your Backend Service
    • Re-using Existing Contracts
      • Deployed Contracts on XION
      • Non-Fungible Tokens (NFTs)
      • Fungible Tokens
      • Marketplace
      • Multisig
      • Proxy Contracts
      • Membership Management
      • Governance
      • Valuts
      • SCV Audited Contracts
    • Web3 for Web2 Developers
      • Web2 vs Web3 App Architecture: A Comparison
      • Misconceptions and Misapplied Web2 Patterns
      • Recommended Architecture for Apps on XION
    • Building for Mainnet
      • Xion Testnet: Your Development Playground
      • Building with Audited & Battle-Tested Contracts
      • Community Engagement: Building Support for Your app
      • Deploying to Xion Mainnet
        • Smart Contract Audits: Process, Costs & Support
        • Governance Process to Deploying Smart Contracts to Mainnet
    • Learn & Build
      • Token Factory
        • Creating, Minting, and Interacting with a Token Factory Token
        • Building a React dApp to Interact with Token Factory Tokens
        • Integrating a Token Factory Token in a Smart Contract
      • Websockets
        • WebSockets with Xion: Real-Time Communication
      • Oracles
        • Creating a Smart Contract with Pyth Oracle Integration
      • Indexers: Optimized Data Retrieval
        • SubQuery
      • Use Cases
        • Building a Per-User Data Storage App
        • Build a TODO App using the Collection-Document Storage Smart Contract
      • Crossmint Integration
        • Crossmint Digital Collectibles Checkout via Credit Card
    • Reference and Resources
      • Requesting XION Testnet Tokens
      • Public Endpoints & Resources
      • Block Explorers
      • Governance
        • Deploying Smart Contracts to Mainnet
      • Developer Tools: Abstract
      • IBC Denoms on XION Networks
      • Frequently Asked Questions
      • XION Token Contract Addresses on EVM Chains
  • Nodes & Validators
    • Run a Node
      • System Specifications
      • Build the Xion Daemon
      • Download the Xion Daemon
      • Configure the Xion Daemon
        • app.toml
        • client.toml
        • config.toml
      • Join the XION Network
        • xion-testnet-1
      • Confirm node is running
    • Become a Validator
      • Initial Setup
      • Obtain a XION Wallet Address
      • Obtain Funds
        • Testnet
      • Create Validator
    • IBC Relayers and Tokens
  • Others
    • Resources
Powered by GitBook
On this page
  • Pyth Contracts
  • Price Feeds
  • Fetching Price Data
  • Query Price Feed from Contract
  • Query Price Feed from Frontend

Was this helpful?

Edit on GitHub
  1. developers
  2. Learn & Build
  3. Oracles

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 app.

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.

Network
Contract Address

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:

use cosmwasm_std::{Deps, StdResult, Binary, WasmQuery, QueryRequest, to_binary};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

const PYTH_CONTRACT: &str = "xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl";
const PRICE_FEED_ID: &str = "0x436ccb0d465f3cb48554bcc8def65ff695341b3ebe0897563d118b9291178d0f";

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PriceFeedQueryMsg {
    pub id: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PriceFeedResponse {
    pub price_feed: PriceFeed,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PriceFeed {
    pub price: i64,         // price in integer format
    pub conf: u64,          // confidence interval
    pub expo: i32,          // exponent for scaling
    pub publish_time: i64,  // timestamp of the price
}

/// Queries the price feed from the Pyth contract
pub fn query_pyth_price_feed(deps: Deps) -> StdResult<PriceFeedResponse> {
    let query_msg = PriceFeedQueryMsg {
        id: PRICE_FEED_ID.to_string(),
    };

    let response: PriceFeedResponse = deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart {
        contract_addr: PYTH_CONTRACT.to_string(),
        msg: to_binary(&query_msg)?,
    }))?;

    Ok(response)
}

Query Price Feed from Frontend

Below is JavaScript code to query the price feed from the Pyth contract using cosmjs:

import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";

// Constants
const RPC_ENDPOINT = "https://rpc.xion-testnet-2.burnt.com:443"; // Replace with the correct RPC
const PYTH_CONTRACT = "xion1wptw89weav8tnpgxg4fyhcahgk8yy99lka3w308536ktadkvjwxqe463hl"; // Replace with the correct Pyth contract address
const PRICE_FEED_ID = "0x436ccb0d465f3cb48554bcc8def65ff695341b3ebe0897563d118b9291178d0f"; // Replace with the correct Feed ID

// Function to fetch price feed
async function fetchPythPriceFeed() {
    try {
        // Connect to the blockchain
        const client = await CosmWasmClient.connect(RPC_ENDPOINT);

        // Query message for the Pyth contract
        const queryMsg = {
            PriceFeed: { id: PRICE_FEED_ID },
        };

        // Execute query
        const response = await client.queryContractSmart(PYTH_CONTRACT, queryMsg);

        console.log("Pyth Price Feed Response:", response);
        return response;
    } catch (error) {
        console.error("Error fetching price feed:", error);
    }
}

// Call the function
fetchPythPriceFeed();

queryContractSmart(PYTH_CONTRACT, queryMsg): Sends a query to the Pyth contract to fetch the price feed.

PreviousOraclesNextIndexers: Optimized Data Retrieval

Last updated 14 days ago

Was this helpful?