Pyth

Pyth is an Oracle used to get real-world financial and crypto market data. Pyth Oracle can be used by on-chain programs in consuming data for a variety of use cases.

How to use Pyth in Client

Pyth provides a JavaScript/TypeScript library called @pythnetwork/client. This library can be used to read on-chain Pyth Data for off-chain applications, such as displaying the Pyth price on a website. Learn more about this hereopen in new window

Press </> button to view full source
import * as web3 from "@solana/web3.js";
import * as pyth from "@pythnetwork/client";

(async () => {
  const connection = new web3.Connection(
    web3.clusterApiUrl("devnet"),
    "confirmed"
  );
  const pythConnection = new pyth.PythConnection(
    connection,
    pyth.getPythProgramKeyForCluster("devnet")
  );

  pythConnection.onPriceChange((product, price) => {
    if (price.price && price.confidence) {
      console.log(
        `${product.symbol}: $${price.price} \xB1$${price.confidence}`
      );
    } else {
      console.log(
        `${product.symbol}: price currently unavailable. status is ${price.status}`
      );
    }
  });
  pythConnection.start();
})();

How to use Pyth in Anchor

Pyth provides a Rust Crate which can be used by on-chain programs or off-chain application's to consume pyth's data.

Press </> button to view full source
use anchor_lang::prelude::*;
use pyth_client::{self, load_price, Price};

declare_id!("6B7XgKFmo73geJY8ZboSpLhkTumvwXeCXBpeP7nCT35w");

#[program]
pub mod pyth_test {
    use super::*;

    pub fn get_sol_price(ctx: Context<SolPrice>) -> Result<()> {
        let pyth_price_info = &ctx.accounts.pyth_account;
        let pyth_price_data = &pyth_price_info.try_borrow_data()?;
        let price_account: Price = *load_price(pyth_price_data).unwrap();

        msg!("price_account .. {:?}", pyth_price_info.key);
        msg!("price_type ... {:?}", price_account.ptype);
        msg!("price ........ {}", price_account.agg.price);

        Ok(())
    }
}

#[derive(Accounts)]
pub struct SolPrice<'info> {
    #[account(mut)]
    pub user_account: Signer<'info>,
    pub pyth_account: UncheckedAccount<'info>,
    pub system_program: UncheckedAccount<'info>,
    pub rent: Sysvar<'info, Rent>,
}

Other Resources

Last Updated:
Contributors: tuphan-dn