Solana CookbookTokens
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,} from "gill";import { loadKeypairSignerFromFile } from "gill/node";import {getAssociatedTokenAccountAddress,getCreateAssociatedTokenIdempotentInstruction,getTransferInstruction,TOKEN_PROGRAM_ADDRESS,getTransferTokensInstructions,buildTransferTokensTransaction,} from "gill/programs/token";const signer = await loadKeypairSignerFromFile();const { rpc, sendAndConfirmTransaction } = createSolanaClient({urlOrMoniker: "devnet",});const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();const mint = address("HwxZNMkZbZMeiu9Xnmc6Rg8jYgNsJB47jwabHGUebW4F");const tokenProgram = TOKEN_PROGRAM_ADDRESS; // use the correct program for the `mint`const destination = address("7sZoCrE3cGgEpNgxcPnGffDeWfTewKnk6wWdLxmYA7Cy");const destinationAta = await getAssociatedTokenAccountAddress(mint,destination,tokenProgram,);const source = address("nick6zJc6HpW3kfBm4xS2dmbuVRyb5F3AnUvj5ymzR5");const sourceAta = await getAssociatedTokenAccountAddress(mint,source,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);console.log("Explorer:",getExplorerLink({cluster: "devnet",transaction: getSignatureFromTransaction(signedTransaction),}),);await sendAndConfirmTransaction(signedTransaction);
Is this page helpful?