This is similar to Can I Create an Account and Transfer Tokens in the same Transaction? but the 'answer' to that question doesn't actually show how to use the token account created in the first instruction as the destination for the transfer instruction.
I know I can add an instruction to create an associated token account with:
transaction.add(
createAssociatedTokenAccountInstruction(
payer.publicKey,
associatedToken,
owner,
mint,
programId,
associatedTokenProgramId
)
)
And add instructions to do a transfer with:
transaction.add(
createTransferInstruction(
sourceTokenAccount,
destinationTokenAccount,
ownerPublicKey,
amount,
multiSigners,
programId
)
);
But is it possible to create a token account, and then transfer a token to the newly created destinationTokenAccount
, in a single transaction?
Important:
I understand the concept of chaining instructions with .add()
but I don't know how to use the ATA made during the account creating instruction in the subsequent transfer instruction.
Please don't post answers showing me how to use method chaining to add multiple instructions. That is not the question I am asking.
The reason I'm asking is:
- It would be useful to have a single transaction succeed or fail (rather than, say, paying to make a USDC account for someone in one transaction, then failing to send them money in the next).
- It may be faster to perform all instructions in a single transaction
- I want to calculate fees in advance, and one transaction is simpler to calculate fees for than multiple transactions.