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());
});
});