percli_program/instructions/
crank.rs1use anchor_lang::prelude::*;
2use pyth_sdk_solana::state::{load_price_account, PriceStatus};
3
4use crate::error::{from_risk_error, PercolatorError};
5use crate::state::{engine_from_account_data, MARKET_ACCOUNT_SIZE};
6
7const MAX_PRICE_AGE_SECS: i64 = 60;
9
10const PYTH_PROGRAM_ID: Pubkey = pubkey!("FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH");
12
13#[derive(Accounts)]
14pub struct Crank<'info> {
15 pub cranker: Signer<'info>,
17
18 #[account(
20 mut,
21 owner = crate::ID @ PercolatorError::AccountNotFound,
22 constraint = market.data_len() == MARKET_ACCOUNT_SIZE @ PercolatorError::AccountNotFound,
23 )]
24 pub market: UncheckedAccount<'info>,
25
26 #[account(
28 owner = PYTH_PROGRAM_ID @ PercolatorError::InvalidOraclePrice,
29 )]
30 pub oracle: UncheckedAccount<'info>,
31}
32
33pub fn handler(ctx: Context<Crank>, funding_rate: i64) -> Result<()> {
34 let oracle_data = ctx.accounts.oracle.data.borrow();
37 let price_account = load_price_account::<32, ()>(&oracle_data)
38 .map_err(|_| error!(PercolatorError::InvalidOraclePrice))?;
39
40 require!(
42 price_account.agg.status == PriceStatus::Trading,
43 PercolatorError::InvalidOraclePrice
44 );
45
46 let clock = Clock::get()?;
48 let current_timestamp = clock.unix_timestamp;
49 let price_age = current_timestamp
50 .checked_sub(price_account.timestamp)
51 .ok_or_else(|| error!(PercolatorError::StaleOracle))?;
52 require!(price_age <= MAX_PRICE_AGE_SECS, PercolatorError::StaleOracle);
53
54 let price = price_account.agg.price;
55 let expo = price_account.expo;
56
57 require!(price > 0, PercolatorError::InvalidOraclePriceValue);
59
60 require!(expo >= -18 && expo <= 18, PercolatorError::InvalidOraclePrice);
62
63 let oracle_price = if expo >= 0 {
67 (price as u64)
68 .checked_mul(10u64.pow(expo as u32))
69 .ok_or_else(|| error!(PercolatorError::InvalidOraclePriceValue))?
70 } else {
71 let divisor = 10u64.pow((-expo) as u32);
72 (price as u64)
73 .checked_div(divisor)
74 .ok_or_else(|| error!(PercolatorError::InvalidOraclePriceValue))?
75 };
76
77 require!(oracle_price > 0, PercolatorError::InvalidOraclePriceValue);
78
79 drop(oracle_data);
81
82 let market = &ctx.accounts.market;
84 let mut data = market.try_borrow_mut_data()?;
85
86 require!(
87 &data[0..8] == b"percmrkt",
88 PercolatorError::AccountNotFound
89 );
90
91 let engine = engine_from_account_data(&mut data);
92
93 engine
94 .keeper_crank_not_atomic(clock.slot, oracle_price, &[], 0, funding_rate)
95 .map_err(from_risk_error)?;
96
97 Ok(())
98}