|
| 1 | +use anchor_lang::prelude::*; |
| 2 | +pub mod state; |
| 3 | +use state::PriceFeed; |
| 4 | + |
| 5 | +pub mod error; |
| 6 | +use error::ErrorCode; |
| 7 | + |
| 8 | +declare_id!("F6mNuN1xoPdRaZcUX3Xviq7x1EFtoBXygpFggCLd62eU"); |
| 9 | + |
| 10 | +#[program] |
| 11 | +pub mod pythexample { |
| 12 | + use super::*; |
| 13 | + pub fn read_price(ctx: Context<Pyth>) -> Result<()> { |
| 14 | + let price_feed = &ctx.accounts.price_feed; |
| 15 | + let clock = &ctx.accounts.clock; |
| 16 | + // Get the current timestamp |
| 17 | + let timestamp: i64 = clock.unix_timestamp; |
| 18 | + // Load the price from the price feed. Here, the price can be no older than 500 seconds. |
| 19 | + let price: pyth_sdk::Price = price_feed |
| 20 | + .get_price_no_older_than(timestamp, 30) |
| 21 | + .ok_or(ErrorCode::PythError)?; |
| 22 | + |
| 23 | + let confidence_interval: u64 = price.conf; |
| 24 | + |
| 25 | + let asset_price_full: i64 = price.price; |
| 26 | + |
| 27 | + let asset_exponent: i32 = price.expo; |
| 28 | + |
| 29 | + let asset_price = asset_price_full as f64 * 10f64.powi(asset_exponent); |
| 30 | + |
| 31 | + msg!("Price: {}", asset_price); |
| 32 | + msg!("Confidence interval: {}", confidence_interval); |
| 33 | + |
| 34 | + Ok(()) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Accounts)] |
| 39 | +pub struct Pyth<'info> { |
| 40 | + pub price_feed: Account<'info, PriceFeed>, |
| 41 | + pub system_program: Program<'info, System>, |
| 42 | + pub clock: Sysvar<'info, Clock>, |
| 43 | +} |
0 commit comments