The initialize_account
function is to create a new Token Account.
The account
in the struct is the Token Account that is being initialized in the instruction
Here's a solpg link for reference implementation:
https://beta.solpg.io/63170ee1bb7e0b5f4ca6df9c
#[program]
mod hello_anchor {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let space = anchor_spl::token::TokenAccount::LEN as u64;
let lamports = Rent::get()?.minimum_balance(space as usize);
let ix = anchor_lang::solana_program::system_instruction::create_account(
&ctx.accounts.authority.key(),
&ctx.accounts.token_account.key(),
lamports,
space,
&anchor_spl::token::ID,
);
anchor_lang::solana_program::program::invoke(
&ix,
&[ctx.accounts.authority.to_account_info(), ctx.accounts.token_account.to_account_info(), ctx.accounts.system_program.to_account_info()])?;
let cpi_program = ctx.accounts.token_program.to_account_info();
let cpi_accounts = InitializeAccount {
account: ctx.accounts.token_account.to_account_info(),
mint: ctx.accounts.mint.to_account_info(),
authority: ctx.accounts.authority.to_account_info(),
rent: ctx.accounts.rent.to_account_info(),
};
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
anchor_spl::token::initialize_account(cpi_ctx)?;
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(mut)]
pub token_account: Signer<'info>,
pub mint: Account<'info, Mint>,
#[account(mut)]
pub authority: Signer<'info>,
pub token_program: Program<'info, Token>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}