Create Token Account
Create account for Solana SPL token
New Way
import { getCreateAssociatedTokenIdempotentInstructionAsync, TOKEN_PROGRAM_ADDRESS, findAssociatedTokenPda } from "@solana-program/token";
import { createSolanaRpc, createSolanaRpcSubscriptions, sendAndConfirmTransactionFactory, pipe, createTransactionMessage, setTransactionMessageLifetimeUsingBlockhash, signTransactionMessageWithSigners, getSignatureFromTransaction, setTransactionMessageFeePayerSigner, appendTransactionMessageInstructions, createKeyPairSignerFromBytes, address } from "@solana/web3.js";
import walletSecret from '../wallet.json';
async function createAccount() {
const rpc = createSolanaRpc('http://127.0.0.1:8899');
const rpcSubscriptions = createSolanaRpcSubscriptions('ws://127.0.0.1:8900');
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });
const payer = await createKeyPairSignerFromBytes(new Uint8Array(walletSecret));
const mint = address('ERrUbrQcDf6EzChT8gTonvsKTiRrTG9YVhMDJhruHcjP'); // make sure its already created
const instructions = [
await getCreateAssociatedTokenIdempotentInstructionAsync({
mint: mint,
payer: payer,
owner: payer.address,
})
];
const [ata] = await findAssociatedTokenPda({
mint: mint,
owner: payer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const transaction = pipe(
createTransactionMessage({ version: 0 }),
(tx) => setTransactionMessageFeePayerSigner(payer, tx),
(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
(tx) => appendTransactionMessageInstructions(instructions, tx)
);
const signedTransaction = await signTransactionMessageWithSigners(transaction);
try {
await sendAndConfirmTransaction(signedTransaction, {
commitment: 'processed',
skipPreflight: true
});
const signature = getSignatureFromTransaction(signedTransaction);
console.log(`Account created: ${ata} Signature: ${signature}`);
} catch (e) {
console.error('Transaction failed:', e);
throw e;
}
}
createAccount();
Old Way
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import { getOrCreateAssociatedTokenAccount } from '@solana/spl-token';
import walletSecret from './wallet.json' assert { type: "json" };
const createAccount = async () => {
try {
const wallet = Keypair.fromSecretKey(new Uint8Array(walletSecret));
const connection = new Connection('http://127.0.0.1:8899', 'confirmed');
const { address: tokenAccountAddress } = await getOrCreateAssociatedTokenAccount(
connection,
wallet,
new PublicKey('4RWxatXMBct4NQxVG39SXenRbTzSsXvAYBNm8WTXEcxa'), // token must exist and minting must not be disabled
wallet.publicKey
);
console.log(`Token account: ${tokenAccountAddress.toBase58()}`);
return {
tokenAccountAddress: tokenAccountAddress.toBase58()
};
} catch (error) {
console.error('Token creation failed:', error);
throw error;
}
};
createAccount();