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 transfer 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:

ts
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`,
);
Expand
[15 more lines]

Abstracted Instruction

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

ts
const destination = Keypair.generate();

const destinationAta = await getOrCreateAssociatedTokenAccount(
  connection,
  keypair,
  mint,
  destination.publicKey,
);

console.log(`This is your ATA: ${destinationAta.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`,
);
Expand
[8 more lines]

Checked Instruction

Contents
View Source
Blueshift © 2026Commit: 3c44267