Solana CookbookTokens
How to Close Token Accounts
You can close a token account if you don't want to use it anymore. There are two situations:
- Wrapped SOL - Closing converts Wrapped SOL to SOL
- Other Tokens - You can close it only if token account's balance is 0.
import { Connection, Keypair } from "@solana/web3.js";import {createMint,getOrCreateAssociatedTokenAccount,closeAccount} from "@solana/spl-token";(async () => {// Connect to local Solana nodeconst connection = new Connection("http://127.0.0.1:8899", "confirmed");// Create a fee payer accountconst feePayer = Keypair.generate();// Request airdrop for fee payerconst airdropSig = await connection.requestAirdrop(feePayer.publicKey,1000000000);await connection.confirmTransaction(airdropSig);// Step 1: Create a new mintconst mintAuthority = feePayer;const freezeAuthority = feePayer;const decimals = 8;console.log("Creating mint...");const mint = await createMint(connection,feePayer,mintAuthority.publicKey,freezeAuthority.publicKey,decimals);console.log("Mint created:", mint.toBase58());// Step 2: Create Associated Token Accountconsole.log("Creating token account...");const tokenAccount = await getOrCreateAssociatedTokenAccount(connection,feePayer,mint,feePayer.publicKey);console.log("Token account:", tokenAccount.address.toBase58());// Step 3: Close the token accountconst txSignature = await closeAccount(connection, // connectionfeePayer, // payertokenAccount.address, // token account which you want to closefeePayer.publicKey, // destinationfeePayer // owner of token account);console.log("Close Token Account:", txSignature);})();
Is this page helpful?