> ## 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.

# How to interact with tokens in programs

> Learn how to use tokens in Solana games with an onchain tutorial

Tokens on Solana can serve various purposes, such as in-game rewards,
incentives, or other applications. For example, you can create tokens and
distribute them to players when they complete specific in-game actions. In this
example we will learn how to setup an Anchor program to mint and burn tokens in
a game.

## Overview

In this tutorial, we will build a game using Anchor to introduce the basics of
interacting with the [Token Program](/developers/docs/tokens) on Solana. The game will be
structured around four main actions: creating a new token mint, initializing
player accounts, rewarding players for defeating enemies, and allowing players
to heal by burning tokens.

The program consists of 4 [instructions](/developers/docs/core/instructions):

- `create_mint` - this instruction creates a new token mint with a
  [program-derived address (PDA)](/developers/docs/core/pda) as the mint authority and
  creates the metadata account for the mint. We will add a constraint that
  allows only an "admin" to invoke this instruction
- `init_player` - this instruction initializes a new player account with a
  starting health of 100
- `kill_enemy` - this instruction deducts 10 health points from the player
  account upon “defeating an enemy” and mints 1 token as a reward for the player
- `heal` - this instruction allows a player to burn 1 token to restore their
  health back to 100

> This example uses some external tools and program, created by Metaplex, for
> working with tokens. For a high-level overview of the relationship among user
> wallets, token mints, token accounts, and token metadata accounts, consider
> exploring this portion of the
> [Metaplex documentation](https://developers.metaplex.com/token-metadata).

## Getting Started

You'll build the program and run its client on your machine with the Anchor
CLI. Before you start,
[install the Solana development tools](/developers/docs/quickstart). The
installer sets up the Anchor CLI 1.1.2, the Solana CLI, Surfpool, Node.js, and
Yarn, which this tutorial uses.

<Steps titleSize="h3">

<Step title="Create the project">

Create a project with a single-file program and a Mocha test:

```bash Terminal
anchor init anchor-token --template single --test-template mocha --package-manager yarn
cd anchor-token
```

`--package-manager yarn` sets the project up with Yarn. Without it,
`anchor init` uses the first of pnpm, Yarn, and npm that it finds. The program
is in `programs/anchor-token/src/lib.rs`, and the client you'll write is the
test file, `tests/anchor-token.ts`.

</Step>

<Step title="Add the dependencies">

In `programs/anchor-token/Cargo.toml`, add `anchor-spl` with its `metadata`
feature, enable Anchor's `init-if-needed` feature (the `init_if_needed`
constraint needs it), and add `anchor-spl/idl-build` to the `idl-build`
feature. Keep the other `[features]` entries that `anchor init` created:

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

[dependencies]
anchor-lang = { version = "1.1.2", features = ["init-if-needed"] }
anchor-spl = { version = "1.1.2", features = ["metadata"] }
```

The client uses the `@solana/spl-token` library. Add it with Yarn:

```bash Terminal
yarn add @solana/spl-token
```

</Step>

<Step title="Load the Token Metadata program">

`anchor test` runs the client against a local [Surfpool](/developers/docs/tools/surfpool)
validator. The `create_mint` instruction calls the Token Metadata program,
which the local validator doesn't have. Add this section to `Anchor.toml`:

```toml Anchor.toml
[surfpool]
online = true
```

`anchor test` starts Surfpool offline unless `online` is `true`. Online,
Surfpool loads accounts that a transaction uses but the local validator doesn't
have, such as the Token Metadata program, from mainnet. Without this setting,
`create_mint` fails with `InvalidProgramExecutable`.

<Note>
  To use `solana-test-validator` instead of Surfpool, add this to `Anchor.toml`
  to clone the Token Metadata program from mainnet, then run
  `anchor test --validator legacy` wherever this tutorial runs `anchor test`:

  ```toml Anchor.toml
  [test.validator]
  url = "https://api.mainnet-beta.solana.com"

  [[test.validator.clone]]
  address = "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
  ```
</Note>

</Step>

</Steps>

Next, replace the starter code in `programs/anchor-token/src/lib.rs` with the
code below:

```rust lib.rs
use anchor_lang::prelude::*;
use anchor_spl::{
    associated_token::AssociatedToken,
    metadata::{
        create_metadata_accounts_v3,
        mpl_token_metadata::{accounts::Metadata as MetadataAccount, types::DataV2},
        CreateMetadataAccountsV3, Metadata,
    },
    token::{burn, mint_to, Burn, Mint, MintTo, Token, TokenAccount},
};

declare_id!("11111111111111111111111111111111");

#[program]
pub mod anchor_token {
    use super::*;
}
```

Here we are simply bringing into scope the crates and corresponding modules we
will be using for this program. We'll be using the `anchor_spl` crate to
interact with the SPL Token program, and its `metadata` module, which re-exports
Metaplex's `mpl_token_metadata` crate, to interact with the Token Metadata
program. You'll replace the `declare_id!` placeholder with your program's
address when you [build the program](#build-the-program).

## Create Mint instruction

First, let's implement an instruction to create a new token mint and its
metadata account. The onchain token metadata, including the name, symbol, and
URI, will be provided as parameters to the instruction.

Additionally, we'll only allow an "admin" to invoke this instruction by defining
an `ADMIN_PUBKEY` constant and using it as a constraint. Be sure to replace
`REPLACE_WITH_YOUR_WALLET_PUBKEY` in the `ADMIN_PUBKEY` line with the address of
the wallet that signs the client's transactions. That's the `wallet` in
`Anchor.toml`, `~/.config/solana/id.json` by default. Print its address with:

```bash Terminal
solana address -k ~/.config/solana/id.json
```

The `create_mint` instruction requires the following accounts:

- `admin` - the `ADMIN_PUBKEY` that signs the transaction and pays for the
  initialization of the accounts
- `reward_token_mint` - the new token mint we are initializing, using a PDA as
  both the mint account's address and its mint authority
- `metadata_account` - the metadata account we are initializing for the token
  mint
- `token_program` - required for interacting with instructions on the Token
  program
- `token_metadata_program` - required account for interacting with instructions
  on the Token Metadata program
- `system_program`- a required account when creating a new account
- `rent` - Sysvar Rent, a required account when creating the metadata account

```rust lib.rs
// Only this public key can call this instruction
const ADMIN_PUBKEY: Pubkey = pubkey!("REPLACE_WITH_YOUR_WALLET_PUBKEY");

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

    // Create new token mint with PDA as mint authority
    pub fn create_mint(
        ctx: Context<CreateMint>,
        uri: String,
        name: String,
        symbol: String,
    ) -> Result<()> {
        // PDA seeds and bump to "sign" for CPI
        let seeds = b"reward";
        let bump = ctx.bumps.reward_token_mint;
        let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]];

        // Onchain token metadata for the mint
        let data_v2 = DataV2 {
            name: name,
            symbol: symbol,
            uri: uri,
            seller_fee_basis_points: 0,
            creators: None,
            collection: None,
            uses: None,
        };

        // CPI Context
        let cpi_ctx = CpiContext::new_with_signer(
            ctx.accounts.token_metadata_program.key(),
            CreateMetadataAccountsV3 {
                metadata: ctx.accounts.metadata_account.to_account_info(), // the metadata account being created
                mint: ctx.accounts.reward_token_mint.to_account_info(), // the mint account of the metadata account
                mint_authority: ctx.accounts.reward_token_mint.to_account_info(), // the mint authority of the mint account
                update_authority: ctx.accounts.reward_token_mint.to_account_info(), // the update authority of the metadata account
                payer: ctx.accounts.admin.to_account_info(), // the payer for creating the metadata account
                system_program: ctx.accounts.system_program.to_account_info(), // the system program account
                rent: ctx.accounts.rent.to_account_info(), // the rent sysvar account
            },
            signer,
        );

        create_metadata_accounts_v3(
            cpi_ctx, // cpi context
            data_v2, // token metadata
            true,    // is_mutable
            true,    // update_authority_is_signer
            None,    // collection details
        )?;

        Ok(())
    }
}

#[derive(Accounts)]
pub struct CreateMint<'info> {
    #[account(
        mut,
        address = ADMIN_PUBKEY
    )]
    pub admin: Signer<'info>,

    // The PDA is both the address of the mint account and the mint authority
    #[account(
        init,
        seeds = [b"reward"],
        bump,
        payer = admin,
        mint::decimals = 9,
        mint::authority = reward_token_mint,

    )]
    pub reward_token_mint: Account<'info, Mint>,

    ///CHECK: Using "address" constraint to validate metadata account address
    #[account(
        mut,
        address = MetadataAccount::find_pda(&reward_token_mint.key()).0
    )]
    pub metadata_account: UncheckedAccount<'info>,

    pub token_program: Program<'info, Token>,
    pub token_metadata_program: Program<'info, Metadata>,
    pub system_program: Program<'info, System>,
    pub rent: Sysvar<'info, Rent>,
}
```

The `create_mint` instruction creates a new token mint, using a Program Derived
Address (PDA) as both the address of the token mint and its mint authority. The
instruction takes a URI (offchain metadata), name, and symbol as parameters.

This instruction then creates a metadata account for the token mint through a
[Cross-Program Invocation (CPI)](/developers/docs/core/cpi) calling the
`create_metadata_accounts_v3` instruction from the Token Metadata program.
`CpiContext::new_with_signer` takes the address of the program to call
(`ctx.accounts.token_metadata_program.key()`), the accounts that instruction
needs, and the seeds the program signs with.

The PDA is used to "sign" the CPI since it is the mint authority, which is a
required signer when creating the metadata account for a mint. The instruction
data (URI, name, symbol) is included in the `DataV2` struct to specify the new
token mint's metadata.

We also verify that the address of the `admin` account signing the transaction
matches the value of the `ADMIN_PUBKEY` constant to ensure only the intended
wallet can invoke this instruction.

```rust
const ADMIN_PUBKEY: Pubkey = pubkey!("REPLACE_WITH_YOUR_WALLET_PUBKEY");
```

## Init Player Instruction

Next, let's implement the `init_player` instruction which creates a new player
account with an initial health of 100. The constant `MAX_HEALTH` is set to 100
to represent the starting health.

The `init_player` instruction requires the following accounts:

- `player_data` - the new player account we are initializing, which will store
  the player's health
- `player` - the user who signs the transaction and pays for the initialization
  of the account
- `system_program` - a required account when creating a new account

```rust lib.rs
// Player max health
const MAX_HEALTH: u8 = 100;

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

    // Create new player account
    pub fn init_player(ctx: Context<InitPlayer>) -> Result<()> {
        ctx.accounts.player_data.health = MAX_HEALTH;
        Ok(())
    }
}
...

#[derive(Accounts)]
pub struct InitPlayer<'info> {
    #[account(
        init,
        payer = player,
        space = 8 + 8,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,
    #[account(mut)]
    pub player: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct PlayerData {
    pub health: u8,
}
```

The `player_data` account is initialized using a program-derived address (PDA)
with the `player` public key as one of the seeds. This ensures that each
`player_data` account is unique and associated with the `player`, allowing every
player to create their own `player_data` account.

## Kill Enemy Instruction

Next, let's implement the `kill_enemy` instruction which reduces the player's
health by 10 and mints 1 token to the player's token account as a reward.

The `kill_enemy` instruction requires the following accounts:

- `player` - the player receiving the token
- `player_data` - the player data account storing the player's current health
- `player_token_account` - the player's associated token account where tokens
  will be minted
- `reward_token_mint` - the token mint account, specifying the type of token
  that will be minted
- `token_program` - required for interacting with instructions on the token
  program
- `associated_token_program` - required when working with associated token
  accounts
- `system_program` - a required account when creating a new account

```rust lib.rs
#[program]
pub mod anchor_token {
    use super::*;
    ...

    // Mint token to player token account
    pub fn kill_enemy(ctx: Context<KillEnemy>) -> Result<()> {
        // Check if player has enough health
        if ctx.accounts.player_data.health == 0 {
            return err!(ErrorCode::NotEnoughHealth);
        }
        // Subtract 10 health from player
        ctx.accounts.player_data.health = ctx.accounts.player_data.health.checked_sub(10).unwrap();

        // PDA seeds and bump to "sign" for CPI
        let seeds = b"reward";
        let bump = ctx.bumps.reward_token_mint;
        let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]];

        // CPI Context
        let cpi_ctx = CpiContext::new_with_signer(
            ctx.accounts.token_program.key(),
            MintTo {
                mint: ctx.accounts.reward_token_mint.to_account_info(),
                to: ctx.accounts.player_token_account.to_account_info(),
                authority: ctx.accounts.reward_token_mint.to_account_info(),
            },
            signer,
        );

        // Mint 1 token, accounting for decimals of mint
        let amount = (1u64)
            .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32))
            .unwrap();

        mint_to(cpi_ctx, amount)?;
        Ok(())
    }
}
...

#[derive(Accounts)]
pub struct KillEnemy<'info> {
    #[account(mut)]
    pub player: Signer<'info>,

    #[account(
        mut,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,

    // Initialize player token account if it doesn't exist
    #[account(
        init_if_needed,
        payer = player,
        associated_token::mint = reward_token_mint,
        associated_token::authority = player
    )]
    pub player_token_account: Account<'info, TokenAccount>,

    #[account(
        mut,
        seeds = [b"reward"],
        bump,
    )]
    pub reward_token_mint: Account<'info, Mint>,

    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
    pub system_program: Program<'info, System>,
}

#[error_code]
pub enum ErrorCode {
    #[msg("Not enough health")]
    NotEnoughHealth,
}
```

The player's health is reduced by 10 to represent the “battle with the enemy”.
We'll also check the player's current health and return a custom Anchor error if
the player has 0 health.

The instruction then uses a cross-program invocation (CPI) to call the `mint_to`
instruction from the Token program and mints 1 token of the `reward_token_mint`
to the `player_token_account` as a reward for killing the enemy.

Since the mint authority for the token mint is a program-derived address (PDA),
we can mint tokens directly by calling this instruction without additional
signers. The program can "sign" on behalf of the PDA, allowing token minting
without explicitly requiring extra signers.

## Heal Instruction

Next, let's implement the `heal` instruction which allows a player to burn 1
token and restore their health to its maximum value.

The `heal` instruction requires the following accounts:

- `player` - the player executing the healing action
- `player_data` - the player data account storing the player's current health
- `player_token_account` - the player's associated token account where the
  tokens will be burned
- `reward_token_mint` - the token mint account, specifying the type of token
  that will be burned
- `token_program` - required for interacting with instructions on the token
  program
- `associated_token_program` - required when working with associated token
  accounts

```rust lib.rs
#[program]
pub mod anchor_token {
    use super::*;
    ...

    // Burn token to health player
    pub fn heal(ctx: Context<Heal>) -> Result<()> {
        ctx.accounts.player_data.health = MAX_HEALTH;

        // CPI Context
        let cpi_ctx = CpiContext::new(
            ctx.accounts.token_program.key(),
            Burn {
                mint: ctx.accounts.reward_token_mint.to_account_info(),
                from: ctx.accounts.player_token_account.to_account_info(),
                authority: ctx.accounts.player.to_account_info(),
            },
        );

        // Burn 1 token, accounting for decimals of mint
        let amount = (1u64)
            .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32))
            .unwrap();

        burn(cpi_ctx, amount)?;
        Ok(())
    }
}
...

#[derive(Accounts)]
pub struct Heal<'info> {
    #[account(mut)]
    pub player: Signer<'info>,

    #[account(
        mut,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,

    #[account(
        mut,
        associated_token::mint = reward_token_mint,
        associated_token::authority = player
    )]
    pub player_token_account: Account<'info, TokenAccount>,

    #[account(
        mut,
        seeds = [b"reward"],
        bump,
    )]
    pub reward_token_mint: Account<'info, Mint>,

    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
}
```

The player's health is restored to its maximum value using the `heal`
instruction. The instruction then uses a cross-program invocation (CPI) to call
the `burn` instruction from the Token program, which burns 1 token from the
`player_token_account` to heal the player.

## Build the Program

You've now completed the program. Your final program should look like this:

```rust lib.rs
use anchor_lang::prelude::*;
use anchor_spl::{
    associated_token::AssociatedToken,
    metadata::{
        create_metadata_accounts_v3,
        mpl_token_metadata::{accounts::Metadata as MetadataAccount, types::DataV2},
        CreateMetadataAccountsV3, Metadata,
    },
    token::{burn, mint_to, Burn, Mint, MintTo, Token, TokenAccount},
};

declare_id!("11111111111111111111111111111111");

const ADMIN_PUBKEY: Pubkey = pubkey!("REPLACE_WITH_YOUR_WALLET_PUBKEY");
const MAX_HEALTH: u8 = 100;

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

    // Create new token mint with PDA as mint authority
    pub fn create_mint(
        ctx: Context<CreateMint>,
        uri: String,
        name: String,
        symbol: String,
    ) -> Result<()> {
        // PDA seeds and bump to "sign" for CPI
        let seeds = b"reward";
        let bump = ctx.bumps.reward_token_mint;
        let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]];

        // Onchain token metadata for the mint
        let data_v2 = DataV2 {
            name: name,
            symbol: symbol,
            uri: uri,
            seller_fee_basis_points: 0,
            creators: None,
            collection: None,
            uses: None,
        };

        // CPI Context
        let cpi_ctx = CpiContext::new_with_signer(
            ctx.accounts.token_metadata_program.key(),
            CreateMetadataAccountsV3 {
                metadata: ctx.accounts.metadata_account.to_account_info(), // the metadata account being created
                mint: ctx.accounts.reward_token_mint.to_account_info(), // the mint account of the metadata account
                mint_authority: ctx.accounts.reward_token_mint.to_account_info(), // the mint authority of the mint account
                update_authority: ctx.accounts.reward_token_mint.to_account_info(), // the update authority of the metadata account
                payer: ctx.accounts.admin.to_account_info(), // the payer for creating the metadata account
                system_program: ctx.accounts.system_program.to_account_info(), // the system program account
                rent: ctx.accounts.rent.to_account_info(), // the rent sysvar account
            },
            signer,
        );

        create_metadata_accounts_v3(
            cpi_ctx, // cpi context
            data_v2, // token metadata
            true,    // is_mutable
            true,    // update_authority_is_signer
            None,    // collection details
        )?;

        Ok(())
    }

    // Create new player account
    pub fn init_player(ctx: Context<InitPlayer>) -> Result<()> {
        ctx.accounts.player_data.health = MAX_HEALTH;
        Ok(())
    }

    // Mint tokens to player token account
    pub fn kill_enemy(ctx: Context<KillEnemy>) -> Result<()> {
        // Check if player has enough health
        if ctx.accounts.player_data.health == 0 {
            return err!(ErrorCode::NotEnoughHealth);
        }
        // Subtract 10 health from player
        ctx.accounts.player_data.health = ctx.accounts.player_data.health.checked_sub(10).unwrap();

        // PDA seeds and bump to "sign" for CPI
        let seeds = b"reward";
        let bump = ctx.bumps.reward_token_mint;
        let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]];

        // CPI Context
        let cpi_ctx = CpiContext::new_with_signer(
            ctx.accounts.token_program.key(),
            MintTo {
                mint: ctx.accounts.reward_token_mint.to_account_info(),
                to: ctx.accounts.player_token_account.to_account_info(),
                authority: ctx.accounts.reward_token_mint.to_account_info(),
            },
            signer,
        );

        // Mint 1 token, accounting for decimals of mint
        let amount = (1u64)
            .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32))
            .unwrap();

        mint_to(cpi_ctx, amount)?;
        Ok(())
    }

    // Burn Token to health player
    pub fn heal(ctx: Context<Heal>) -> Result<()> {
        ctx.accounts.player_data.health = MAX_HEALTH;

        // CPI Context
        let cpi_ctx = CpiContext::new(
            ctx.accounts.token_program.key(),
            Burn {
                mint: ctx.accounts.reward_token_mint.to_account_info(),
                from: ctx.accounts.player_token_account.to_account_info(),
                authority: ctx.accounts.player.to_account_info(),
            },
        );

        // Burn 1 token, accounting for decimals of mint
        let amount = (1u64)
            .checked_mul(10u64.pow(ctx.accounts.reward_token_mint.decimals as u32))
            .unwrap();

        burn(cpi_ctx, amount)?;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct CreateMint<'info> {
    #[account(
        mut,
        address = ADMIN_PUBKEY
    )]
    pub admin: Signer<'info>,

    // The PDA is both the address of the mint account and the mint authority
    #[account(
        init,
        seeds = [b"reward"],
        bump,
        payer = admin,
        mint::decimals = 9,
        mint::authority = reward_token_mint,

    )]
    pub reward_token_mint: Account<'info, Mint>,

    ///CHECK: Using "address" constraint to validate metadata account address
    #[account(
        mut,
        address = MetadataAccount::find_pda(&reward_token_mint.key()).0
    )]
    pub metadata_account: UncheckedAccount<'info>,

    pub token_program: Program<'info, Token>,
    pub token_metadata_program: Program<'info, Metadata>,
    pub system_program: Program<'info, System>,
    pub rent: Sysvar<'info, Rent>,
}

#[derive(Accounts)]
pub struct InitPlayer<'info> {
    #[account(
        init,
        payer = player,
        space = 8 + 8,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,
    #[account(mut)]
    pub player: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct KillEnemy<'info> {
    #[account(mut)]
    pub player: Signer<'info>,

    #[account(
        mut,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,

    // Initialize player token account if it doesn't exist
    #[account(
        init_if_needed,
        payer = player,
        associated_token::mint = reward_token_mint,
        associated_token::authority = player
    )]
    pub player_token_account: Account<'info, TokenAccount>,

    #[account(
        mut,
        seeds = [b"reward"],
        bump,
    )]
    pub reward_token_mint: Account<'info, Mint>,

    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Heal<'info> {
    #[account(mut)]
    pub player: Signer<'info>,

    #[account(
        mut,
        seeds = [b"player".as_ref(), player.key().as_ref()],
        bump,
    )]
    pub player_data: Account<'info, PlayerData>,

    #[account(
        mut,
        associated_token::mint = reward_token_mint,
        associated_token::authority = player
    )]
    pub player_token_account: Account<'info, TokenAccount>,

    #[account(
        mut,
        seeds = [b"reward"],
        bump,
    )]
    pub reward_token_mint: Account<'info, Mint>,

    pub token_program: Program<'info, Token>,
    pub associated_token_program: Program<'info, AssociatedToken>,
}

#[account]
pub struct PlayerData {
    pub health: u8,
}

#[error_code]
pub enum ErrorCode {
    #[msg("Not enough health")]
    NotEnoughHealth,
}
```

Set the program's `declare_id!` to your project's program address, then build
the program:

```bash Terminal
anchor keys sync
anchor build
```

`anchor keys sync` writes the address of the program keypair that `anchor init`
created into `declare_id!`. Without it, `anchor build` only warns
`Program ID mismatch detected`, and the client fails with
`DeclaredProgramIdMismatch`.

If `anchor build` fails, see
[Build your first program](/developers/docs/programs/build-first-program#run-test)
for the workarounds that apply to your Anchor and Solana CLI versions.

## Get Started with the Client

In this section, we'll walk you through a simple client-side implementation for
interacting with the program. The client is the project's Mocha test:
`anchor test` builds the program, starts a local validator, deploys the program
to it, and runs `tests/anchor-token.ts`. To get started, open
`tests/anchor-token.ts`, remove the placeholder code, and add the code snippets
from the following sections.

Start by adding the following code for the setup.

```ts tests/anchor-token.ts
import * as anchor from "@anchor-lang/core";
import { Program } from "@anchor-lang/core";
import { getMint, getAssociatedTokenAddressSync } from "@solana/spl-token";
import { AnchorToken } from "../target/types/anchor_token";

// Configure the client to use the local cluster
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);

const program = anchor.workspace.anchorToken as Program<AnchorToken>;
const connection = provider.connection;
const wallet = provider.wallet;

// metaplex token metadata program ID
const TOKEN_METADATA_PROGRAM_ID = new anchor.web3.PublicKey(
  "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
);

// token metadata
const metadata = {
  uri: "https://raw.githubusercontent.com/solana-foundation/program-examples/main/tokens/.assets/spl-token.json",
  name: "Solana Gold",
  symbol: "GOLDSOL"
};

// reward token mint PDA
const [rewardTokenMintPda] = anchor.web3.PublicKey.findProgramAddressSync(
  [Buffer.from("reward")],
  program.programId
);

// player data account PDA
const [playerPDA] = anchor.web3.PublicKey.findProgramAddressSync(
  [Buffer.from("player"), wallet.publicKey.toBuffer()],
  program.programId
);

// reward token mint metadata account address
const [rewardTokenMintMetadataPDA] = anchor.web3.PublicKey.findProgramAddressSync(
  [
    Buffer.from("metadata"),
    TOKEN_METADATA_PROGRAM_ID.toBuffer(),
    rewardTokenMintPda.toBuffer()
  ],
  TOKEN_METADATA_PROGRAM_ID
);

// player token account address
const playerTokenAccount = getAssociatedTokenAddressSync(
  rewardTokenMintPda,
  wallet.publicKey
);
```

`@anchor-lang/core` is Anchor's TypeScript client. `anchor.workspace.anchorToken`
creates a client for the program from the IDL that `anchor build` writes to
`target/idl/anchor_token.json`, typed with `target/types/anchor_token.ts`. The
provider connects to the local validator that `anchor test` starts and signs
with the `wallet` in `Anchor.toml`.

Next, add the following two helper functions. These functions will be used to
log transaction signatures and fetch account data.

```ts
function logTransaction(txHash: string) {
  console.log(`Transaction signature: ${txHash}`);
}

async function fetchAccountData() {
  const [playerBalance, playerData] = await Promise.all([
    connection.getTokenAccountBalance(playerTokenAccount),
    program.account.playerData.fetch(playerPDA)
  ]);

  console.log("Player Token Balance: ", playerBalance.value.uiAmount);
  console.log("Player Health: ", playerData.health);
}
```

Next, invoke the `createMint` instruction to create a new token mint if it does
not already exist:

```ts
it("Creates the reward token mint", async () => {
  try {
    await getMint(connection, rewardTokenMintPda);
    console.log("Mint Already Exists");
  } catch {
    const txHash = await program.methods
      .createMint(metadata.uri, metadata.name, metadata.symbol)
      .accounts({
        metadataAccount: rewardTokenMintMetadataPDA
      })
      .rpc();
    logTransaction(txHash);
  }
  console.log("Token Mint: ", rewardTokenMintPda.toString());
});
```

`rpc()` sends the transaction and waits for the validator to confirm it. The
client fills in every account that it can work out from the IDL: fixed
addresses such as `admin` and the program accounts, PDAs whose seeds the IDL
describes, such as `rewardTokenMint`, and signers, which default to the
provider's wallet. `accounts()` takes only the rest, here `metadataAccount`,
because the program checks its address with a function call that the IDL can't
describe. Listing an account that the client resolves is a TypeScript error;
use `accountsPartial()` instead to set such accounts yourself.

Next, call the `initPlayer` instruction to create a new player account if one
does not already exist.

```ts
it("Initializes the player", async () => {
  try {
    const playerData = await program.account.playerData.fetch(playerPDA);
    console.log("Player Already Exists");
    console.log("Player Health: ", playerData.health);
  } catch {
    const txHash = await program.methods.initPlayer().rpc();
    logTransaction(txHash);
    console.log("Player Account Created");
  }
});
```

Next, invoke the `killEnemy` instruction:

```ts
it("Kills an enemy", async () => {
  const txHash = await program.methods.killEnemy().rpc();
  logTransaction(txHash);
  console.log("Enemy Defeated");
  await fetchAccountData();
});
```

Next, invoke the `heal` instruction:

```ts
it("Heals the player", async () => {
  const txHash = await program.methods.heal().rpc();
  logTransaction(txHash);
  console.log("Player Healed");
  await fetchAccountData();
});
```

Finally, run the client:

```bash Terminal
anchor test
```

`anchor test` builds the program, starts Surfpool, deploys the program, runs
the client, then stops the validator. The output should be similar to the
following, with your own addresses and signatures. Before it, recent Node.js
releases print a `MODULE_TYPELESS_PACKAGE_JSON` warning about
`tests/anchor-token.ts`, which doesn't affect the client.

```txt title="Output"
Transaction signature: 569qoEtkKPPsFbFL5krsSMPQQbQWe5aXCwVpXAgRxt6ToP1cmpdpongKmvm1xq8HnsTU9XDauavPjgrKvp5pZZDa
Token Mint:  7xH57Gd8qWnMPUEiebTw95ptC3XexkoJWzmYQpioJx3f
  ✔ Creates the reward token mint (125ms)
Transaction signature: 38FsjcD9SWjs4Hw8UDvidDKhPhdzJqSTtf2Q9vqP73XpWM1AXv7WWs7JtnBHwXwa1dYn8hBgA8oYCzyEMDvBJm7D
Player Account Created
  ✔ Initializes the player (58ms)
Transaction signature: jDGBQSBtmr3CqZgYt3JriUXZK6PSwVpck83Mtv8ARmQZRKnEzjqz2avESefc1DDpa1WMweZTy5SX2djnKiT1Pjh
Enemy Defeated
Player Token Balance:  1
Player Health:  90
  ✔ Kills an enemy (75ms)
Transaction signature: 8VPFkkj9oJW4fHdEa1YouZ2rEL81jxAnvAHrpTcbNQNsnonk51iDtjpiQjh865LHSoxvJbsNqEgfgk6MLY97NxE
Player Healed
Player Token Balance:  0
Player Health:  100
  ✔ Heals the player

  4 passing (268ms)
```

Each `anchor test` run starts a new local validator, so the client creates the
mint and the player account every time. The `Mint Already Exists` and
`Player Already Exists` branches only run against a validator that already has
those accounts.

To inspect the transactions and accounts after the client runs, use
`anchor test --detach`, which keeps the validator running until you press
Ctrl+C. Print a transaction's logs, including the Token Metadata program's
`IX: Create Metadata Accounts v3` from `createMint`, with
`solana confirm -v <SIGNATURE> --url localhost`. To look up the token mint
address, open
[Solana Explorer](https://explorer.solana.com/?cluster=custom&customUrl=http%3A%2F%2Flocalhost%3A8899)
connected to the local validator.
