1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! provides support for reading pyth price feeds from tulip's pyth price manager program
//! this should in theory work with any pyth v2 price account out there, however it is only tested
//! with the accounts that tulip publishes prices for via our own price feed program.

use crate::math::{common::TryDiv, decimal::Decimal};
use anchor_lang::prelude::ProgramError;
use bytemuck::{cast_slice, from_bytes, try_cast_slice, Pod, PodCastError, Zeroable};
use std::mem::size_of;

/// after this many slots consider a price update as being stale and thus invalid
// 30 slots translates to a period of around 15s depending on slot times
pub const STALE_AFTER_SLOTS_ELAPSED: u64 = 120;

pub const MAGIC: u32 = 0xa1b2c3d4;
pub const VERSION_2: u32 = 2;
pub const VERSION: u32 = VERSION_2;
pub const MAP_TABLE_SIZE: usize = 640;
pub const PROD_ACCT_SIZE: usize = 512;
pub const PROD_HDR_SIZE: usize = 48;
pub const PROD_ATTR_SIZE: usize = PROD_ACCT_SIZE - PROD_HDR_SIZE;

#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct AccKey {
    pub val: [u8; 32],
}

#[derive(Copy, Clone)]
#[repr(C)]
pub enum AccountType {
    Unknown,
    Mapping,
    Product,
    Price,
}

#[derive(Copy, Clone)]
#[repr(C)]
pub enum PriceStatus {
    Unknown,
    Trading,
    Halted,
    Auction,
}

impl std::fmt::Display for PriceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name().as_str())
    }
}

impl PriceStatus {
    pub fn name(&self) -> String {
        match self {
            PriceStatus::Unknown => String::from("unknown"),
            PriceStatus::Trading => String::from("trading"),
            PriceStatus::Halted => String::from("halted"),
            PriceStatus::Auction => String::from("auction"),
        }
    }
}

impl Default for PriceStatus {
    fn default() -> Self {
        PriceStatus::Trading
    }
}

#[derive(Copy, Clone)]
#[repr(C)]
pub enum CorpAction {
    NoCorpAct,
}

impl Default for CorpAction {
    fn default() -> Self {
        CorpAction::NoCorpAct
    }
}

#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct PriceInfo {
    pub price: i64,
    pub conf: u64,
    pub status: PriceStatus,
    pub corp_act: CorpAction,
    pub pub_slot: u64,
}

#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct PriceComp {
    publisher: AccKey,
    agg: PriceInfo,
    latest: PriceInfo,
}

#[derive(Copy, Clone)]
#[repr(C)]
pub enum PriceType {
    Unknown,
    Price,
    #[allow(clippy::upper_case_acronyms)]
    TWAP,
    Volatility,
}

impl Default for PriceType {
    fn default() -> Self {
        PriceType::Price
    }
}

#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct Price {
    pub magic: u32,       // Pyth magic number.
    pub ver: u32,         // Program version.
    pub atype: u32,       // Account type.
    pub size: u32,        // Price account size.
    pub ptype: PriceType, // Price or calculation type.
    pub expo: i32,        // Price exponent.
    pub num: u32,         // Number of component prices.
    pub unused: u32,
    pub curr_slot: u64,        // Currently accumulating price slot.
    pub valid_slot: u64,       // Valid slot-time of agg. price.
    pub twap: i64,             // Time-weighted average price.
    pub avol: u64,             // Annualized price volatility.
    pub drv0: i64,             // Space for future derived values.
    pub drv1: i64,             // Space for future derived values.
    pub drv2: i64,             // Space for future derived values.
    pub drv3: i64,             // Space for future derived values.
    pub drv4: i64,             // Space for future derived values.
    pub drv5: i64,             // Space for future derived values.
    pub prod: AccKey,          // Product account key.
    pub next: AccKey,          // Next Price account in linked list.
    pub agg_pub: AccKey,       // Quoter who computed last aggregate price.
    pub agg: PriceInfo,        // Aggregate price info.
    pub comp: [PriceComp; 32], // Price components one per quoter.
}

#[cfg(target_endian = "little")]
unsafe impl Zeroable for Price {}

#[cfg(target_endian = "little")]
unsafe impl Pod for Price {}

#[derive(Copy, Clone)]
#[repr(C)]
pub struct Product {
    pub magic: u32,                 // pyth magic number
    pub ver: u32,                   // program version
    pub atype: u32,                 // account type
    pub size: u32,                  // price account size
    pub px_acc: AccKey,             // first price account in list
    pub attr: [u8; PROD_ATTR_SIZE], // key/value pairs of reference attr.
}

#[cfg(target_endian = "little")]
unsafe impl Zeroable for Product {}

#[cfg(target_endian = "little")]
unsafe impl Pod for Product {}

pub fn load<T: Pod>(data: &[u8]) -> Result<&T, PodCastError> {
    let size = size_of::<T>();
    Ok(from_bytes(cast_slice::<u8, u8>(try_cast_slice(
        &data[0..size],
    )?)))
}

pub fn load_pyth_price(pyth_price_account_data: &[u8]) -> Result<Decimal, ProgramError> {
    let pyth_price =
        load::<Price>(pyth_price_account_data).map_err(|_| ProgramError::InvalidAccountData)?;
    parse_pyth_price(pyth_price)
}

/// 🚨 see the warning at the end of this function for safe usage 🚨
///
/// parses the Price account for the currently stored price data.
///
/// 🚨 warning 🚨
///
/// this function does not check price staleness, confidence, or any
/// other such validation of the price. it simply ensures that the value
/// can be parsed into a Decimal without error.
///
/// this is only intended for use with the pyth price feeds published by
/// tulip, and should be used cautiously as inappropriate usage will result
/// in loss of money
pub fn parse_pyth_price(pyth_price: &Price) -> Result<Decimal, ProgramError> {
    if pyth_price.ptype as u32 != PriceType::Price as u32 {
        return Err(ProgramError::Custom(u32::MAX - 1));
    }

    let price: u64 = match pyth_price.agg.price.checked_abs() {
        Some(val) => match val.try_into() {
            Ok(val) => val,
            Err(_) => return Err(ProgramError::InvalidArgument),
        },
        None => return Err(ProgramError::Custom(u32::MAX - 2)),
    };

    // @TODO: handle the case that the exponent is positive?
    let pyth_exponent = match pyth_price.expo.checked_abs() {
        Some(val) => match val.try_into() {
            Ok(val) => val,
            Err(_) => return Err(ProgramError::InvalidArgument),
        },
        None => return Err(ProgramError::Custom(u32::MAX - 2)),
    };

    let pyth_decimals = match 10u64.checked_pow(pyth_exponent) {
        Some(val) => val,
        None => return Err(ProgramError::Custom(u32::MAX - 2)),
    };
    let market_price = Decimal::from(price).try_div(pyth_decimals)?;
    Ok(market_price)
}

#[cfg(test)]
mod test {

    use super::*;
    use anchor_client::solana_client::rpc_client::RpcClient;
    use anchor_lang::solana_program;
    use static_pubkey::static_pubkey;
    #[test]
    fn test_get_pyth_price_account() {
        let rpc = RpcClient::new("https://ssc-dao.genesysgo.net".to_string());
        let tulip_price_account_key =
            static_pubkey!("5RHxy1NbUR15y34uktDbN1a2SWbhgHwkCZ75yK2RJ1FC");
        let tulip_price_account = rpc.get_account(&tulip_price_account_key).unwrap();
        let price = load_pyth_price(&tulip_price_account.data[..]).unwrap();
        println!("price {:#?}", price);
    }
}