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

# Dynamic metadata NFTs using Token Extensions

> Using the metadata token extension it is possible to save dynamic metadata, like level and XP, directly in the mint of an NFT.

With the [Token Extension program](/developers/docs/tokens/extensions), you can create NFTs
and digital assets using the metadata extensions. Together, these extensions
([metadata pointer and token metadata](/developers/docs/tokens/extensions/metadata)) allow
you to put any desired metadata natively onchain. All within a customizable
key-value data store directly on the token's mint account, reducing costs and
complexity.

These can be especially great for [web3 games](https://solana.com/solutions/games-tooling) since
we can now have these "additional metadata fields" within an onchain key-value
store, allowing games to save/access unique state within the NFT itself (like
for a game character's stats or inventory).

## Building the onchain program

In this developer guide, we will demonstrate how to build these Token Extension
based NFTs and custom metadata using an
[Anchor program](https://www.anchor-lang.com/docs). This program will save the
level and the collected resources of a game player within an NFT.

This NFT will be created by the Anchor program so it is very easy to mint from
the JavaScript client. Each NFT will have some basic structure provided via the
Token Metadata interface:

- default onchain fields - `name`, `symbol`, and `uri`
  - the `uri` is a link to an offchain json file which contains the offchain
    metadata of the NFT
- we will also have custom "additional fields" that we define

All of these fields are saved using the metadata extension which is pointed to
the NFT's mint account, making them accessible to anyone or any program.

<Note>

**Video and Source Code**

You can find a video walkthrough of this example on the Solana Foundation
Youtube channel:

- [Video Walkthrough](https://www.youtube.com/watch?v=n-ym1utpzhk)
- [Full Source Code](https://github.com/solana-foundation/program-examples/tree/main/tokens/token-2022/nft-meta-data-pointer/anchor)

</Note>

### Other use case within games

These types of NFTs with customizable onchain metadata open up many interesting
possibilities for game developers. Especially since this metadata can be
directly interacted with or managed by an
[onchain program](/developers/docs/core/programs).

Some of these gaming related use cases include:

- save the level and XP of the player
- the current weapon and armor
- the current quest
- and more.

## Minting the NFT

To create the NFT, the program performs the following steps:

1. Create a mint account
2. Initialize the mint account
3. Create a metadata pointer account
4. Initialize the metadata pointer account
5. Create the metadata account
6. Initialize the metadata account
7. Create the associated token account
8. Mint the token to the associated token account
9. Remove the mint authority (set it to `None`) so no more tokens can be minted

### Rust program code

Here is the rust code used to mint the NFT using the Token extension program:

```rust Program
// calculate the space need for the mint account with the desired extensions
let space = ExtensionType::try_calculate_account_len::<Mint>(
    &[ExtensionType::MetadataPointer])
    .unwrap();

// This is the space required for the metadata account.
// We put the metadata into the mint account at the end so we
// don't need to create and additional account.
// Then the metadata pointer points back to the mint account.
// Using this technique, only one account is needed for both the mint
// information and the metadata.

let meta_data_space = 250;

let lamports_required = (Rent::get()?).minimum_balance(space + meta_data_space);

msg!(
    "Create Mint and metadata account size and cost: {} lamports: {}",
    space as u64,
    lamports_required
);

system_program::create_account(
    CpiContext::new(
        ctx.accounts.token_program.key(),
        system_program::CreateAccount {
            from: ctx.accounts.signer.to_account_info(),
            to: ctx.accounts.mint.to_account_info(),
        },
    ),
    lamports_required,
    space as u64,
    &ctx.accounts.token_program.key(),
)?;

// Assign the mint to the token program
system_program::assign(
    CpiContext::new(
        ctx.accounts.token_program.key(),
        system_program::Assign {
            account_to_assign: ctx.accounts.mint.to_account_info(),
        },
    ),
    &token_2022::ID,
)?;

// Initialize the metadata pointer (Need to do this before initializing the mint)
let init_meta_data_pointer_ix =
spl_token_2022::extension::metadata_pointer::instruction::initialize(
    &Token2022::id(),
    &ctx.accounts.mint.key(),
    Some(ctx.accounts.nft_authority.key()),
    Some(ctx.accounts.mint.key()),
)
.unwrap();

invoke(
    &init_meta_data_pointer_ix,
    &[
        ctx.accounts.mint.to_account_info(),
        ctx.accounts.nft_authority.to_account_info()
    ],
)?;

// Initialize the mint cpi
let mint_cpi_ix = CpiContext::new(
    ctx.accounts.token_program.key(),
    token_2022::InitializeMint2 {
        mint: ctx.accounts.mint.to_account_info(),
    },
);

token_2022::initialize_mint2(
    mint_cpi_ix,
    0,
    &ctx.accounts.nft_authority.key(),
    None).unwrap();

// We use a PDA as a mint authority for the metadata account because
// we want to be able to update the NFT from the program.
let seeds = b"nft_authority";
let bump = ctx.bumps.nft_authority;
let signer: &[&[&[u8]]] = &[&[seeds, &[bump]]];

msg!("Init metadata {0}", ctx.accounts.nft_authority.to_account_info().key);

// Init the metadata account
let init_token_meta_data_ix =
&spl_token_metadata_interface::instruction::initialize(
    &spl_token_2022::id(),
    ctx.accounts.mint.key,
    ctx.accounts.nft_authority.to_account_info().key,
    ctx.accounts.mint.key,
    ctx.accounts.nft_authority.to_account_info().key,
    "Beaver".to_string(),
    "BVA".to_string(),
    "https://arweave.net/MHK3Iopy0GgvDoM7LkkiAdg7pQqExuuWvedApCnzfj0".to_string(),
);

invoke_signed(
    init_token_meta_data_ix,
    &[ctx.accounts.mint.to_account_info().clone(), ctx.accounts.nft_authority.to_account_info().clone()],
    signer,
)?;

// Update the metadata account with an additional metadata field in this case the player level
invoke_signed(
    &spl_token_metadata_interface::instruction::update_field(
        &spl_token_2022::id(),
        ctx.accounts.mint.key,
        ctx.accounts.nft_authority.to_account_info().key,
        spl_token_metadata_interface::state::Field::Key("level".to_string()),
        "1".to_string(),
    ),
    &[
        ctx.accounts.mint.to_account_info().clone(),
        ctx.accounts.nft_authority.to_account_info().clone(),
    ],
    signer
)?;

// Create the associated token account
associated_token::create(
    CpiContext::new(
    ctx.accounts.associated_token_program.key(),
    associated_token::Create {
        payer: ctx.accounts.signer.to_account_info(),
        associated_token: ctx.accounts.token_account.to_account_info(),
        authority: ctx.accounts.signer.to_account_info(),
        mint: ctx.accounts.mint.to_account_info(),
        system_program: ctx.accounts.system_program.to_account_info(),
        token_program: ctx.accounts.token_program.to_account_info(),
    },
))?;

// Mint one token to the associated token account of the player
token_2022::mint_to(
    CpiContext::new_with_signer(
        ctx.accounts.token_program.key(),
        token_2022::MintTo {
            mint: ctx.accounts.mint.to_account_info(),
            to: ctx.accounts.token_account.to_account_info(),
            authority: ctx.accounts.nft_authority.to_account_info(),
        },
        signer
    ),
    1,
)?;

// Remove the mint authority (set it to None) so no more tokens can be minted
token_2022::set_authority(
    CpiContext::new_with_signer(
        ctx.accounts.token_program.key(),
        token_2022::SetAuthority {
            current_authority: ctx.accounts.nft_authority.to_account_info(),
            account_or_mint: ctx.accounts.mint.to_account_info(),
        },
        signer
    ),
    AuthorityType::MintTokens,
    None,
)?;
```

### JavaScript client code

Calling mint NFT from the client is very easy:

```js Client
const nftAuthority = PublicKey.findProgramAddressSync(
  [Buffer.from("nft_authority")],
  program.programId
);

const mint = new Keypair();

const destinationTokenAccount = getAssociatedTokenAddressSync(
  mint.publicKey,
  publicKey,
  false,
  TOKEN_2022_PROGRAM_ID
);

const transaction = await program.methods
  .mintNft()
  .accounts({
    signer: publicKey,
    systemProgram: SystemProgram.programId,
    tokenProgram: TOKEN_2022_PROGRAM_ID,
    tokenAccount: destinationTokenAccount,
    mint: mint.publicKey,
    rent: web3.SYSVAR_RENT_PUBKEY,
    associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
    nftAuthority: nftAuthority[0]
  })
  .signers([mint])
  .transaction();

console.log("transaction", transaction);

const txSig = await sendTransaction(transaction, connection, {
  signers: [mint],
  skipPreflight: true
});

console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`);
```

## Run the example

The code above is adapted from the
[`nft-meta-data-pointer`](https://github.com/solana-foundation/program-examples/tree/main/tokens/token-2022/nft-meta-data-pointer/anchor)
example in the Solana program examples repository: an Anchor program with a
LiteSVM test that mints the NFT and checks its metadata. The example has no web
client; the JavaScript snippet above shows how a client calls `mint_nft`.

### Setup your local environment

In order to run this example locally, you will need to make sure you have
[setup your local environment](/developers/docs/quickstart) for Solana development,
including installing and configuring the Anchor CLI. If you do not already, you
can follow the previously linked setup guide to do so.

### Build and test the program

Clone the repository, then build and test the example:

```shell
git clone https://github.com/solana-foundation/program-examples.git
cd program-examples/tokens/token-2022/nft-meta-data-pointer/anchor
cp ../../../../Cargo.lock .
anchor build
cargo test
```

- The example's `Anchor.toml` pins Anchor 1.2.1 and Solana CLI 4.3.2. If you
  installed Anchor with AVM, as the installer sets it up, the first
  `anchor build` installs those versions and uses them for this project.
- The example has no `Cargo.lock` of its own, so copy the repository's. Without
  it, Cargo resolves newer Agave crates that need a newer Rust than the
  repository's toolchain (Rust 1.97, set in `rust-toolchain.toml`), and the IDL
  build fails with `rustc 1.97.1 is not supported by the following packages`.
- `cargo test` runs the LiteSVM test in `tests/test_mint_nft.rs` against the
  built program, so it doesn't need a running validator. (`anchor test` first
  deploys to a local validator.)

The test passes with:

```shell
test mint_nft ... ok
```

### Project structure

The entry point is in the lib.rs file. Here we define the program id and the
instructions. The instructions are defined in the instructions folder. The state
is defined in the state folder.

So the calls arrive in the lib.rs file and are then forwarded to the
instructions. The instructions then call the state to get the data and update
it.

You can find the mint NFT instruction in the instructions folder.

```shell
programs/extension_nft
├── src
│   ├── instructions
│   │   ├── chop_tree.rs
│   │   ├── init_player.rs
│   │   ├── mint_nft.rs
│   │   └── mod.rs
│   ├── state
│   │   ├── game_data.rs
│   │   ├── mod.rs
│   │   └── player_data.rs
│   ├── constants.rs
│   ├── errors.rs
│   └── lib.rs
└── tests
    └── test_mint_nft.rs
```
