> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Calling the Token Program via CPI

> Invoke the Token Program from an onchain program with a Cross Program Invocation (CPI) — transfer, mint, and burn tokens, sign with a PDA authority, and batch several token instructions into a single CPI.

Onchain programs move tokens by issuing a
[cross-program invocation (CPI)](/developers/docs/core/cpi) into the Token Program. Your
program builds a Token Program instruction, supplies the accounts it needs, and
calls `invoke` (or `invoke_signed` when a program-derived address
signs). The Token Program then runs that instruction with the privileges your
program extends to it.

This page covers the token-specific side of that flow. For the CPI mechanism
itself — how `invoke` and `invoke_signed` work, how signer and writable
privileges propagate, and the
[per-CPI cost model](/developers/docs/core/cpi/cpi-cost-model) — see
[cross-program invocation](/developers/docs/core/cpi).

## Common patterns

Most token CPIs follow the same shape: build the instruction, pass the token
accounts and an authority, and invoke. The example below transfers tokens with
`TransferChecked`, which verifies the mint and decimals as part of the
transfer.

To build the Anchor example in a project created with `anchor init`, add
`anchor-spl` from the program's folder (`programs/<program-name>`):

```bash Terminal
cargo add anchor-spl
```

Then add `anchor-spl/idl-build` to the `idl-build` feature in the program's
`Cargo.toml`. Without it, `anchor build` fails with `Building IDL failed`:

```toml Cargo.toml
[features]
idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"]
```

After you paste the example into `src/lib.rs`, run `anchor keys sync` to write
your program's address into `declare_id!`. `anchor build` also compiles the
tests that `anchor init` created for its template program in
`programs/<program-name>/tests`, so delete them or rewrite them for this
program. If `anchor build` stops with `Platform tools v1.52 is incompatible with
SBPFv3` (Anchor 1.1 with a recent Solana CLI), see the workaround in
[Build your first program](/developers/docs/programs/build-first-program).

The Pinocchio examples on this page use `pinocchio` 0.12 and `pinocchio-token`
0.8:

```bash Terminal
cargo add pinocchio@0.12 pinocchio-token@0.8
```

<CodeGroup>

```rust Anchor
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{transfer_checked, Mint, TokenAccount, TokenInterface, TransferChecked};

declare_id!("YOUR_PROGRAM_ID");

#[program]
pub mod token_cpi {
    use super::*;

    pub fn transfer(ctx: Context<TokenTransfer>, amount: u64) -> Result<()> {
        let cpi_accounts = TransferChecked {
            from: ctx.accounts.source.to_account_info(),
            mint: ctx.accounts.mint.to_account_info(),
            to: ctx.accounts.destination.to_account_info(),
            authority: ctx.accounts.authority.to_account_info(),
        };
        let cpi_ctx = CpiContext::new(
            ctx.accounts.token_program.key(),
            cpi_accounts,
        );

        transfer_checked(cpi_ctx, amount, ctx.accounts.mint.decimals)?;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct TokenTransfer<'info> {
    #[account(mut)]
    pub source: InterfaceAccount<'info, TokenAccount>,
    pub mint: InterfaceAccount<'info, Mint>,
    #[account(mut)]
    pub destination: InterfaceAccount<'info, TokenAccount>,
    pub authority: Signer<'info>,
    pub token_program: Interface<'info, TokenInterface>,
}
```

```rust title="Native (Pinocchio)"
use pinocchio::{account::AccountView, error::ProgramError, ProgramResult};
use pinocchio_token::instructions::TransferChecked;

/// Account layout:
///   [0] source      (writable) — source token account
///   [1] mint                   — token mint
///   [2] destination (writable) — destination token account
///   [3] authority   (signer)   — owner or delegate of the source account
///   [4] token_program          — SPL Token program
pub fn process(accounts: &[AccountView], data: &[u8]) -> ProgramResult {
    if accounts.len() < 5 {
        return Err(ProgramError::NotEnoughAccountKeys);
    }
    if data.len() < 9 {
        return Err(ProgramError::InvalidInstructionData);
    }

    let amount = u64::from_le_bytes(data[0..8].try_into().unwrap());
    let decimals = data[8];

    let source = &accounts[0];
    let mint = &accounts[1];
    let destination = &accounts[2];
    let authority = &accounts[3];

    TransferChecked::new(source, mint, destination, authority, amount, decimals).invoke()?;

    Ok(())
}
```

</CodeGroup>

Minting, burning, and closing accounts follow the same pattern with a different
instruction — `MintTo`, `Burn`, and `CloseAccount` in Anchor's
[`anchor_spl::token`](https://docs.rs/anchor-spl/latest/anchor_spl/token/index.html)
module, or the matching builders in
[`pinocchio-token`](https://crates.io/crates/pinocchio-token). For complete,
runnable programs that CPI into the Token Program in both Anchor and native
Rust, see the [token program examples](/developers/docs/programs/examples#tokens) — in
particular the "Transfer Tokens" example.

<Security title="Check the token program and the accounts it acts on">

- Verify the token program account is `spl_token::ID` or
  `spl_token_2022::ID` before invoking it, and that it matches the owner of
  the token accounts and mint you pass. In Anchor, use
  `Interface<'info, TokenInterface>` with `InterfaceAccount`.
- Use `TransferChecked`, not `Transfer`. It verifies the mint and decimals,
  and the Token Extensions Program requires it for mints with some
  extensions.
- Check that the destination token account's mint and owner are the ones
  you expect. A token transfer to the wrong account succeeds.
- After the CPI, reload the token accounts before reading their balances
  (see [Reload state after a CPI](/developers/docs/core/cpi/cpi-cost-model)).

</Security>

## Signing with a PDA authority

When the authority on a token account is a
[program-derived address](/developers/docs/core/pda) owned by your program, the program
signs the CPI itself with `invoke_signed`, passing the PDA seeds as signer
seeds. In Anchor, use `CpiContext::new_with_signer` with the seeds instead
of `CpiContext::new`. The instruction is otherwise identical to the examples
above. See [CPIs with PDA Signers](/developers/docs/core/cpi/cpi-with-pda) for the full
mechanics.

## Batching

The `Batch` instruction executes several Token Program instructions inside a
single program invocation. Because each CPI carries a fixed compute cost,
running several token operations in one batch CPI uses fewer
[compute units](/developers/docs/core/fees/compute-budget) than issuing a separate CPI per
operation — see the [CPI cost model](/developers/docs/core/cpi/cpi-cost-model) for how
per-CPI costs add up.

Lower compute usage lets you request a smaller compute-unit limit, which lowers
the total [priority fee](/developers/docs/core/fees) at a given compute-unit
price. This matters most for programs that perform many token operations in a
single instruction. Common uses include fanning out a transfer to many
recipients, or running a multi-step token flow (for example sync, transfer, and
close) in a single CPI.

<Info>

`Batch` only accepts Token Program instructions as children, and a batch
cannot contain another batch. For the operations that move tokens (such as
transfers, mints, and burns), the program verifies that the affected accounts
are owned by the Token Program before executing them.

</Info>

### Source reference

| Item            | Description                                | Source                                                                                               |
| --------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `Batch`         | The Batch instruction (discriminator 255). | [Source](https://github.com/solana-program/token/blob/main/pinocchio/interface/src/instruction.rs)   |
| `process_batch` | Batch processor logic.                     | [Source](https://github.com/solana-program/token/blob/main/pinocchio/program/src/processor/batch.rs) |

### Calling Batch via CPI

The [`pinocchio-token`](https://crates.io/crates/pinocchio-token) crate exposes
a `Batch` builder under `pinocchio_token::instructions::Batch`. You
stage each child instruction into the batch's buffers and then issue a single
CPI with `invoke_unchecked`. The example below uses `pinocchio-token` 0.8.

A `Batch` is backed by three caller-provided buffers: one for the serialized
instruction data, one for the per-child instruction account metas, and one for
the account views passed to the CPI. Construct them as `MaybeUninit` slices,
hand them to `Batch::new`, append children, then invoke:

```rust title="Batch two transfers in one CPI"
use core::mem::MaybeUninit;
use pinocchio::{account::AccountView, error::ProgramError, ProgramResult};
use pinocchio_token::instructions::{Batch, IntoBatch, Transfer};

/// Process SwapBatch.
///
/// Performs two transfers in a single batch CPI instead of two separate
/// `invoke()` calls.
///
/// Data layout:
///   [0..8]  amount_a_to_b (u64 LE)
///   [8..16] amount_b_to_a (u64 LE)
///
/// Account layout:
///   [0] source_a    (writable) — token account A
///   [1] source_b    (writable) — token account B
///   [2] authority_a (signer)   — authority for account A
///   [3] authority_b (signer)   — authority for account B
///   [4] token_program          — SPL Token program
pub fn process(accounts: &[AccountView], data: &[u8]) -> ProgramResult {
    if data.len() < 16 {
        return Err(ProgramError::InvalidInstructionData);
    }
    if accounts.len() < 5 {
        return Err(ProgramError::NotEnoughAccountKeys);
    }

    let amount_a_to_b = u64::from_le_bytes(data[0..8].try_into().unwrap());
    let amount_b_to_a = u64::from_le_bytes(data[8..16].try_into().unwrap());

    let source_a = &accounts[0];
    let source_b = &accounts[1];
    let authority_a = &accounts[2];
    let authority_b = &accounts[3];

    // Two child transfers, each with 3 accounts and 9 bytes of data
    // (1-byte discriminator + 8-byte amount).
    const NUM_CHILDREN: usize = 2;
    const CHILD_ACCOUNTS: usize = 3;
    const CHILD_DATA_LEN: usize = 9;

    // Data buffer: 1-byte batch discriminator + per child (2-byte header + data).
    const DATA_LEN: usize = 1 + NUM_CHILDREN * (2 + CHILD_DATA_LEN);
    // Account buffers: total accounts across all children.
    const ACCOUNTS_LEN: usize = NUM_CHILDREN * CHILD_ACCOUNTS;

    let mut data_buf = [MaybeUninit::uninit(); DATA_LEN];
    let mut ix_accounts_buf = [const { MaybeUninit::uninit() }; ACCOUNTS_LEN];
    let mut accounts_buf = [MaybeUninit::uninit(); ACCOUNTS_LEN];

    let mut batch = Batch::new(&mut data_buf, &mut ix_accounts_buf, &mut accounts_buf)?;

    Transfer::new(source_a, source_b, authority_a, amount_a_to_b).into_batch(&mut batch)?;
    Transfer::new(source_b, source_a, authority_b, amount_b_to_a).into_batch(&mut batch)?;

    // SAFETY: `into_batch` checked that the accounts weren't borrowed, and
    // nothing borrows their data or lamports before the batch is invoked.
    unsafe { batch.invoke_unchecked() }?;

    Ok(())
}
```

`Batch::new` writes the batch discriminator into the first byte of the data
buffer and returns a `Batch` that tracks how much of each buffer has been
used. Every Token Program instruction builder (such as `Transfer`,
`TransferChecked`, `MintTo`, and `Burn`) implements the
`IntoBatch` trait, so `into_batch` appends that instruction's data,
account metas, and account views to the batch. Calling `invoke_unchecked`
issues the assembled batch as one CPI into the Token Program.

From `pinocchio-token` 0.8, the batch invoke methods are `unsafe`. `into_batch`
checks that a child's accounts aren't borrowed when you add it, but nothing
checks again when the batch is invoked. Between adding the first child and
invoking the batch, don't borrow the data or lamports of any account in the
batch; otherwise the CPI can change them while a reference is still alive.
Versions 0.6 and 0.7 have safe `invoke` and `invoke_signed` batch methods
instead.

The buffers bound the batch's capacity. Size the data buffer to
`1 + Σ(2 + child_data_len)` bytes (the discriminator, plus a 2-byte header and
the serialized data for each child) and each account buffer to the total number
of accounts across all children. If a child does not fit, `into_batch`
returns `ProgramError::InvalidArgument`. For reference,
`Batch::MAX_DATA_LEN` is 10 KiB and `Batch::MAX_ACCOUNTS_LEN` equals the
runtime's maximum CPI account count.

For batches whose size is only known at runtime, enable the crate's `alloc`
feature and use `BatchState::new(accounts_len, data_len)` to allocate the
buffers on the heap, then call `as_batch` to obtain a `Batch`.

When a child instruction's authority is a PDA owned by your program, sign the
CPI with `invoke_signed_unchecked` instead of `invoke_unchecked`, passing the
PDA seeds as `Signer` entries.

### Instruction data layout

A batch encodes its children one after another behind the `255` discriminator.
All accounts are passed flat, in order, and sliced by `num_accounts` for each
child. The builder produces exactly this wire format:

```text title="Batch Wire Format"
[255]                    // Batch discriminator
// For each child instruction, in order:
//   [num_accounts: u8]  // accounts this instruction consumes
//   [data_len: u8]      // length of this instruction's data
//   [data: u8; data_len]// the instruction data (begins with its own discriminator)
```

<Warning>

A batch's capacity is bounded by the buffers passed to `Batch::new`: the
data buffer must hold the discriminator plus every child's header and data, and
the account buffers must hold every child's accounts. Size them for the largest
batch you build, or use `BatchState` (with the `alloc` feature) to size them
at runtime. The combined CPI is still subject to the transaction's account and
size limits, so for very large fan-outs use Address Lookup Tables to fit more
accounts.

</Warning>
