How to transfer custom SPL Token (USDC) using @Solana\web3.js (amount issues)

2.2k Views Asked by At

I have been trying to transfer custom SPL tokens using @Solana\web3.js and am having issues with the instruction creation. I created the instruction using the Token.createTransferInstruction method but when the instruction is created, my wallet receives all the information added except the amount of tokens I want to send. P.S. I also added the recent blockhash and set the feepayer so those shouldn't be of issue.

var transaction = new web3.Transaction().add(
    splToken.Token.createTransferInstruction(
        splToken.TOKEN_PROGRAM_ID,
        fromTokenAcc.address,
        toTokenAcc.address,
        sender,
        [],
        1
    )
)

As seen above, I use the right parameters to my knowledge but when I send the transaction to my wallet, the amount doesn't get transferred.

I was going to add direct images but StackOverflow said I need at least 10 rep to post images, sorry about that :/

https://i.stack.imgur.com/ucDAt.png

I've also looked into the transfer data that the instruction adds to the transaction and it uses the 3 for transfer instruction but is the 1 where it should be for amount?

https://i.stack.imgur.com/uRSVS.png

Any help would be much appreciated. Thank You!

1

There are 1 best solutions below

2
Garantor On

Solana USDC is a SPL-Token like other non-native token too,Here is how you transfer an existing spl-token already on the blockchain using the latest version of solana/web3.js and spl-token;

import { Keypair, PublicKey, LAMPORTS_PER_SOL } from "@solana/web3.js";
import { transfer, getOrCreateAssociatedTokenAccount } from "@solana/spl-token";
import base58 from "bs58";

export async function TransferToken(
  senderMasterKey,
  tokenAddress,
  recipientAdd,
  amt,
  connectionCluster
) {
  const TokenAddress = new PublicKey(tokenAddress);
  const recipientAddress = new PublicKey(recipientAdd);
  const senderKeypair = Keypair.fromSecretKey(base58.decode(senderMasterKey));
  const addRecipientToAcct = await getOrCreateAssociatedTokenAccount(
    connectionCluster,
    senderKeypair,
    TokenAddress,
    recipientAddress
  );
  const addSenderToAcct = await getOrCreateAssociatedTokenAccount(
    connectionCluster,
    senderKeypair,
    TokenAddress,
    senderKeypair.publicKey
  );
  const tranferToken = await transfer(
    connectionCluster,
    senderKeypair,
    addSenderToAcct.address,
    addRecipientToAcct.address,
    senderKeypair.publicKey,
    amt * 100000
  );
  return tranferToken;
}