Skip to content

Commit

Permalink
Add createAta instruction if needed for transfer (#266)
Browse files Browse the repository at this point in the history
# 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
  • Loading branch information
thearyanag authored Feb 10, 2025
2 parents d508a7e + 7b5a8e5 commit e2e13fd
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/tools/solana/transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
getAssociatedTokenAddress,
createTransferInstruction,
getMint,
getAccount,
createAssociatedTokenAccountInstruction,
} from "@solana/spl-token";

/**
Expand Down Expand Up @@ -36,18 +38,33 @@ 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,
agent.wallet_address,
);
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,
Expand Down

0 comments on commit e2e13fd

Please sign in to comment.