program_utils/
lib.rs

1#![deny(missing_docs)]
2
3//! Program utility functions
4
5use solana_program::account_info::AccountInfo;
6use solana_program::clock::Clock;
7use solana_program::entrypoint::ProgramResult;
8use solana_program::program_error::ProgramError;
9use solana_program::pubkey::Pubkey;
10use solana_program::sysvar::Sysvar;
11use solana_program::{msg, sysvar};
12use solana_sdk_ids::system_program;
13
14/// mini helper to log from native Rust or to the program log
15/// Very useful for debugging when you have to run some code on Solana and via
16/// native Rust
17#[macro_export]
18macro_rules! log_everywhere {
19    ($($arg:tt)*) => {{
20        let message = format!($($arg)*);
21
22        #[cfg(not(target_os = "solana"))]
23        {
24            dbg!(message);
25        }
26
27        #[cfg(target_os = "solana")]
28        {
29            solana_program::msg!("SOL: {}", message);
30        }
31    }}
32}
33
34/// Checks that the supplied program ID is the correct one
35pub fn check_program_account(program_id: &Pubkey, check_f: fn(&Pubkey) -> bool) -> ProgramResult {
36    if !&check_f(program_id) {
37        return Err(ProgramError::IncorrectProgramId);
38    }
39    Ok(())
40}
41
42/// Tries to fetch the next account as an optional account from the account iterator
43///
44/// By convention, when an account is set to be the `program_id`, it's interpreted as
45/// [`Option::None`]
46pub fn next_optional_account_info<'a, 'b, I: Iterator<Item = &'a AccountInfo<'b>>>(
47    iter: &mut I,
48    program_id: &Pubkey,
49) -> Result<Option<I::Item>, ProgramError> {
50    iter.next()
51        .ok_or(ProgramError::NotEnoughAccountKeys)
52        .map(|account| {
53            if account.key == program_id {
54                None
55            } else {
56                Some(account)
57            }
58        })
59}
60
61/// Macro to ensure exactly one feature from a list is enabled
62#[macro_export]
63macro_rules! ensure_single_feature {
64    ($($feature:literal),+) => {
65        // Check that at least one feature is enabled
66        #[cfg(not(any($(feature = $feature),+)))]
67        compile_error!(concat!("Exactly one of these features must be enabled: ", $(stringify!($feature), ", "),+));
68
69        // Generate all pair combinations to check mutual exclusivity
70        ensure_single_feature!(@pairs [] $($feature),+);
71    };
72
73    // Helper to generate all pairs
74    (@pairs [$($processed:literal),*] $first:literal $(,$rest:literal)*) => {
75        // Check current element against all processed elements
76        $(
77            #[cfg(all(feature = $first, feature = $processed))]
78            compile_error!(concat!("Features '", $first, "' and '", $processed, "' are mutually exclusive"));
79        )*
80
81        // Continue with the rest
82        ensure_single_feature!(@pairs [$($processed,)* $first] $($rest),*);
83    };
84
85    // Base case: no more elements to process
86    (@pairs [$($processed:literal),*]) => {};
87}
88
89/// Converts a little-endian 256-bit unsigned integer to a 64-bit unsigned
90/// integer.
91///
92/// This function takes a 32-byte array representing a little-endian 256-bit
93/// unsigned integer and converts it to a 64-bit unsigned integer, ensuring that
94/// the upper bytes are all zero.
95///
96/// # Arguments
97///
98/// * `le_u256` - A reference to a 32-byte array representing a little-endian
99///   256-bit unsigned integer.
100///
101/// # Errors
102///
103/// Returns [`ProgramError::InvalidArgument`] if the upper bytes are not all
104/// zero and the caller should take care of adding more contextual information
105/// into the program.
106///
107/// # Examples
108///
109/// ```
110/// use program_utils::checked_from_u256_le_bytes_to_u64;
111///
112/// let le_u256: [u8; 32] = [0; 32];
113/// let result = checked_from_u256_le_bytes_to_u64(&le_u256).unwrap();
114/// assert_eq!(result, 0);
115/// ```
116#[allow(clippy::little_endian_bytes)]
117pub fn checked_from_u256_le_bytes_to_u64(le_u256: &[u8; 32]) -> Result<u64, ProgramError> {
118    // Check that the upper bytes are all zero.
119    if le_u256[8..32].iter().any(|&byte| byte != 0) {
120        return Err(ProgramError::InvalidArgument);
121    }
122
123    // Copy the first 8 bytes into a u64 array.
124    let mut u64data: [u8; 8] = [0_u8; 8];
125    u64data.copy_from_slice(&le_u256[0..8]);
126
127    // Convert the array to a u64.
128    Ok(u64::from_le_bytes(u64data))
129}
130
131/// Converts from little endian u64 type to [u8; 32] type
132#[must_use]
133#[allow(clippy::little_endian_bytes)]
134pub fn from_u64_to_u256_le_bytes(u64: u64) -> [u8; 32] {
135    let mut u256 = [0; 32];
136    u256[0..8].copy_from_slice(&u64.to_le_bytes());
137    u256
138}
139
140/// Returns the current Unix timestamp as a `u64`.
141///
142/// This function normalizes the timestamp to `u64` because we do not care about
143/// time before the epoch, and it helps to standardize our data types.
144///
145/// # Errors
146///
147/// Returns `ProgramError::InvalidArgument` if the conversion from `i64` to
148/// `u64` fails.
149pub fn current_time() -> Result<u64, ProgramError> {
150    let solana_now = Clock::get()?.unix_timestamp;
151    let now = u64::try_from(solana_now).map_err(|err| {
152        msg!("Cannot convert solana type into u64: {}", err);
153        ProgramError::InvalidArgument
154    })?;
155    Ok(now)
156}
157
158/// Transfers lamports from one account to another.
159///
160/// # Arguments
161///
162/// * `from_account` - The account to transfer lamports from.
163/// * `to_account` - The account to transfer lamports to.
164/// * `amount_of_lamports` - The amount of lamports to transfer.
165///
166/// # Errors
167///
168/// Returns `ProgramError::InsufficientFunds` if the `from_account` does not
169/// have enough lamports.
170pub fn transfer_lamports(
171    from_account: &AccountInfo<'_>,
172    to_account: &AccountInfo<'_>,
173    amount_of_lamports: u64,
174) -> ProgramResult {
175    // Does the from account have enough lamports to transfer?
176    if **from_account.try_borrow_lamports()? < amount_of_lamports {
177        return Err(ProgramError::InsufficientFunds);
178    }
179    // Debit from_account and credit to_account
180    let mut from_account = from_account.try_borrow_mut_lamports()?;
181    let mut to_account = to_account.try_borrow_mut_lamports()?;
182    **from_account = from_account
183        .checked_sub(amount_of_lamports)
184        .ok_or(ProgramError::InsufficientFunds)?;
185    **to_account = to_account
186        .checked_add(amount_of_lamports)
187        .ok_or(ProgramError::InsufficientFunds)?;
188    Ok(())
189}
190
191/// Macro for transferring lamports between accounts that implement the Lamports trait
192///
193/// # Requirements
194///
195/// 1. The `from` account must be owned by the executing program.
196/// 2. Both accounts must be marked `mut`.
197/// 3. The total lamports **before** the transaction must equal to total lamports **after**
198///    the transaction.
199/// 4. `lamports` field of both account infos should not currently be borrowed.
200///
201/// # Examples
202/// ```ignore
203/// transfer_lamports_anchor!(
204///  ctx.accounts.from_account,
205///  ctx.accounts.to_account,
206///  amount,
207/// );
208/// ```
209#[macro_export]
210macro_rules! transfer_lamports_anchor {
211    ($from:expr, $to:expr, $amount:expr) => {{
212        if $from.get_lamports() < $amount {
213            return Err(anchor_lang::error::Error::from(
214                anchor_lang::solana_program::program_error::ProgramError::InsufficientFunds,
215            ));
216        }
217        $from.sub_lamports($amount)?;
218        $to.add_lamports($amount)?;
219    }};
220}
221
222/// Checks if the key is from system account
223pub fn validate_system_account_key(key: &Pubkey) -> Result<(), ProgramError> {
224    if !system_program::check_id(key) {
225        msg!("Wrong system account key");
226        return Err(ProgramError::IncorrectProgramId);
227    }
228    Ok(())
229}
230
231/// Checks if the key is from spl associated token account
232pub fn validate_spl_associated_token_account_key(key: &Pubkey) -> Result<(), ProgramError> {
233    if !spl_associated_token_account::check_id(key) {
234        msg!("Wrong spl associated token account key");
235        return Err(ProgramError::IncorrectProgramId);
236    }
237    Ok(())
238}
239
240/// Checks if the key is from rent
241pub fn validate_rent_key(key: &Pubkey) -> Result<(), ProgramError> {
242    if !sysvar::rent::check_id(key) {
243        msg!("Wrong rent key");
244        return Err(ProgramError::IncorrectProgramId);
245    }
246    Ok(())
247}
248
249/// Checks if the key is from sysvar instructions
250pub fn validate_sysvar_instructions_key(key: &Pubkey) -> Result<(), ProgramError> {
251    if !sysvar::instructions::check_id(key) {
252        msg!("Wrong sysvar instructions key");
253        return Err(ProgramError::IncorrectProgramId);
254    }
255    Ok(())
256}
257
258/// Checks if the key is from sysvar instructions
259pub fn validate_mpl_token_metadata_key(key: &Pubkey) -> Result<(), ProgramError> {
260    if *key != mpl_token_metadata::ID {
261        msg!("Wrong mpl token metadata key");
262        return Err(ProgramError::IncorrectProgramId);
263    }
264    Ok(())
265}
266
267#[cfg(test)]
268mod tests {
269    #[allow(deprecated)]
270    use solana_program::{system_program, sysvar};
271
272    use crate::{
273        validate_mpl_token_metadata_key, validate_rent_key,
274        validate_spl_associated_token_account_key, validate_system_account_key,
275        validate_sysvar_instructions_key,
276    };
277
278    #[test]
279    fn validate_system_account_key_works() {
280        assert!(validate_system_account_key(&system_program::ID).is_ok());
281        assert!(validate_system_account_key(&sysvar::instructions::ID).is_err());
282        assert!(validate_system_account_key(&sysvar::rent::ID).is_err());
283    }
284
285    #[test]
286    fn validate_spl_associated_token_account_key_works() {
287        assert!(
288            validate_spl_associated_token_account_key(&spl_associated_token_account::ID).is_ok()
289        );
290        assert!(validate_spl_associated_token_account_key(&sysvar::instructions::ID).is_err());
291        assert!(validate_spl_associated_token_account_key(&sysvar::rent::ID).is_err());
292    }
293
294    #[test]
295    fn validate_rent_key_works() {
296        assert!(validate_rent_key(&sysvar::rent::ID).is_ok());
297        assert!(validate_rent_key(&system_program::ID).is_err());
298        assert!(validate_rent_key(&spl_associated_token_account::ID).is_err());
299    }
300
301    #[test]
302    fn sysvar_instructions_key() {
303        assert!(validate_sysvar_instructions_key(&sysvar::instructions::ID).is_ok());
304        assert!(validate_sysvar_instructions_key(&system_program::ID).is_err());
305        assert!(validate_sysvar_instructions_key(&spl_associated_token_account::ID).is_err());
306    }
307
308    #[test]
309    fn mpl_token_metadata_key() {
310        assert!(validate_mpl_token_metadata_key(&mpl_token_metadata::ID).is_ok());
311        assert!(validate_mpl_token_metadata_key(&system_program::ID).is_err());
312        assert!(validate_mpl_token_metadata_key(&spl_associated_token_account::ID).is_err());
313    }
314}