Solana CookbookTokens
How to Create a Token Account
A token account is required for a user to hold tokens.
A user will have at least one token account for every type of token they own.
Associated Token Accounts (ATAs) are deterministically created accounts for every keypair. ATAs are the recommended method of managing token accounts.
import {address,createSolanaClient,createTransaction,getExplorerLink,getSignatureFromTransaction,signTransactionMessageWithSigners,} from "gill";import { loadKeypairSignerFromFile } from "gill/node";import {getAssociatedTokenAccountAddress,getCreateAssociatedTokenIdempotentInstruction,TOKEN_PROGRAM_ADDRESS,} from "gill/programs/token";const signer = await loadKeypairSignerFromFile();const { rpc, sendAndConfirmTransaction } = createSolanaClient({urlOrMoniker: "devnet", // or `mainnet`, `localnet`, etc});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("nick6zJc6HpW3kfBm4xS2dmbuVRyb5F3AnUvj5ymzR5");const destinationAta = await getAssociatedTokenAccountAddress(mint,destination,tokenProgram,);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,}),],latestBlockhash,});const signedTransaction = await signTransactionMessageWithSigners(transaction);console.log("Explorer:",getExplorerLink({cluster: "devnet",transaction: getSignatureFromTransaction(signedTransaction),}),);await sendAndConfirmTransaction(signedTransaction);
Is this page helpful?