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