How to check and create for Associated Token Account
To check if an Associated Token Account Exist:
let associated_token_address = await findAssociatedTokenAddress(<publickey of Account>,<Mint Address of the Token>);
let associated_token_account_info = await connection.getAccountInfo(associated_token_address);
if (!associated_token_account_info){
//not exist do something
}
findAssociatedTokenAddress = async (
walletAddress: PublicKey,
tokenMintAddress: PublicKey
) => {
return (await PublicKey.findProgramAddress(
[
walletAddress.toBuffer(),
TOKEN_PROGRAM_ID.toBuffer(),
tokenMintAddress.toBuffer(),
],
SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID
))[0];
}
To create Associated Token Account:
const associated_token_account_creationIx = Token.createAssociatedTokenAccountInstruction(
SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID,
TOKEN_PROGRAM_ID,
<Mint Address of the Token>,
<Associated Token Address>,
new PublicKey('B79aeojkWoqiN2S3zTvNR2uLzqqUGs2iNmAin4YsyHrM'),
publicKey
);
await sendTransaction(connection,wallet,[associated_token_account_creationIx],[]);