Typescript
SPL Token with Web3.js

SPL Token with Web3.js

Transfer Instruction

Moves tokens from one account to another. This is the basic operation for sending tokens between users.

Before we can mint any token, we'll need to already have:

  • Initialized a Mint account.
  • A source Token account or Associated Token account that already has at least the amount we want to transfer.
  • A destination Token account or Associated Token account that will receive the tokens from the source Token account.

The amount of tokens we transfer are "normalized" for decimals. This means that if we want to transfer 1 token that has 6 decimals, we'll need to actually put 1e6 as amount

Raw Instruction

By using just "raw" instruction without any abstraction, this is how transferring a token would look like:

const destination = Keypair.generate();
 
const destinationTokenAccount = await getAssociatedTokenAddress(
    mint.publicKey,
    destination.publicKey,
);
 
// Create ATA creation instruction
const createAtaInstruction = createAssociatedTokenAccountIdempotentInstruction(
    keypair.publicKey, // payer
    destinationTokenAccount, // associated token account address
    destination.publicKey, // owner
    mint.publicKey, // mint
);
 
// Transfer tokens to ATA 
const transferInstruction = createTransferInstruction(
    sourceTokenAccount, // source token account pubkey
    destinationTokenAccount, // destination token account pubkey
    keypair.publicKey, // owner of the source token account
    1e6, // amount
);
 
const transaction = new Transaction().add(
    createAtaInstruction,
    transferInstruction,
);
 
const signature = await sendAndConfirmTransaction(connection, transaction, [keypair]);
 
console.log(`Token accounts created and tokens transferred! Check out your TX here: https://explorer.solana.com/tx/${signature}?cluster=devnet`);

Abstracted Instruction

This is how the same instructions would look like abstracted away with the transfer() instruction:

const destination = Keypair.generate();
 
const destinationAta = await getOrCreateAssociatedTokenAccount(
    connection,
    keypair,
    mint,
    destination.publicKey
);
 
console.log(`This is your ATA: ${ata.address}!`)
  
let tx = await transfer(
    connection, // connection
    keypair, // payer
    sourceAta, // source token account
    destinationAta, // destination token account
    keypair.publicKey, // owner of the source token account
    1e6, // amount to transfer
);
 
console.log(`Succesfully Transferred!. Transaction Here: https://explorer.solana.com/tx/${tx}?cluster=devnet`)

Checked Instruction

Contents
View Source
Blueshift © 2025Commit: dd6c76d