Skip to content

Commit e2e13fd

Browse files
authored
Add createAta instruction if needed for transfer (#266)
# Pull Request Description Handles creating the AssociatedTokenAccount for a token if the receiver doesn't have one initialized. [Test transaction](https://solscan.io/tx/2Bnh3J1hUUntTmJyiDX18vbhEDnGxKNYqnVoAJLm1nPqtBcqxP9LsaKdhe6UXpoXKma6cWvqyneMzHhSLPFZDKbi) <img width="1391" alt="image" src="https://github.com/user-attachments/assets/a8f70fa7-c75c-4974-ae74-6dbc811ffa01" /> ## Changes Made This PR adds the following changes: <!-- List the key changes made in this PR --> - Fixes issue when trying to send tokens to an account that has not initialized the associated token account ## Implementation Details <!-- Provide technical details about the implementation --> - Checks for the account with a try-catch block - Adds `createAssociatedTokenAccountInstruction` to the transaction if needed ## Checklist - [x] I have tested these changes locally - [ ] I have updated the documentation - [x] I have added a transaction link - [ ] I have added the prompt used to test it
2 parents d508a7e + 7b5a8e5 commit e2e13fd

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/tools/solana/transfer.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
getAssociatedTokenAddress,
66
createTransferInstruction,
77
getMint,
8+
getAccount,
9+
createAssociatedTokenAccountInstruction,
810
} from "@solana/spl-token";
911

1012
/**
@@ -36,18 +38,33 @@ export async function transfer(
3638

3739
tx = await agent.connection.sendTransaction(transaction, [agent.wallet]);
3840
} else {
41+
const transaction = new Transaction();
3942
// Transfer SPL token
4043
const fromAta = await getAssociatedTokenAddress(
4144
mint,
4245
agent.wallet_address,
4346
);
4447
const toAta = await getAssociatedTokenAddress(mint, to);
4548

49+
try {
50+
await getAccount(agent.connection, toAta);
51+
} catch {
52+
// Error is thrown if the tokenAccount doesn't exist
53+
transaction.add(
54+
createAssociatedTokenAccountInstruction(
55+
agent.wallet_address,
56+
toAta,
57+
to,
58+
mint,
59+
),
60+
);
61+
}
62+
4663
// Get mint info to determine decimals
4764
const mintInfo = await getMint(agent.connection, mint);
4865
const adjustedAmount = amount * Math.pow(10, mintInfo.decimals);
4966

50-
const transaction = new Transaction().add(
67+
transaction.add(
5168
createTransferInstruction(
5269
fromAta,
5370
toAta,

0 commit comments

Comments
 (0)