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 orAssociated Token
account that already has at least the amount we want to transfer. - A destination
Token
account orAssociated Token
account that will receive the tokens from the sourceToken
account.
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`);
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: ${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`)