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 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 msg!("pyth account ok");
47
48 let data = &account.data.borrow();
49 let update = parse_price(data)?;
50
51 let Price { price, exponent, .. } = update.0
52 .get_price_no_older_than(clock, maximum_age, &PYTH_PRICE_FEED)
53 .map_err(|_| ProgramError::InvalidArgument)?;
54
55 let price = if exponent > 0 {
56 ((price as u128) << 32) * 10u128.pow(exponent as u32)
57 } else {
58 ((price as u128) << 32) / 10u128.pow((-exponent) as u32)
59 };
60
61 let corrected_price = (price * 10u128.pow(6)) / 10u128.pow(9);
62
63 let final_price: u64 = corrected_price
64 .try_into()
65 .map_err(|_| ProgramError::InvalidArgument)?;
66
67 msg!("Pyth SOL/USD FP32 price: {:?}", final_price);
68
69 Ok(final_price)
70}
71
72
73pub fn get_domain_price_sol(
74 domain_price_usd: u64,
75 sol_pyth_feed_account: &AccountInfo,
76) -> Result<u64, ProgramError> {
77
78 let clock = Clock::get()
79 .map_err(|_| ProgramError::InvalidArgument)?;
80 msg!("get clock ok");
81
82 #[cfg(feature="devnet")]
83 let query_deviation = 6000;
84 #[cfg(not(feature="devnet"))]
85 let query_deviation = 60;
86
87 msg!("now the deviation: {:?}", query_deviation);
88
89 let sol_price = get_oracle_price_fp32_v2(
90 &sol_pyth_feed_account, &clock, query_deviation)
91 .map_err(|_| ProgramError::InvalidArgument)?;
92
93 Ok(domain_price_usd * sol_price)
94}