Pyth

Pyth adalah Oracle yang digunakan untuk mendapatkan data pasar keuangan dan kripto. Pyth Oracle dapat digunakan oleh program on-chain dalam mengkonsumsi data untuk berbagai kasus penggunaan.

Cara Menggunakan Pyth di Client

Pyth menyediakan a JavaScript/TypeScript library yang disebut @pythnetwork/client. Librari ini bisa digunakan untuk membaca data on-chain untuk aplikasi off-chain, seperti menampilan harga Pyth di website. Pelajari lebih lanjut 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();
})();

Cara Memakai Pyth di Anchor

Pyth menyediakan a Rust Crate yang bisa digunakan program on-chain atau off-chain untuk konsumsi data Pyth..

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>,
}

Sumber Lainnya

Last Updated:
Contributors: akangaziz