import * as web3 from "@solana/web3.js"; import * as splToken from "@solana/spl-token-v2"; export async function withFindOrInitAssociatedTokenAccount( transaction: web3.Transaction, connection: web3.Connection, mint: web3.PublicKey, owner: web3.PublicKey, payer: web3.PublicKey, allowOwnerOffCurve?: boolean ): Promise { const associatedAddress = await splToken.getAssociatedTokenAddress( mint, owner, allowOwnerOffCurve, splToken.TOKEN_PROGRAM_ID, splToken.ASSOCIATED_TOKEN_PROGRAM_ID, ); const account = await connection.getAccountInfo(associatedAddress); if (!account) { transaction.add( splToken.createAssociatedTokenAccountInstruction( payer, associatedAddress, owner, mint, splToken.TOKEN_PROGRAM_ID, splToken.ASSOCIATED_TOKEN_PROGRAM_ID, ) ); } return associatedAddress; }