@@ -16,7 +16,7 @@ use pyth_sdk::{
16
16
PriceIdentifier ,
17
17
UnixTimestamp ,
18
18
} ;
19
- use solana_program:: pubkey:: Pubkey ;
19
+ use solana_program:: { pubkey:: Pubkey , clock :: Clock } ;
20
20
use std:: mem:: size_of;
21
21
22
22
pub use pyth_sdk:: {
@@ -354,6 +354,33 @@ impl PriceAccount {
354
354
}
355
355
}
356
356
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
+
357
384
pub fn to_price_feed ( & self , price_key : & Pubkey ) -> PriceFeed {
358
385
let status = self . agg . status ;
359
386
@@ -480,7 +507,7 @@ mod test {
480
507
Price ,
481
508
PriceFeed ,
482
509
} ;
483
- use solana_program:: pubkey:: Pubkey ;
510
+ use solana_program:: { pubkey:: Pubkey , clock :: Clock } ;
484
511
485
512
use super :: {
486
513
PriceAccount ,
@@ -585,4 +612,38 @@ mod test {
585
612
)
586
613
) ;
587
614
}
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
+ }
588
649
}
0 commit comments