Transfer Tokens
Learn how to transfer tokens between token accounts through cross program invocations (CPIs) in Anchor.
How to Transfer Tokens
Transferring tokens involves moving tokens from one token account to another
token account that share the same mint. This is done by invoking the
transfer_checked
instruction on a token program. Only the address specified as the owner
(authority) of the source token account can transfer tokens out of the account.
The Token Program and Token Extension Program share similar implementations to achieve the same functionality.
Examples
To transfer tokens through an Anchor program, you need to make a cross program
invocation (CPI) to the transfer_checked
instruction on either the Token
Program or Token Extension Program.
This means you are invoking the transfer_checked
instruction on the Token
Program or Token Extension Program from an instruction in your program. Your
program acts as an intermediary, passing along the required accounts,
instruction data, and signatures to the token program.
Transfer Tokens via CPI
Use the token_interface::transfer_checked
function make a CPI to either the
Token Program or Token Extension Program. This function requires:
-
The
TransferChecked
struct which specifies the required accounts:mint
- The mint account specifying the type of token to transferfrom
- The source token account to transfer tokens fromto
- The destination token account to receive the transferred tokensauthority
- The owner of the source token account
-
The
amount
of tokens to transfer, in base units of the token adjusted by decimals. (e.g. if the mint has 2 decimals, amount of 100 = 1 token)
At minimum, the following accounts are required:
Within the instruction logic, use the:
TransferChecked
struct to specify the required accountstoken_interface::transfer_checked
function to make the CPI
Transfer Tokens with PDA token owner via CPI
You can create a token account with a PDA as the owner. This allows your program to transfer tokens from a program controlled token account by "signing" with the PDA's seeds in the Cross Program Invocation (CPI). This pattern is useful when you want the program itself to control token transfers based on conditions defined within the program.
In this example, the source token account owner is set to a Program Derived
Address (PDA). The PDA is derived using the seed b"token"
. This means the
program itself controls token transfers out of the token account through this
PDA.
To transfer tokens, the program must "sign" with the PDA by including the seeds
and bump in the CPI context. This is done by passing the seeds and bump to the
with_signer
method when creating the CPI context.
Note in this example the same PDA is used as both the address of the source token account and the source token account owner.