@@ -16,7 +16,7 @@ use pyth_sdk::{
1616 PriceIdentifier ,
1717 UnixTimestamp ,
1818} ;
19- use solana_program:: pubkey:: Pubkey ;
19+ use solana_program:: { pubkey:: Pubkey , clock :: Clock } ;
2020use std:: mem:: size_of;
2121
2222pub use pyth_sdk:: {
@@ -354,6 +354,33 @@ impl PriceAccount {
354354 }
355355 }
356356
357+ /// Get the last valid price as long as it was updated within `slot_threshold` slots of the current slot.
358+ pub fn get_price_no_older_than (
359+ & self ,
360+ clock : & Clock ,
361+ slot_threshold : u64
362+ ) -> Option < Price > {
363+ if self . agg . status == PriceStatus :: Trading && self . agg . pub_slot >= clock. slot - slot_threshold {
364+ return Some ( Price {
365+ conf : self . agg . conf ,
366+ expo : self . expo ,
367+ price : self . agg . price ,
368+ publish_time : self . timestamp ,
369+ } )
370+ }
371+
372+ if self . prev_slot > clock. slot - slot_threshold {
373+ return Some ( Price {
374+ conf : self . prev_conf ,
375+ expo : self . expo ,
376+ price : self . prev_price ,
377+ publish_time : self . prev_timestamp ,
378+ } )
379+ }
380+
381+ None
382+ }
383+
357384 pub fn to_price_feed ( & self , price_key : & Pubkey ) -> PriceFeed {
358385 let status = self . agg . status ;
359386
@@ -480,7 +507,7 @@ mod test {
480507 Price ,
481508 PriceFeed ,
482509 } ;
483- use solana_program:: pubkey:: Pubkey ;
510+ use solana_program:: { pubkey:: Pubkey , clock :: Clock } ;
484511
485512 use super :: {
486513 PriceAccount ,
@@ -585,4 +612,38 @@ mod test {
585612 )
586613 ) ;
587614 }
615+
616+ #[ test]
617+ fn test_happy_price_no_older_than ( ) {
618+ let price_account = PriceAccount {
619+ expo : 5 ,
620+ agg : PriceInfo {
621+ price : 10 ,
622+ conf : 20 ,
623+ status : PriceStatus :: Trading ,
624+ pub_slot : 1 ,
625+ ..Default :: default ( )
626+ } ,
627+ timestamp : 200 ,
628+ prev_timestamp : 100 ,
629+ prev_price : 60 ,
630+ prev_conf : 70 ,
631+ ..Default :: default ( )
632+ } ;
633+
634+ let clock = Clock {
635+ slot : 5 ,
636+ ..Default :: default ( )
637+ } ;
638+
639+ assert_eq ! (
640+ price_account. get_price_no_older_than( & clock, 4 ) ,
641+ Some ( Price {
642+ conf: 20 ,
643+ expo: 5 ,
644+ price: 10 ,
645+ publish_time: 200 ,
646+ } )
647+ ) ;
648+ }
588649}
0 commit comments