Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer custom token by '@solana/web3.js'

Tags:

solana

I want to send my deployed token other than sol using solana web3.js, but I don't know how. I've been looking for the official documentation for a long time, but I can't find it. Could you please let me know if you have any information on this? Thanks

like image 552
Normalbut_Genuine Avatar asked Jul 03 '21 12:07

Normalbut_Genuine


2 Answers

The problem with the existing answers is they only show you how to first create a new custom token then perform a transfer from one wallet to another. Here I will show how to do this with an existing custom token.

import { Token, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { web3, Wallet } from "@project-serum/anchor";

async function transfer(tokenMintAddress: string, wallet: Wallet, to: string, connection: web3.Connection, amount: number) {
  const mintPublicKey = new web3.PublicKey(tokenMintAddress);    
  const mintToken = new Token(
    connection,
    mintPublicKey,
    TOKEN_PROGRAM_ID,
    wallet.payer // the wallet owner will pay to transfer and to create recipients associated token account if it does not yet exist.
  );
        
  const fromTokenAccount = await mintToken.getOrCreateAssociatedAccountInfo(
    wallet.publicKey
  );

  const destPublicKey = new web3.PublicKey(to);

  // Get the derived address of the destination wallet which will hold the custom token
  const associatedDestinationTokenAddr = await Token.getAssociatedTokenAddress(
    mintToken.associatedProgramId,
    mintToken.programId,
    mintPublicKey,
    destPublicKey
  );

  const receiverAccount = await connection.getAccountInfo(associatedDestinationTokenAddr);
        
  const instructions: web3.TransactionInstruction[] = [];  

  if (receiverAccount === null) {

    instructions.push(
      Token.createAssociatedTokenAccountInstruction(
        mintToken.associatedProgramId,
        mintToken.programId,
        mintPublicKey,
        associatedDestinationTokenAddr,
        destPublicKey,
        wallet.publicKey
      )
    )

  }
  
  instructions.push(
    Token.createTransferInstruction(
      TOKEN_PROGRAM_ID,
      fromTokenAccount.address,
      associatedDestinationTokenAddr,
      wallet.publicKey,
      [],
      amount
    )
  );

  const transaction = new web3.Transaction().add(...instructions);
  transaction.feePayer = wallet.publicKey;
  transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
  
  const transactionSignature = await connection.sendRawTransaction(
    transaction.serialize(),
    { skipPreflight: true }
  );

  await connection.confirmTransaction(transactionSignature);
}

notice how we add an instruction for creating the recipient's custom token account if they don't have one.

like image 137
Ozymandias Avatar answered Nov 13 '22 18:11

Ozymandias


Small update on @Ozymandias answer, there seems to be few changes in the spl-token library. Firstly Token dosen't exist anymore. And few functions such as Token.getAssociatedTokenAddress also seem to be removed. Here is the updated code:

 

    import * as splToken from "@solana/spl-token";
    import { web3, Wallet } from "@project-serum/anchor";
               
    async function transfer(tokenMintAddress: string, wallet: Wallet, to: string, connection: web3.Connection, amount: number) {
            
                 const mintPublicKey = new web3.PublicKey(tokenMintAddress);  
                 const {TOKEN_PROGRAM_ID} = splToken
                
                 const fromTokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
                    connection,
                    wallet.payer,
                    mintPublicKey,
                    wallet.publicKey
                  );
                
                  const destPublicKey = new web3.PublicKey(to);
                
                  // Get the derived address of the destination wallet which will hold the custom token
                  const associatedDestinationTokenAddr = await splToken.getOrCreateAssociatedTokenAccount(
                    connection,
                    wallet.payer,
                    mintPublicKey,
                    destPublicKey
                  );
                 
                
                  const receiverAccount = await connection.getAccountInfo(associatedDestinationTokenAddr.address);
                        
                  const instructions: web3.TransactionInstruction[] = [];  
                
                  
                  instructions.push(
                    splToken.createTransferInstruction(
                      fromTokenAccount.address,
                      associatedDestinationTokenAddr.address,
                      wallet.publicKey,
                      amount,
                      [],
                      TOKEN_PROGRAM_ID
                    )
                  );
                
                  const transaction = new web3.Transaction().add(...instructions);
                  transaction.feePayer = wallet.publicKey;
                  transaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
                  
                  const transactionSignature = await connection.sendRawTransaction(
                    transaction.serialize(),
                    { skipPreflight: true }
                  );
                
                  await connection.confirmTransaction(transactionSignature);
                }
like image 34
Sanjay Avatar answered Nov 13 '22 19:11

Sanjay