Search code examples
typescriptsolanacryptocurrencysolana-web3jssolana-transaction-instruction

How can I transfer Solana SPL tokens on mainnet?


I am going to develop a TypeScript script to transfer SPL tokens on mainnet.

So, I refered this guide and I developed this script but this didn't work.

Could you check this code and inform me what is wrong?

import bs58 from "bs58";
import {
  LAMPORTS_PER_SOL,
  Transaction,
  sendAndConfirmTransaction,
  Keypair,
  Connection,
  PublicKey,
} from "@solana/web3.js";
import {
  getOrCreateAssociatedTokenAccount,
  createTransferInstruction,
  getAssociatedTokenAddressSync,
} from "@solana/spl-token";

dotenv.config();

// Keys from .env
const fromWalletPrivateKeyString = process.env.SENDER_WALLET_PRIVATE_KEY as string;
const receiverPublicKeyString = process.env.RECEIVER_WALLET_PUBLIC_KEY as string;

const fromWallet = Keypair.fromSecretKey(bs58.decode(fromWalletPrivateKeyString));
const toWalletPublicKey = new PublicKey(receiverPublicKeyString);

// Token Mint Account Address
const mint = new PublicKey("7WphEnjwKtWWMbb7eEVYeLDNN2jodCo871tVt8jHpump"); // Mainnet

(async () => {
  const connection = new Connection("https://api.mainnet-beta.solana.com");

  // Get or create the fromTokenAccount
  const fromTokenAccount = await getOrCreateAssociatedTokenAccount(
    connection,
    fromWallet,
    mint,
    fromWallet.publicKey
  );

  // Get or create the toTokenAccount
  const toTokenAccount = await getOrCreateAssociatedTokenAccount(
    connection,
    fromWallet,
    mint,
    toWalletPublicKey
  );

  console.log("From Token Account:", fromTokenAccount.address.toString());
  console.log("To Token Account:", toTokenAccount.address.toString());

  // Add token transfer instructions to transaction
  const transaction = new Transaction().add(
    createTransferInstruction(
      fromTokenAccount.address,
      toTokenAccount.address,
      fromWallet.publicKey,
      100 * LAMPORTS_PER_SOL // Adjust the amount based on token decimals
    )
  );

  // Sign transaction, broadcast, and confirm
  const transactionSignature = await sendAndConfirmTransaction(
    connection,
    transaction,
    [fromWallet]
  );

  console.log(
    "Transaction Signature: ",
    `https://solscan.io/tx/${transactionSignature}`
  );
})();

Solution

  • This code is incorrect.

    LAMPORTS_PER_SOL is 1000,000,000. const transaction = new Transaction().add( createTransferInstruction( fromTokenAccount.address, toTokenAccount.address, fromWallet.publicKey, 100 * LAMPORTS_PER_SOL // Adjust the amount based on token decimals ) );

    To transfer send 100 tokens, you need to multiply 100 by token decimals. If you want to get token decimals, you can use getMint() from @solana/spl-token.

    Hope this helps you.

    Thanks.