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

# Using NFTs and Digital Assets in Games

> How to use NFTs in Solana games.

Non-fungible tokens (NFTs) are rapidly gaining popularity as a means of
integrating Solana into games. These unique digital assets are stored on the
Solana blockchain and come with a JSON metadata attached to them. This metadata
allows developers to store important attributes and information about a specific
asset, such as its rarity or specific in-game capabilities.

NFTs can be used in games to represent anything from weapons and armor to
digital real estate and collectibles, providing a new level of ownership and
scarcity for players. Furthermore NFTs can be representing land, houses,
achievements, or even characters in a game. The possibilities are endless.

## Token gating with NFTs

Using NFTs, you can conditionally gate access to a particular part of a game
based on owning the NFT. This can form a more tight-knit community within your
game. In [JavaScript](/developers/docs/clients/official/javascript), you can
check ownership with Metaplex's
[Token Metadata client](https://www.metaplex.com/docs/smart-contracts/token-metadata),
which runs on Metaplex's [Umi](https://www.metaplex.com/docs/dev-tools/umi)
framework. Install it with:

```bash
npm install @metaplex-foundation/umi @metaplex-foundation/umi-bundle-defaults @metaplex-foundation/mpl-token-metadata
```

Then load the player's NFTs and keep the ones from your collection. Check that
the collection is verified: anyone can mint an NFT that names your collection,
but only the collection's authority can verify it.

```js
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
import { publicKey, unwrapOption } from "@metaplex-foundation/umi";
import {
  fetchAllDigitalAssetByOwner,
  mplTokenMetadata
} from "@metaplex-foundation/mpl-token-metadata";

const umi = createUmi("https://api.devnet.solana.com").use(mplTokenMetadata());

// The player's wallet and the mint address of your collection NFT
const playerAddress = publicKey("PLAYER_WALLET_ADDRESS");
const collectionAddress = publicKey("COLLECTION_MINT_ADDRESS");

const assets = await fetchAllDigitalAssetByOwner(umi, playerAddress);

const collectionNfts = assets.filter((asset) => {
  const collection = unwrapOption(asset.metadata.collection);
  return collection?.verified && collection.key === collectionAddress;
});

const hasAccess = collectionNfts.length > 0;
console.log(`Collection NFTs: ${collectionNfts.length}, access: ${hasAccess}`);
```

Another performant way to load NFTs is the
[DAS asset API](https://docs.helius.dev/compression-and-das-api/digital-asset-standard-das-api).
You can see an example of this in the Solana games preset in the JavaScript
client via this
[Code Example](https://github.com/solana-developers/solana-game-preset/blob/main/app/components/DisplayNfts.tsx).

## Bonus effects with NFTs

In addition to providing new revenue streams, NFTs can also be used to provide
in-game benefits and bonuses to players. For instance, a player who owns a "coin
doubler" NFT may receive double the amount of coins for as long as they hold the
NFT in their wallet.

NFTs could be used as in-game consumables, allowing players to use them a set
number of times to gain temporary effects (such as potions or spells). Once
fully consumed, the NFT is burned, and the effect is applied to the player's
character.

These innovative features of NFTs provide game developers with new opportunities
to create unique gameplay experiences and reward players for their ownership of
valuable assets on the Solana blockchain.

> You can follow this developer guide on
> [how to interact with tokens](/developers/cookbook/games/interact-with-tokens)
> within a onchain Solana game.

In the example game, Seven Seas, the program uses 3 different digital assets,
both fungible and non-fungible assets:

- "pirate coins" (fungible tokens) which are used to upgrade ships
- "rum" (fungible tokens) which increases the health of ships
- "cannons" (NFTs) which increase ships damage dealt in battles

> You can find the source code
> [source code](https://github.com/solana-developers/solana-game-examples/tree/main/seven-seas)
> and a detailed
> [eight hour video course](https://www.youtube.com/playlist?list=PLilwLeBwGuK6NsYMPP_BlVkeQgff0NwvU)
> for the Seven Seas game here.

You can also use
[dynamic metadata](/developers/docs/tokens/extensions/dynamic-metadata-nft)
(using Token Extensions) to save character level and experience or items in an
NFT. Here is a
[Video Walkthrough](https://www.youtube.com/watch?v=n-ym1utpzhk&ab_channel=Solana)
with source code that explains dynamic metadata NFTs. This could allow the NFTs
in your game to become more valuable the more the players play with them.

You can also do this with Metaplex's new
[Core NFT standard](https://developers.metaplex.com/core).

## Using NFT metadata for player stats

NFTs also have metadata which can be used for all kind of traits for game
objects. For example, an NFT could represent a game character and their traits
(Strength, Intelligence, Agility, etc) could directly influence how strong the
character is in the game. The attributes live in the JSON file that each NFT's
metadata URI points to. You can load them with the same Metaplex packages as
above:

```js
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults";
import { publicKey } from "@metaplex-foundation/umi";
import {
  fetchAllDigitalAssetByOwner,
  mplTokenMetadata
} from "@metaplex-foundation/mpl-token-metadata";

const umi = createUmi("https://api.devnet.solana.com").use(mplTokenMetadata());
const assets = await fetchAllDigitalAssetByOwner(
  umi,
  publicKey("PLAYER_WALLET_ADDRESS")
);

let physicalDamage = 5;
let magicalDamage = 5;

for (const asset of assets) {
  let json;
  try {
    json = await umi.downloader.downloadJson(asset.metadata.uri);
  } catch {
    continue; // Skip assets whose JSON file can't be loaded
  }

  for (const attribute of json.attributes ?? []) {
    if (attribute.trait_type === "Strength") {
      physicalDamage += parseInt(attribute.value);
    }
    if (attribute.trait_type === "Int") {
      magicalDamage += parseInt(attribute.value);
    }
  }
}

console.log("Player Physical Damage: " + physicalDamage);
console.log("Player Magical Damage: " + magicalDamage);
```

## Use NFTs to save a game state

You can also use the mint of an NFT to
[derive a PDA](/developers/docs/core/pda/pda-derivation) and use it to save the game state
of a player. This could allow you to save any game state of a player directly in
an NFT which the player can take with them (including selling it allowing you to
collect royalties). You can see an example of how that can be done in the
[Solana 2048 game](https://github.com/solana-developers/solana-2048) and the
following code snippet:

```rust
#[account(
    init,
    payer = signer,
    space = 800,
    seeds = [b"player".as_ref(), nftMint.key().as_ref()],
    bump,
)]
pub player: Account<'info, PlayerData>,
```

## Fusing NFTs together

The
[Metaplex Fusion Trifle program](https://github.com/metaplex-foundation/mpl-trifle)
allows NFTs to own other NFTs.

As an example, you could create a plant plot NFT and then use to combine it with
a water NFT and a seed NFT to create a Tomato NFT.

## Use 3D NFTs in a game

Every NFT metadata can also have an "animation url". This url can contain a
video, GIF, or a 3D file. These 3D files usually use the format `.glb` or `.gltf`
and can dynamically be loaded into a game.

For Unity, you can use the [glTFast](https://github.com/atteneder/glTFast)
package. In JavaScript, you can use the
[three.js GLTFLoader](https://discoverthreejs.com/book/first-steps/load-models/).

The following Unity snippet loads the 3D model from an NFT's `animation_url`,
using an `Nft` loaded with the
[Solana Unity SDK](https://github.com/magicblock-labs/Solana.Unity-SDK):

```c#
var gltf = gameObject.AddComponent<GLTFast.GltfAsset>();
gltf.Url = nft.metaplexData.data.offchainData.animation_url;
```

In TypeScript, you can load a glTF file with `gltf-loader-ts`:

```bash
npm install --save-dev gltf-loader-ts
```

```ts
import { GltfAsset, GltfLoader, gltf } from 'gltf-loader-ts';

let loader = new GltfLoader();
let uri = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/BoxTextured/glTF/BoxTextured.gltf';
let asset: GltfAsset = await loader.load(uri);
let gltfJson: gltf.GlTf = asset.gltf;
console.log(gltfJson);
// -> {asset: {...}, scene: 0, scenes: Array(1), nodes: Array(2), meshes: Array(1), ...}

let data = await asset.accessorData(0); // fetches BoxTextured0.bin
let image: HTMLImageElement = await asset.imageData.get(0) // fetches CesiumLogoFlat.png
```

## How to create NFTs in a program and add additional metadata

With the new [Token Extensions](/developers/docs/tokens/extensions), it is possible to
create NFTs in a program and add additional dynamic onchain traits that can be
saved in the NFT's mint account itself.

For example, you could save the experience and player level in the NFT itself.
These NFTs could become more valuable the more the players play with them. A
player 99 character maybe more desirable than a level 1 character.

You can find more resources on working with this type of onchain metadata with
the following links:

- [Guide](/developers/docs/tokens/extensions/metadata)
- [Repository](https://github.com/solana-foundation/program-examples/tree/main/tokens/token-2022/nft-meta-data-pointer/anchor)
- [Video](https://www.youtube.com/watch?v=n-ym1utpzhk&ab_channel=Solana)

## How to create an NFT collection

NFTs on Solana commonly follow the Metaplex standard's for collections. Metaplex
is a company that takes care of the most-used NFT standard on Solana. The most
common way to create an NFT collection is to create a Metaplex
"[Candy Machine](https://developers.metaplex.com/candy-machine)" which lets the
user mint predefined pairs of metadata and images.

You can find more information on working with Metaplex collections in the
[Metaplex community guides](https://developers.metaplex.com/community-guides).

While Metaplex is common, is popular, there are many more NFT standards on
Solana:

- spNFTs
- WNS
- Core
- SPL-22
- SPL-404
- nifty

## NFT staking and missions

You can allow players to stake NFTs (time lock) to create in-game currency or
send NFTs on missions to give the players rewards. The
[Honeycomb Protocol](https://docs.honeycombprotocol.com/) offers this type of
functionality and more.
