How to Send Tokens

Use the Token Program or the Token Extensions Program (aka Token22) to transfer SPL Tokens. In order to send a SPL token, you need to know its Associated Token Account (ATA) address, which is derived from:

  • the destination wallet
  • the token mint address
  • the token program used to create the mint

You can both get the token account's address and send tokens to it with the following examples:

import {
address,
createSolanaClient,
createTransaction,
getExplorerLink,
getSignatureFromTransaction,
signTransactionMessageWithSigners,
createKeyPairSignerFromBytes
} from "gill";
import { loadKeypairSignerFromFile } from "gill/node";
import {
getAssociatedTokenAccountAddress,
getCreateAssociatedTokenIdempotentInstruction,
getTransferInstruction,
TOKEN_2022_PROGRAM_ADDRESS,
getTransferTokensInstructions,
buildTransferTokensTransaction
} from "gill/programs/token";
import bs58 from "bs58";
const signer = await createKeyPairSignerFromBytes(
bs58.decode(
"588FU4PktJWfGfxtzpAAXywSNt74AvtroVzGfKkVN1LwRuvHwKGr851uH8czM5qm4iqLbs1kKoMKtMJG4ATR7Ld2"
)
);
const { rpc, sendAndConfirmTransaction } = createSolanaClient({
urlOrMoniker: "http://127.0.0.1:8899"
});
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const mint = address("8mAKLjGGmjKTnmcXeyr3pr7iX13xXVjJJiL6RujDbSPV");
const tokenProgram = TOKEN_2022_PROGRAM_ADDRESS; // use the correct program for the `mint`
const destination = address("nick6zJc6HpW3kfBm4xS2dmbuVRyb5F3AnUvj5ymzR5");
const destinationAta = await getAssociatedTokenAccountAddress(
mint,
destination,
tokenProgram
);
const sourceAta = await getAssociatedTokenAccountAddress(
mint,
signer.address,
tokenProgram
);
/**
* instead of manually crafting the two instructions below, and deriving the ata's above:
* you could use the `getTransferTokensInstructions()` function to simplify this code
*/
const transaction = createTransaction({
feePayer: signer,
version: "legacy",
instructions: [
// create idempotent will gracefully fail if the ata already exists. this is the gold standard!
getCreateAssociatedTokenIdempotentInstruction({
mint,
payer: signer,
tokenProgram,
owner: destination,
ata: destinationAta
}),
getTransferInstruction(
{
source: sourceAta,
authority: signer,
destination: destinationAta,
amount: 1_000_000
},
{ programAddress: tokenProgram }
)
],
latestBlockhash
});
// instead of the above, you can also simplify with `buildTransferTokensTransaction()`
const transaction2 = await buildTransferTokensTransaction({
feePayer: signer,
version: "legacy",
latestBlockhash,
amount: 1_000_000,
authority: signer,
destination: destination,
mint,
tokenProgram
});
const signedTransaction = await signTransactionMessageWithSigners(transaction);
await sendAndConfirmTransaction(signedTransaction);

Is this page helpful?