0

I am working on some code to transfer some spl-tokens from a user connected wallet. But when I send the transfer instructions, the amount does not show up in the wallet for user approval; and therefore the transfer never succeeds e.g.

wallet transfer approval without amount

My code to do this is:

const mint = await getMint(connection, mint_contract)
const fromTokenAccount = await getAssociatedTokenAddress(mint.address, publicKey)

const transferTokensToSellerIx = createTransferInstruction(fromTokenAccount, toPublicKey, publicKey, 2)
const tx = new Transaction().add( transferTokensToSellerIx )

const blockHash = await connection.getLatestBlockhash()
tx.feePayer = await publicKey
tx.recentBlockhash = await blockHash.blockhash

const signed = await signTransaction(tx)
await connection.sendRawTransaction(signed.serialize())

I'm using spl-token v0.2.0 and ^1.28.0 of solana/web3.js.

Any help would be really appreciated.

Thanks in advance

1
  • Did you ever find the solution?
    – pwbred
    Commented Feb 7, 2023 at 14:58

1 Answer 1

0

The "destination" where you currently have toPublicKey should also be a token account address.

const transferTokensToSellerIx = createTransferInstruction(fromTokenAccount, toPublicKey, publicKey, 2)

So something like this:

const mint = await getMint(connection, mint_contract)
const fromTokenAccount = await getAssociatedTokenAddress(mint.address, publicKey)
const toTokenAccount = await getAssociatedTokenAddress(mint.address, toPublicKey)

const transferTokensToSellerIx = createTransferInstruction(fromTokenAccount, toTokenAccount, publicKey, 2)
const tx = new Transaction().add( transferTokensToSellerIx )

The example above assumes the toTokenAccount exists, you would need to include an additional instruction to create the token account if it does not already exist.

Or you can use getOrCreateAssociatedTokenAccount:

const tokenAccount = await getOrCreateAssociatedTokenAccount(
      connection,
      payer,
      mint,
      owner
  )

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.