anchor_utils/
lib.rs

1//! # Anchor Utils
2//!
3//! Utility functions for simplifying Anchor framework development on Solana.
4//!
5//! This crate provides helper functions that make it easier to work with Anchor programs,
6//! particularly when creating instructions from Anchor's generated client code.
7//!
8//! ## Features
9//!
10//! - **Simplified instruction creation**: Convert Anchor's generated structs directly to Solana instructions
11//! - **Type-safe interface**: Leverages Anchor's type system for compile-time safety
12//! - **Zero overhead**: Minimal abstraction layer with no runtime cost
13
14use anchor_lang::prelude::*;
15use anchor_lang::{InstructionData, ToAccountMetas};
16use solana_program::instruction::Instruction;
17
18/// Creates a new Anchor instruction from the generated `declare_program!` client structs
19///
20/// This function simplifies the process of creating Solana instructions from Anchor's
21/// generated types, providing a clean interface that handles the conversion automatically.
22///
23/// # Arguments
24///
25/// * `program_id` - The on-chain program's public key
26/// * `accounts` - Account struct that implements `ToAccountMetas` (generated by Anchor)
27/// * `data` - Instruction data struct that implements `InstructionData` (generated by Anchor)
28///
29/// # Returns
30///
31/// A [solana_program::instruction::Instruction] ready to be added to a transaction.
32///
33/// # Example
34///
35/// ```rust
36/// use anchor_utils::anchor_instruction;
37/// use anchor_lang::prelude::*;
38/// use solana_program::instruction::Instruction;
39///
40/// // Using Anchor's generated types from declare_program!
41/// declare_program!(quarry_mine);
42///
43/// # let user_authority = Pubkey::new_unique();
44/// # let miner_account = Pubkey::new_unique();
45/// # let quarry_account = Pubkey::new_unique();
46/// # let rewarder_account = Pubkey::new_unique();
47/// # let token_account = Pubkey::new_unique();
48/// # let miner_vault_account = Pubkey::new_unique();
49/// # let token_program_id = Pubkey::new_unique();
50///
51/// let instruction: Instruction = anchor_instruction(
52///     quarry_mine::ID,
53///     quarry_mine::client::accounts::StakeTokens {
54///         authority: user_authority,
55///         miner: miner_account,
56///         quarry: quarry_account,
57///         rewarder: rewarder_account,
58///         token_account: token_account,
59///         miner_vault: miner_vault_account,
60///         token_program: token_program_id,
61///     },
62///     quarry_mine::client::args::StakeTokens {
63///         amount: 1_000_000,
64///     },
65/// );
66/// ```
67pub fn anchor_instruction(
68    program_id: Pubkey,
69    accounts: impl ToAccountMetas,
70    data: impl InstructionData,
71) -> Instruction {
72    Instruction {
73        program_id,
74        accounts: accounts.to_account_metas(None),
75        data: data.data(),
76    }
77}