Skip to main content

percli_program/instructions/
crank.rs

1use 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
7/// Maximum age of a Pyth price update before it's considered stale (seconds).
8const MAX_PRICE_AGE_SECS: i64 = 60;
9
10/// Pyth v2 oracle program on mainnet/devnet.
11const PYTH_PROGRAM_ID: Pubkey = pubkey!("FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH");
12
13#[derive(Accounts)]
14pub struct Crank<'info> {
15    /// Permissionless — anyone can crank.
16    pub cranker: Signer<'info>,
17
18    /// CHECK: Validated via owner, discriminator, and size.
19    #[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    /// CHECK: Pyth price feed account. Validated by owner check and pyth_sdk_solana deserialization.
27    #[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    // Read oracle price from Pyth — deserialize directly from raw bytes
35    // to avoid solana-pubkey version mismatch between pyth-sdk-solana and anchor-lang 1.0.
36    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 Trading status
41    require!(
42        price_account.agg.status == PriceStatus::Trading,
43        PercolatorError::InvalidOraclePrice
44    );
45
46    // Check staleness — reject future timestamps (would bypass the age check via saturating_sub)
47    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    // Price must be positive
58    require!(price > 0, PercolatorError::InvalidOraclePriceValue);
59
60    // Bound exponent to reasonable range to prevent overflow/truncation-to-zero
61    require!(expo >= -18 && expo <= 18, PercolatorError::InvalidOraclePrice);
62
63    // Convert Pyth price to u64 oracle price for the engine.
64    // Pyth prices have an exponent (e.g. price=12345, expo=-2 means $123.45).
65    // The engine uses raw integer prices, so normalize to a consistent scale.
66    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 the oracle borrow before mutably borrowing market
80    drop(oracle_data);
81
82    // Update engine
83    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}