Solana CookbookTransactions
How to Send Tokens
Use the Token Program to transfer SPL Tokens. In order to send a SPL token, you need to know its SPL token account address. You can both get the address and send tokens with the following example.
send-tokens.ts
import {Connection,clusterApiUrl,Keypair,LAMPORTS_PER_SOL,Transaction,sendAndConfirmTransaction,} from "@solana/web3.js";import {createMint,getOrCreateAssociatedTokenAccount,mintTo,createTransferInstruction,} from "@solana/spl-token";(async () => {// Connect to clusterconst connection = new Connection(clusterApiUrl("devnet"), "confirmed");// Generate a new wallet keypair and airdrop SOLconst fromWallet = Keypair.generate();const fromAirdropSignature = await connection.requestAirdrop(fromWallet.publicKey,LAMPORTS_PER_SOL,);// Wait for airdrop confirmationawait connection.confirmTransaction(fromAirdropSignature);// Generate a new wallet to receive newly minted tokenconst toWallet = Keypair.generate();// Create new token mintconst mint = await createMint(connection,fromWallet,fromWallet.publicKey,null,9,);// Get the token account of the fromWallet Solana address, if it does not exist, create itconst fromTokenAccount = await getOrCreateAssociatedTokenAccount(connection,fromWallet,mint,fromWallet.publicKey,);//get the token account of the toWallet Solana address, if it does not exist, create itconst toTokenAccount = await getOrCreateAssociatedTokenAccount(connection,fromWallet,mint,toWallet.publicKey,);// Minting 1 new token to the "fromTokenAccount" account we just returned/createdawait mintTo(connection,fromWallet,mint,fromTokenAccount.address,fromWallet.publicKey,1000000000, // it's 1 token, but in lamports[],);// Add token transfer instructions to transactionconst transaction = new Transaction().add(createTransferInstruction(fromTokenAccount.address,toTokenAccount.address,fromWallet.publicKey,1,),);// Sign transaction, broadcast, and confirmawait sendAndConfirmTransaction(connection, transaction, [fromWallet]);})();