Skip to content

Instantly share code, notes, and snippets.

@bji
Last active July 4, 2022 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bji/19e68282b8fe9ac0cee7bf2f605efdc1 to your computer and use it in GitHub Desktop.
Save bji/19e68282b8fe9ac0cee7bf2f605efdc1 to your computer and use it in GitHub Desktop.
// Metaplex implementation
pub fn create_or_allocate_account_raw<'a>(
program_id: Pubkey,
new_account_info: &AccountInfo<'a>,
rent_sysvar_info: &AccountInfo<'a>,
system_program_info: &AccountInfo<'a>,
payer_info: &AccountInfo<'a>,
size: usize,
signer_seeds: &[&[u8]],
) -> ProgramResult {
let rent = &Rent::from_account_info(rent_sysvar_info)?;
let required_lamports = rent
.minimum_balance(size)
.max(1)
.saturating_sub(new_account_info.lamports());
if required_lamports > 0 {
msg!("Transfer {} lamports to the new account", required_lamports);
invoke(
&system_instruction::transfer(&payer_info.key, new_account_info.key, required_lamports),
&[
payer_info.clone(),
new_account_info.clone(),
system_program_info.clone(),
],
)?;
}
let accounts = &[new_account_info.clone(), system_program_info.clone()];
msg!("Allocate space for the account");
invoke_signed(
&system_instruction::allocate(new_account_info.key, size.try_into().unwrap()),
accounts,
&[&signer_seeds],
)?;
msg!("Assign the account to the owning program");
invoke_signed(
&system_instruction::assign(new_account_info.key, &program_id),
accounts,
&[&signer_seeds],
)?;
Ok(())
}
// SPL-Token implementation
fn _process_initialize_mint(
accounts: &[AccountInfo],
decimals: u8,
mint_authority: Pubkey,
freeze_authority: COption<Pubkey>,
rent_sysvar_account: bool,
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let mint_info = next_account_info(account_info_iter)?;
let mint_data_len = mint_info.data_len();
let rent = if rent_sysvar_account {
Rent::from_account_info(next_account_info(account_info_iter)?)?
} else {
Rent::get()?
};
let mut mint = Mint::unpack_unchecked(&mint_info.data.borrow())?;
if mint.is_initialized {
return Err(TokenError::AlreadyInUse.into());
}
if !rent.is_exempt(mint_info.lamports(), mint_data_len) {
return Err(TokenError::NotRentExempt.into());
}
mint.mint_authority = COption::Some(mint_authority);
mint.decimals = decimals;
mint.is_initialized = true;
mint.freeze_authority = freeze_authority;
Mint::pack(mint, &mut mint_info.data.borrow_mut())?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment