Інструкція переказу
Переміщує токени з одного рахунку на інший. Це базова операція для надсилання токенів між користувачами.
Перш ніж ми зможемо переказати будь-який токен, нам потрібно вже мати:
Ініціалізований рахунок
Mint.Вихідний рахунок
TokenабоAssociated Token, на якому вже є принаймні та сума, яку ми хочемо переказати.Цільовий рахунок
TokenабоAssociated Token, який отримає токени з вихідного рахункуToken.
Raw Instruction
Використовуючи лише "сиру" інструкцію без будь-якої абстракції, переказ токена виглядатиме так:
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
Ось як ті самі інструкції виглядатимуть з абстракцією за допомогою інструкції transfer():
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]