1

I'm working on a React app and want to send SPL tokens. I use the @solana/spl-token.

When I call getOrCreateAssociatedTokenAccount it throws a TokenAccountNotFoundError unless a token account already exists.

Here is my code:

import { useState } from 'react';
import { useConnection, useWallet } from '@solana/wallet-adapter-react';
import { PublicKey, Transaction } from '@solana/web3.js';
import { getOrCreateAssociatedTokenAccount, TOKEN_PROGRAM_ID, createTransferInstruction } from '@solana/spl-token';

export function SendUSDC() {
  const { connection } = useConnection();
  const { sendTransaction, publicKey, signTransaction } = useWallet();

  const sendTokens = async () => {
    const toPublicKey = new PublicKey('A8t59GvWSN6W3W4LKcqKNDhm9YYDEL8PSt235fyECA8J');

    // The USDC token on the Devnet
    const tokenPublicKey = new PublicKey('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU');

    const fromTokenAccount = await getOrCreateAssociatedTokenAccount(
      connection,
      publicKey,
      tokenPublicKey,
      publicKey,
      signTransaction,
      'finalized'
    );

    let toTokenAccount = await getOrCreateAssociatedTokenAccount(
      connection,
      publicKey,
      tokenPublicKey,
      toPublicKey,
      signTransaction,
      'finalized'
    );

    const tx = new Transaction().add(
      createTransferInstruction(
        fromTokenAccount,
        toTokenAccount,
        fromPublicKey,
        parseInt(10 * Math.pow(10, 6)),
        [],
        TOKEN_PROGRAM_ID
      )
    );

    const latestBlockHash = await connection.getLatestBlockhash();
    tx.recentBlockhash = latestBlockHash.blockhash;

    tx.feePayer = fromPublicKey;

    const hash = await sendTransaction(tx, connection);
    console.log(hash)
  };

  return (
    <div>
      <button disabled={!fromPublicKey} onClick={sendTokens}>
        Send 10 USDC
      </button>
    </div>
  );
}

1 Answer 1

2

Without digging a lot into your question / code, I would recommend to have a look at https://solana-labs.github.io/solana-program-library/token/js/modules.html#getOrCreateAssociatedTokenAccount and check that you're passing the right arguments. Let me know if that helps in any way.

Edit: After looking at your code, and the link provided, the fifth argument of the function is a boolean type (mismatch with signTransaction) that specifies whether or not the owner of the ATA is a PDA (optional argument that is false by default). You should be fine without it.

Try it like this:

const fromTokenAccount = await getOrCreateAssociatedTokenAccount(connection, publicKey, tokenPublicKey, publicKey );

Your Answer

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

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