I want to create an associated token address in Solana from a connected wallet address. This is my code currently:
import { useWallet, useConnection } from "@solana/wallet-adapter-react";
...
const wallet = useWallet();
const { publicKey, sendTransaction } = wallet;
const associatedAccount = await getAssociatedTokenAddress(
mintPubkey,
wallet.publicKey
);
const transaction = new Transaction().add(
createAssociatedTokenAccountInstruction(
wallet.publicKey,
associatedAccount,
wallet.publicKey,
mintPubkey,
TOKEN_2022_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
)
);
signature = await sendTransaction(transaction, connection, {
skipPreflight: true,
});
await connection.confirmTransaction(signature, "confirmed");
...
But the tx is keep failing like this:
https://solscan.io/tx/ZaQtfVkNkkAweGug2JfDYz8hcFXh4jDUEJoz2Lik6jPv8huFgzpMXMwui51VJsk8yHmpcWUD6UgnqdmRhu4Covh?cluster=devnet
How can I achieve this?
Because you use Token-2022, you need to specify it when generating the associatedAccount
address. Otherwise it uses the default Token Program.
Documentation: getAssociatedTokenAddress()
const associatedAccount = await getAssociatedTokenAddress(
mintPubkey,
wallet.publicKey,
false,
TOKEN_2022_PROGRAM_ID,
);