1
        let create_cpi_accounts = associated_token::Create {
            payer: ctx.accounts.user.to_account_info(),
            associated_token: ctx.accounts.wallet.to_account_info(),
            authority: ctx.accounts.mint_authority.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(),
        };
        let cpi_ctx = CpiContext::new(
            ctx.accounts.token_program.clone().to_account_info(),
            create_cpi_accounts,
        );
        associated_token::create(cpi_ctx)?;

Gives me the following error:

     Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: An account required by the instruction is missing

What is causing this? Everything seems to line up with the documentation and I am passing all the correct accounts.

1
  • can you add the rest of the instruction, the accounts, and how you're invoking the instruction?
    – john
    Commented Jan 5 at 18:49

1 Answer 1

5

Here is a Solana Playground example for how to create an associated token account in an Anchor program.

use anchor_lang::prelude::*;
use anchor_spl::{
    associated_token::AssociatedToken,
    token::{Mint, Token, TokenAccount},
};

declare_id!("BQJrDLm7z8NPnE45oNLfWXDzudhBHSDWTsKadxmU4FYE");

#[program]
pub mod example {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        msg!(
            "Created Associated Token Account: {}",
            ctx.accounts.associated_token.key()
        );
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(mut)]
    pub signer: Signer<'info>,
    #[account(
        init,
        payer = signer,
        associated_token::mint = mint,
        associated_token::authority = signer,
    )]
    pub associated_token: Account<'info, TokenAccount>,
    pub mint: Account<'info, Mint>,
    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
    pub system_program: Program<'info, System>,
}

And here is how to you invoke the instruction

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Example } from "../target/types/example";
import {
  createMint,
  getAccount,
  getAssociatedTokenAddressSync,
} from "@solana/spl-token";
import assert from "assert";

describe("example", () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  const wallet = provider.wallet as anchor.Wallet;
  const connection = provider.connection;

  const program = anchor.workspace.Example as Program<Example>;

  it("Is initialized!", async () => {
    // Create new mint account
    const mint = await createMint(
      connection,
      wallet.payer, // payer
      wallet.publicKey, // mint authority
      null, // freeze authority
      2 // decimals
    );

    // Derive associated token account address
    const associatedTokenAddress = getAssociatedTokenAddressSync(
      mint,
      wallet.publicKey
    );

    // Create associated token account via a cross program invocation (CPI)
    const transactionSignature = await program.methods
      .initialize()
      .accounts({
        signer: wallet.publicKey,
        associatedToken: associatedTokenAddress,
        mint: mint,
      })
      .rpc();

    console.log("Your transaction signature", transactionSignature);

    const tokenAccount = await getAccount(connection, associatedTokenAddress);
    assert(tokenAccount.mint.toBase58() == mint.toBase58());
    assert(tokenAccount.owner.toBase58() == wallet.publicKey.toBase58());
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.