Associated Token Account
- create an ata token account
 - manually do it
 - use helper to do it
 
How to Create an Associated Token Account
https://beta.solpg.io/660ce868cffcf4b13384d011
Starter Code
- open solana playground
 - starter code
 
client.ts
import {
  Connection,
  Transaction,
  clusterApiUrl,
  sendAndConfirmTransaction,
  Keypair,
} from "@solana/web3.js";
import {
  createMint,
  createAssociatedTokenAccountInstruction,
  getAssociatedTokenAddressSync,
  TOKEN_2022_PROGRAM_ID,
} from "@solana/spl-token";
 
const wallet = pg.wallet;
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
 
// Create new Mint Account
const mint = await createMint(
  connection,
  wallet.keypair, // payer
  wallet.publicKey, // mint authority
  wallet.publicKey, // freeze authority
  2, // decimals
  new Keypair(), // keypair for mint account
  null,
  TOKEN_2022_PROGRAM_ID,
);Derive Associated Token Address
client.ts
// Derive PDA
const associatedTokenAccountAddress = getAssociatedTokenAddressSync(
  mint, // mint address
  wallet.publicKey, // token account owner
  false, // allow owner off-curve (PDA)
  TOKEN_2022_PROGRAM_ID,
);Build Create Associated Token Account Instruction
client.ts
// Instruction to create associated token account
const instruction = createAssociatedTokenAccountInstruction(
  wallet.publicKey, // payer
  associatedTokenAccountAddress, // token account address
  wallet.publicKey, // owner
  mint, // mint address
  TOKEN_2022_PROGRAM_ID,
);Add Instruction to Transaction
client.ts
// Create transaction with instruction
const transaction = new Transaction().add(instruction);Send Transaction
client.ts
const transactionSignature = await sendAndConfirmTransaction(
  connection,
  transaction,
  [
    wallet.keypair, // payer
  ],
);client.ts
console.log(
  "\nTransaction Signature:",
  `https://explorer.solana.com/tx/${transactionSignature}?cluster=devnet`,
);
 
console.log(
  "\nToken Account: ",
  `https://explorer.solana.com/address/${associatedTokenAccountAddress}?cluster=devnet`,
);Run script
Terminal
runOutput
Running client...
  client.ts:
 
Transaction Signature: https://explorer.solana.com/tx/hi7bbn11SMX9RRc82QUG72FhCxWRpx8h5U5gxsKPc4LmToYMe5hhcmXi6gyNd81s4a532jWQ51Rq8JXf6aWVL2P?cluster=devnet
 
Token Account:  https://explorer.solana.com/address/4iCdCKzXrSZTmtZ1FMHvU3owWcy1fwyYHYzw9BnpN745?cluster=devnet