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>
);
}