Integrating with SPL Tokens

Cross-Program Invocations (CPIs)

Chapter 4: Integrating with SPL Tokens

Use CPIs to interact with SPL Token programs for token operations.

  • Key Points:

    • Leverage SPL Token Program for tokens.

    • Anchor provides CPI helpers.

    • Example: Token transfer.

  • Code Example:

pub fn transfer_tokens(ctx: Context<TransferTokens>, amount: u64) -> Result<()> {
    let cpi_program = ctx.accounts.token_program.to_account_info();
    let cpi_accounts = spl_token::instruction::Transfer {
        from: ctx.accounts.from.to_account_info(),
        to: ctx.accounts.to.to_account_info(),
        authority: ctx.accounts.authority.to_account_info(),
    };
    let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
    spl_token::transfer(cpi_ctx, amount)?;
    Ok(())
}
  • Interactivity: Simulate a token transfer and verify balances.

Last updated