web3_utils/
pyth.rs

1use solana_program::{
2    account_info::AccountInfo,
3    clock::Clock,
4    msg,
5    program_error::ProgramError,
6    pubkey::{Pubkey},
7    pubkey,
8    sysvar::Sysvar,
9};
10use pyth_solana_receiver_sdk::{
11    self,
12    price_update::Price,
13};
14use std::convert::TryInto;
15
16use crate::{check::{check_account_key}, price_update::OriginSolanaPriceUpdateV2};
17
18pub const SOL_MINT: Pubkey = pubkey!("So11111111111111111111111111111111111111112");
19
20pub const PYTH_SOL_USD_FEED: Pubkey = pubkey!("7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE");
21
22pub const PRICE_FEED_DISCRIMATOR: [u8; 8] = [34, 241, 35, 99, 157, 126, 244, 205];
23
24pub const PYTH_PRICE_FEED: [u8; 32] = [
25    239, 13, 139, 111, 218, 44, 235, 164, 29, 161, 93, 64, 149, 209, 218, 57, 42, 13,
26    47, 142, 208, 198, 199, 188, 15, 76, 250, 200, 194, 128, 181, 109,
27];
28
29pub fn parse_price(data: &[u8]) -> Result<OriginSolanaPriceUpdateV2, ProgramError> {
30    // now the pyth accounts are anchor account
31    let suffix = &data[..8];
32    if suffix != PRICE_FEED_DISCRIMATOR {
33        return Err(ProgramError::InvalidArgument);
34    }
35    let update = OriginSolanaPriceUpdateV2::new(data)?;
36
37    Ok(update)
38}
39 
40pub fn get_oracle_price_fp32_v2(
41    account: &AccountInfo,
42    clock: &Clock,
43    maximum_age: u64,
44) -> Result<u64, ProgramError> {
45    check_account_key(account, &PYTH_SOL_USD_FEED)?;
46
47    let data = &account.data.borrow();
48    let update = parse_price(data)?;
49
50    let Price { price, exponent, .. } = update.0
51        .get_price_no_older_than(clock, maximum_age, &PYTH_PRICE_FEED)
52        .map_err(|_| ProgramError::InvalidArgument)?;
53
54    let price = if exponent > 0 {
55        ((price as u128) << 32) * 10u128.pow(exponent as u32)
56    } else {
57        ((price as u128) << 32) / 10u128.pow((-exponent) as u32)
58    };
59
60    let corrected_price = (price * 10u128.pow(6)) / 10u128.pow(9);
61
62    let final_price: u64 = corrected_price
63        .try_into()
64        .map_err(|_| ProgramError::InvalidArgument)?;
65
66    msg!("Pyth SOL/USD FP32 price: {:?}", final_price);
67
68    Ok(final_price)
69}
70
71
72pub fn get_domain_price_sol(
73    domain_price_usd: u64,
74    sol_pyth_feed_account: &AccountInfo,
75) -> Result<u64, ProgramError> {
76
77    let clock = Clock::get()
78        .map_err(|_| ProgramError::InvalidArgument)?;
79
80    #[cfg(feature="devnet")]
81    let query_deviation = 6000;
82    #[cfg(not(feature="devnet"))]
83    let query_deviation = 60;
84
85    let sol_price = get_oracle_price_fp32_v2(
86        &sol_pyth_feed_account, &clock, query_deviation)
87        .map_err(|_| ProgramError::InvalidArgument)?;
88
89    Ok(domain_price_usd * sol_price)
90}