I am struggling with creating a program that creates an Associated Token Account (ATA) for a mint I created. I am using the anchor_spl::associated_token
for the task. Here is my code:
use anchor_lang::prelude::*;
use anchor_spl::token::{Token, Mint};
use anchor_spl::associated_token::{self, AssociatedToken, Create};
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
#[program]
pub mod token_util {
use super::*;
pub fn create_ata(ctx: Context<CreateAta>) -> Result<()> {
let cpi_accounts = Create {
payer: ctx.accounts.payer.to_account_info(),
associated_token: ctx.accounts.token_account.to_account_info(),
authority: ctx.accounts.payer.to_account_info(),
mint: ctx.accounts.mint.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
token_program: ctx.accounts.token_program.to_account_info(),
rent: ctx.accounts.rent.to_account_info(),
};
let cpi_program = ctx.accounts.associated_token_program.to_account_info();
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
associated_token::create(cpi_ctx)
}
}
#[derive(Accounts)]
pub struct Purchase<'CreateAta> {
#[account(mut)]
pub payer: Signer<'info>,
/// CHECK: new token account
#[account(mut)]
pub token_account: UncheckedAccount<'info>,
pub mint: Account<'info, Mint>,
pub token_program: Program<'info, Token>,
pub system_program: Program<'info, System>,
pub associated_token_program: Program<'info, AssociatedToken>,
pub rent: Sysvar<'info, Rent>,
}
The PDA I pass via token_account
is correctly derived using the seeds that Associated Token Program is expecting:
const [pda, bump] = await anchor.web3.PublicKey.findProgramAddress(
[payer.publicKey.toBytes(), TOKEN_PROGRAM_ID.toBytes(), mint.toBytes()],
ASSOCIATED_TOKEN_PROGRAM_ID
);
Still, I am getting the following error message when invoking the function create_ata
:
Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: insufficient account keys for instruction
Could it be, that a signer is missing? Maybe the token_account
needs to sign the CPI. But I cannot do this via my own program since it is a PDA that needs to be derived from the Associated Token Program.