Skip to content

Instantly share code, notes, and snippets.

View alecchendev's full-sized avatar

Alec Chen alecchendev

View GitHub Profile
// calling token program to burn some tokens
invoke(
&spl_token::instruction::burn(
&spl_token::id(),
user_token_account_ai.key,
vending_machine_mint.key,
&user.key,
&[],
price,
)?,
// get accounts
let accounts_iter = &mut accounts.iter();
let ribbon_account = next_account_info(&accounts_iter)?;
// serialize
let ribbon_data = RibbonAccount { // random struct, idk how I thought of this
length: 10,
color: 3
};
ribbon_data.serialize(&mut *ribbon_account.try_borrow_mut_data()?)?;
// get accounts
let accounts_iter = &mut accounts.iter();
let account = next_account_info(&accounts_iter)?;
// modify
let mut account_data = account.try_borrow_mut_data()?;
for i in 0..account.data_len() {
account_data[i] = 0;
}
use solana_program::{entrypoint::ProgramResult, msg, program_error::ProgramError};
pub fn assert_msg(statement: bool, err: ProgramError, msg: &str) -> ProgramResult {
if !statement {
msg!(msg);
Err(err)
} else {
Ok(())
}
}
// usage
// validating token program id
// imports
use solana_program::program_error::ProgramError;
use spl_token;
// code inside of `process_instruction`
// [get accounts] - token_program_account
if *token_program_account.key != spl_token::id() {
return Err(ProgramError::IncorrectProgramId);
}
// [get accounts] - user_ai, pda_ai
// regenerate the PDA
// seed scheme: ["arbitrary_seed", user's key]
let (pda, bump) = Pubkey::find_program_address(
&[
b"arbitrary_seed",
user_ai.key.as_ref(),
],
program_id,
);
// import
use solana_program::{
program_pack::Pack,
};
use spl_token::{
error::TokenError, // custom errors defined in token program
state::{Account as TokenAccount} // alias
}
// code inside of an instruction implementation
// get accounts
// in `state.rs`
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::pubkey::Pubkey;
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct Pool {
pub mint_a: Pubkey,
pub mint_b: Pubkey,
pub mint: Pubkey,
pub fee: u64,
pub fee_decimals: u64,
// import Pack trait
use solana_program::{
program_pack::Pack,
};
// import type
use spl_token::{
state::Mint,
}
// code inside of `process_instruction`
// mint_account is of type `AccountInfo` retrieved previously
// don't forget to import!
use solana_program::{
account_info::{AccountInfo, next_account_info}
};
// code inside of `process_instruction`
let accounts_iter = &mut accounts.iter(); // accounts here refers to the argument denoting the array of `AccountInfo`s
let account_one = next_account_info(accounts_iter)?;
let account_two = next_account_info(accounts_iter)?;
let account_three = next_account_info(accounts_iter)?;
...