gmsol_store/states/oracle/
feed.rs

1use anchor_lang::prelude::*;
2use bytemuck::Zeroable;
3use gmsol_utils::InitSpace;
4
5use crate::{
6    states::{Seed, TokenConfig},
7    CoreError,
8};
9
10use super::PriceProviderKind;
11
12const MAX_FLAGS: usize = 8;
13
14/// Custom Price Feed.
15#[account(zero_copy)]
16#[cfg_attr(feature = "debug", derive(Debug))]
17pub struct PriceFeed {
18    pub(crate) bump: u8,
19    pub(crate) provider: u8,
20    pub(crate) index: u16,
21    padding_0: [u8; 12],
22    pub(crate) store: Pubkey,
23    /// Authority.
24    pub authority: Pubkey,
25    pub(crate) token: Pubkey,
26    pub(crate) feed_id: Pubkey,
27    last_published_at_slot: u64,
28    last_published_at: i64,
29    price: PriceFeedPrice,
30    reserved: [u8; 256],
31}
32
33impl InitSpace for PriceFeed {
34    const INIT_SPACE: usize = std::mem::size_of::<Self>();
35}
36
37impl Seed for PriceFeed {
38    const SEED: &'static [u8] = b"price_feed";
39}
40
41impl Default for PriceFeed {
42    fn default() -> Self {
43        Zeroable::zeroed()
44    }
45}
46
47impl PriceFeed {
48    pub(crate) fn init(
49        &mut self,
50        bump: u8,
51        index: u16,
52        provider: PriceProviderKind,
53        store: &Pubkey,
54        authority: &Pubkey,
55        token: &Pubkey,
56        feed_id: &Pubkey,
57    ) -> Result<()> {
58        self.bump = bump;
59        self.provider = provider.into();
60        self.index = index;
61        self.store = *store;
62        self.authority = *authority;
63        self.token = *token;
64        self.feed_id = *feed_id;
65        Ok(())
66    }
67
68    pub(crate) fn update(&mut self, price: &PriceFeedPrice, max_future_excess: u64) -> Result<()> {
69        let clock = Clock::get()?;
70        let slot = clock.slot;
71        let current_ts = clock.unix_timestamp;
72
73        // Validate time.
74        require_gte!(
75            slot,
76            self.last_published_at_slot,
77            CoreError::PreconditionsAreNotMet
78        );
79        require_gte!(
80            current_ts,
81            self.last_published_at,
82            CoreError::PreconditionsAreNotMet
83        );
84
85        require_gte!(price.ts, self.price.ts, CoreError::InvalidArgument);
86        require_gte!(
87            current_ts.saturating_add_unsigned(max_future_excess),
88            price.ts,
89            CoreError::InvalidArgument
90        );
91        require_gte!(price.max_price, price.min_price, CoreError::InvalidArgument);
92        require_gte!(price.max_price, price.price, CoreError::InvalidArgument);
93        require_gte!(price.price, price.min_price, CoreError::InvalidArgument);
94
95        self.last_published_at_slot = slot;
96        self.last_published_at = current_ts;
97        self.price = *price;
98
99        Ok(())
100    }
101
102    /// Get provider.
103    pub fn provider(&self) -> Result<PriceProviderKind> {
104        PriceProviderKind::try_from(self.provider)
105            .map_err(|_| error!(CoreError::InvalidProviderKindIndex))
106    }
107
108    /// Get price feed price.
109    pub fn price(&self) -> &PriceFeedPrice {
110        &self.price
111    }
112
113    /// Get published slot.
114    pub fn last_published_at_slot(&self) -> u64 {
115        self.last_published_at_slot
116    }
117
118    /// Get feed id.
119    pub fn feed_id(&self) -> &Pubkey {
120        &self.feed_id
121    }
122
123    pub(crate) fn check_and_get_price(
124        &self,
125        clock: &Clock,
126        token_config: &TokenConfig,
127    ) -> Result<(u64, i64, gmsol_utils::Price)> {
128        let provider = self.provider()?;
129        require_eq!(token_config.expected_provider()?, provider);
130        let feed_id = token_config.get_feed(&provider)?;
131
132        require_keys_eq!(self.feed_id, feed_id, CoreError::InvalidPriceFeedAccount);
133        require!(self.price.is_market_open(), CoreError::MarketNotOpen);
134
135        let timestamp = self.price.ts;
136        let current = clock.unix_timestamp;
137        if current > timestamp && current - timestamp > token_config.heartbeat_duration().into() {
138            return Err(CoreError::PriceFeedNotUpdated.into());
139        }
140
141        let price = self.try_to_price(token_config)?;
142
143        Ok((self.last_published_at_slot(), timestamp, price))
144    }
145
146    fn try_to_price(&self, token_config: &TokenConfig) -> Result<gmsol_utils::Price> {
147        self.price().try_to_price(token_config)
148    }
149}
150
151/// Price Feed Flags.
152#[repr(u8)]
153#[non_exhaustive]
154#[derive(num_enum::IntoPrimitive, num_enum::TryFromPrimitive)]
155pub enum PriceFlag {
156    /// Is Market Opened.
157    Open,
158    // CHECK: should have no more than `MAX_FLAGS` of flags.
159}
160
161gmsol_utils::flags!(PriceFlag, MAX_FLAGS, u8);
162
163/// Price structure for Price Feed.
164#[zero_copy]
165#[cfg_attr(feature = "debug", derive(Debug))]
166pub struct PriceFeedPrice {
167    decimals: u8,
168    flags: PriceFlagContainer,
169    padding: [u8; 6],
170    ts: i64,
171    price: u128,
172    min_price: u128,
173    max_price: u128,
174}
175
176impl PriceFeedPrice {
177    /// Get ts.
178    pub fn ts(&self) -> i64 {
179        self.ts
180    }
181
182    /// Get min price.
183    pub fn min_price(&self) -> &u128 {
184        &self.min_price
185    }
186
187    /// Get max price.
188    pub fn max_price(&self) -> &u128 {
189        &self.max_price
190    }
191
192    /// Get price.
193    pub fn price(&self) -> &u128 {
194        &self.price
195    }
196
197    /// Is market open.
198    pub fn is_market_open(&self) -> bool {
199        self.flags.get_flag(PriceFlag::Open)
200    }
201
202    /// Try converting to [`Price`](gmsol_utils::Price).
203    pub fn try_to_price(&self, token_config: &TokenConfig) -> Result<gmsol_utils::Price> {
204        use gmsol_utils::price::{Decimal, Price};
205
206        let token_decimals = token_config.token_decimals();
207        let precision = token_config.precision();
208
209        let min = Decimal::try_from_price(self.min_price, self.decimals, token_decimals, precision)
210            .map_err(|_| error!(CoreError::InvalidPriceFeedPrice))?;
211
212        let max = Decimal::try_from_price(self.max_price, self.decimals, token_decimals, precision)
213            .map_err(|_| error!(CoreError::InvalidPriceFeedPrice))?;
214
215        Ok(Price { min, max })
216    }
217
218    /// Create from chainlink price report.
219    pub fn from_chainlink_report(
220        report: &gmsol_chainlink_datastreams::report::Report,
221    ) -> Result<Self> {
222        use gmsol_chainlink_datastreams::report::Report;
223        use gmsol_utils::price::{find_divisor_decimals, TEN, U192};
224
225        let price = report
226            .non_negative_price()
227            .ok_or_else(|| error!(CoreError::NegativePriceIsNotSupported))?;
228        let bid = report
229            .non_negative_bid()
230            .ok_or_else(|| error!(CoreError::NegativePriceIsNotSupported))?;
231        let ask = report
232            .non_negative_ask()
233            .ok_or_else(|| error!(CoreError::NegativePriceIsNotSupported))?;
234
235        require!(ask >= price, CoreError::InvalidPriceReport);
236        require!(price >= bid, CoreError::InvalidPriceReport);
237
238        let divisor_decimals = find_divisor_decimals(&ask);
239
240        require_gte!(Report::DECIMALS, divisor_decimals, CoreError::PriceOverflow);
241
242        let divisor = TEN.pow(U192::from(divisor_decimals));
243
244        debug_assert!(!divisor.is_zero());
245
246        let mut price = Self {
247            decimals: Report::DECIMALS - divisor_decimals,
248            flags: Default::default(),
249            padding: [0; 6],
250            ts: i64::from(report.observations_timestamp),
251            price: (price / divisor).try_into().unwrap(),
252            min_price: (bid / divisor).try_into().unwrap(),
253            max_price: (ask / divisor).try_into().unwrap(),
254        };
255
256        price.flags.set_flag(PriceFlag::Open, true);
257
258        Ok(price)
259    }
260}