1

I am trying to build an anchor project where I want to pass a specefic token from one address to another. The token was made using spl-token in cli. I am getting TokenAccountNotFoundError when running anchor test.

Here is the anchor rust code:

pub fn transfer_tokens(ctx: Context<TransferTokens>, amount: u64) -> Result<()> {
    let cpi_accounts = Transfer {
        from: ctx.accounts.from_token_account.to_account_info(),
        to: ctx.accounts.to_token_account.to_account_info(),
        authority: ctx.accounts.authority.to_account_info(),
    };

    let cpi_program = ctx.accounts.token_program.to_account_info();
    let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);

    token::transfer(cpi_ctx, amount)?;

    Ok(())
}

#[derive(Accounts)]
pub struct TransferTokens<'info> {
    ///CHECK:
    #[account(mut)]
    pub from_token_account: AccountInfo<'info>,
    #[account(mut)]
    ///CHECK:
    pub to_token_account: AccountInfo<'info>,
    pub authority: Signer<'info>,
    pub token_program: Program<'info, Token>,

}

Here is the test code:

  const to = new anchor.web3.PublicKey("EtaPZdsxmKUrumNr6EgUoVaguqdeGHGKAVqnrGtFjeup");

  let bs = bs58.decode("<PRIVATE_KEY>");

  const from_keypair = anchor.web3.Keypair.fromSecretKey(bs);

  const tokenAddress = new anchor.web3.PublicKey("8UWrbejwzaaYGSeNjzAaLZMv6vitTwf7fZ9bxC2wU5Vr"); // ADDRESS OF THE TOKEN I WANT TO PASS


const payer = await getKeypairFromFile("~/.config/solana/id.json");
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

const from_ata = await getOrCreateAssociatedTokenAccount(
  connection,
  from_keypair,
  tokenAddress,
  from
);

const to_ata = await getOrCreateAssociatedTokenAccount(
  connection,
  payer,
  tokenAddress,
  to
);

const tx = await program.methods
  .transferTokens(new anchor.BN(10))
  .accounts({
    fromTokenAccount: from_ata.address,
    toTokenAccount: to_ata.address,
    authority: payer.publicKey,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .signers([payer])
  .rpc();

console.log(tx);
2
  • What's the tokenAccount in getOrCreateAssociatedTokenAccount function? It was supposed to tokenAddress, right?
    – Julbh
    Mar 29 at 3:31
  • Token account was the derived account, the one you get after runnig "spl-token create account" in the cli. I had also tried with tokenAdress, but it is not working as well Mar 30 at 7:17

0

Your Answer

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

Browse other questions tagged or ask your own question.