diff --git a/src/tools/solana/transfer.ts b/src/tools/solana/transfer.ts index 04473d17..96efd891 100644 --- a/src/tools/solana/transfer.ts +++ b/src/tools/solana/transfer.ts @@ -5,6 +5,8 @@ import { getAssociatedTokenAddress, createTransferInstruction, getMint, + getAccount, + createAssociatedTokenAccountInstruction, } from "@solana/spl-token"; /** @@ -36,6 +38,7 @@ export async function transfer( tx = await agent.connection.sendTransaction(transaction, [agent.wallet]); } else { + const transaction = new Transaction(); // Transfer SPL token const fromAta = await getAssociatedTokenAddress( mint, @@ -43,11 +46,25 @@ export async function transfer( ); const toAta = await getAssociatedTokenAddress(mint, to); + try { + await getAccount(agent.connection, toAta); + } catch { + // Error is thrown if the tokenAccount doesn't exist + transaction.add( + createAssociatedTokenAccountInstruction( + agent.wallet_address, + toAta, + to, + mint, + ), + ); + } + // Get mint info to determine decimals const mintInfo = await getMint(agent.connection, mint); const adjustedAmount = amount * Math.pow(10, mintInfo.decimals); - const transaction = new Transaction().add( + transaction.add( createTransferInstruction( fromAta, toAta,