The Token Program
On Solana everything token related is handled by the SPL Token Program and the Token2022 Program: Solana's native token framework that defines how all tokens are created, managed, and transferred.
It's a single, unified program that handles all token operations across the network, ensuring consistency and interoperability.
The decision of having a single, unified interface for all tokens on Solana creates an easy implementation that can be replicated across all dApps (decentralized applications) and integrations (like wallets, ...)
For anchor, everything token related can be found in the anchor-spl
crate. For this reason, after having initialized an Anchor
workspace we can just do:
cargo add anchor-spl
If you're not familiar with anchor, we advise you to go through our introduction to anchor course before moving forward.
Mint and Token Accounts
If you're familiar with Anchor
, you'll know that they have a set of macros that help the user abstract away a lot of the complexities related to initializing accounts.
The same works here for Mint
, Token
and Associated Token
accounts.
Mint Account
Thanks to the macros that Anchor
offers, this is how we can easily create a Mint
account:
#[derive(Accounts)]
pub struct CreateMint<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
payer = signer,
mint::decimals = 6,
mint::authority = signer.key(),
)]
pub mint: Account<'info, Mint>,
pub system_program: Program<'info, System>,
pub token_program: Program<'info, Token>,
}
Token Account
Same goes with the Token
account. Creating a Token
accounts through macros would look like this:
#[derive(Accounts)]
pub struct CreateToken<'info> {
#[account(mut)]
pub signer: Signer<'info>,
pub mint: Account<'info, Mint>,
#[account(
mut,
token::mint = mint,
token::authority = signer,
)]
pub token: Account<'info, TokenAccount>,
pub system_program: Program<'info, System>,
pub token_program: Program<'info, Token>,
}
Associated Token Account
Same goes for the Associated Token
account, creating an Associated Token
accounts through macros would look similar to creating a Token
account, the only difference are the constraint and this is how it would look like:
#[derive(Accounts)]
pub struct CreateToken<'info> {
#[account(mut)]
pub signer: Signer<'info>,
pub mint: Account<'info, Mint>,
#[account(
mut,
associated_token::mint = mint,
associated_token::authority = signer,
)]
pub token: Account<'info, TokenAccount>,
pub system_program: Program<'info, System>,
pub token_program: Program<'info, Token>,
pub associated_token_program: Program<'info, AssociatedToken>,
}