vipers/
lib.rs

1//! Library for writing safer Solana programs.
2#![deny(missing_docs)]
3#![deny(rustdoc::all)]
4#![allow(rustdoc::missing_doc_code_examples)]
5
6pub mod assert;
7mod error;
8mod keyref;
9pub mod validate;
10
11use anchor_lang::prelude::*;
12pub use error::*;
13pub use keyref::AsKeyRef;
14#[cfg(feature = "spl-associated-token-account")]
15pub use spl_associated_token_account as ata;
16
17pub use validate::Validate;
18
19declare_id!("VipersTest111111111111111111111111111111111");
20
21/// Validates a derived program address.
22///
23/// # Example
24///
25/// ```
26/// use vipers::validate_derived_address;
27/// use anchor_lang::solana_program;
28/// let random = solana_program::system_program::ID;
29/// let seeds: &[&[u8]] = &["test".as_ref() as &[u8], &random.to_bytes()];
30/// let expected = static_pubkey::static_pubkey!("HjTCk2QYVrDPH1emJyrKBjtnooGqTvHfxa8ResZg3Kb4");
31/// assert!(validate_derived_address(
32///   &expected, &vipers::ID, seeds
33/// ));
34/// assert!(!validate_derived_address(
35///   &solana_program::system_program::ID, &vipers::ID, seeds
36/// ));
37/// ```
38pub fn validate_derived_address(
39    derived_address: &Pubkey,
40    program_id: &Pubkey,
41    seeds: &[&[u8]],
42) -> bool {
43    match Pubkey::create_program_address(seeds, program_id) {
44        Ok(ref key) => derived_address == key,
45        _ => false,
46    }
47}
48
49/// Helper for getting the current timestamp.
50pub fn now_i64() -> Result<i64> {
51    Ok(Clock::get()?.unix_timestamp)
52}
53
54/// Helper for getting the current timestamp as any convertible type.
55pub fn now<T: TryFrom<i64>>() -> Result<T> {
56    now_i64()?
57        .try_into()
58        .map_err(|_| ::anchor_lang::prelude::error!(VipersError::IntegerOverflow))
59}
60
61pub mod prelude {
62    //! The prelude contains all commonly used components of the crate. All programs should include it via `use vipers::prelude::*;`.
63
64    pub use super::{
65        assert_is_zero_token_account, assert_keys_eq, assert_keys_neq, invariant, now, now_i64,
66        try_or_err, unwrap_bump, unwrap_checked, unwrap_int, unwrap_opt, unwrap_opt_block,
67        unwrap_or_err, AsKeyRef, CmpError, IntoCmpError, Validate, VipersError,
68    };
69}