1

I'm trying to send SPL tokens to a specific address using a Wallet Adapter. Also I need to create an associated account for recipient, but the getOrCreateAssociatedTokenAccount @solana/spl-token method requires a keypair.

So, I need to sign the transaction through the Wallet Adapter:

  1. Sender's find or create ATA
  2. Recipient's find or create ATA
  3. createTransferInstruction

enter image description here

1 Answer 1

4

To get or create an associated token account with the wallet-adapter, you need to use the underlying source of getOrCreateAssociatedTokenAccount

const { publicKey, sendTransaction } = useWallet();

const associatedToken = await getAssociatedTokenAddress(
    mint,
    owner,
    allowOwnerOffCurve,
    programId,
    associatedTokenProgramId
);

let account: Account;
try {
    account = await getAccount(connection, associatedToken, commitment, programId);
} catch (error: unknown) {
  if (error instanceof TokenAccountNotFoundError || error instanceof TokenInvalidAccountOwnerError) {
    try {
      const transaction = new Transaction().add(
          createAssociatedTokenAccountInstruction(
              publicKey,
              associatedToken,
              owner,
              mint,
              programId,
              associatedTokenProgramId
          )
      );

      await sendTransaction(connection, transaction);
    } catch (error: unknown) {
    }
    account = await getAccount(connection, associatedToken, commitment, programId);
  } else {
    throw error;
  }
}
return account;

The above code adapts the source code in getOrCreateAssociatedTokenAccount to uses the sendTransaction and publicKey from useWallet in the wallet-adapter to use whatever wallet the user has chosen.

2
  • Thanks, it works. I want to clarify, is it possible to combine a transaction into one and use one confirmation from the Wallet Adapter if the ATA is not created? Now if I send a token to an empty address, I first confirm the creation of the ATA, wait a few seconds for the account to be found, and then a second confirmation occurs from the Wallet Adapter to send the token.
    – Kanitelk
    Commented Jul 31, 2022 at 14:54
  • @Kanitelk yes, with multiple instructions, you can create the ATA in the same transaction as the transfer.
    – Jordan
    Commented Aug 2, 2022 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.