Overview
This guide covers the fundamental token operations you’ll need in Anchor programs:- Creating token accounts
- Minting new tokens
- Transferring tokens between accounts
- Using Program Derived Addresses (PDAs) as authorities
token_interface module, which works with both the Token Program and Token-2022 Program.
Creating Token Accounts
Before tokens can be held, you must create a token account. Anchor provides two approaches:Associated Token Accounts (Recommended)
Associated Token Accounts (ATAs) are the standard way to create token accounts for users:- Uses
associated_tokenconstraints - Address is deterministically derived from owner + mint
- Requires the
AssociatedTokenprogram - Use
init_if_neededto handle existing accounts (requiresinit-if-neededfeature)
Custom Token Accounts with PDAs
For program-controlled accounts, use custom PDAs:- Uses
tokenconstraints instead ofassociated_token - Requires
seedsandbumpfor PDA derivation - Can set the PDA as its own authority for program-controlled transfers
Minting Tokens
Minting creates new token supply. Only the mint authority can mint tokens.Basic Minting
Minting with PDA Authority
When the mint authority is a PDA, your program must sign with the PDA’s seeds:- Use
ctx.bumps.<account_name>to access the bump seed - Call
.with_signer()on the CPI context with the seeds - The PDA must be set as the mint authority when creating the mint
Transferring Tokens
Transfers move tokens from one token account to another. Usetransfer_checked for safety.
Basic Transfer
transfer_checkedverifies the mint and decimals for safety- The authority must own the source token account
- Both token accounts must be for the same mint
Transfer from Program-Controlled Account
When transferring from a PDA-owned account, use PDA signing:Complete Example
Here’s a complete example showing mint creation, token account creation, minting, and transferring:lib.rs
Common Patterns
Checking Token Balances
Validating Mint and Owner
Burning Tokens
Best Practices
- Use
transfer_checkedovertransfer- It validates mint and decimals - Use
init_if_neededfor ATAs - Handles existing accounts gracefully (requires feature flag) - Store bump seeds - Use
ctx.bumps.<account>instead of recomputing - Use
InterfaceAccountandInterface- Works with both token programs - Validate token account relationships - Check mint and owner match expectations
- Handle decimals correctly - Remember amounts are in base units
Next Steps
- Token Extensions - Learn about Token-2022 extensions like metadata, transfer hooks, and more
- Token Overview - Review token concepts and terminology