---
id: BI0083
title: "NFT trait battle game"
url: https://carbium.sh/library/blockchainideas/nft-trait-battle-game
collection: Blockchain ideas
category: Games
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# NFT trait battle game

Two NFTs fight with stats computed from what a read can prove: the mint address and its metadata account, with a recent blockhash as the dice. A runnable main.ts picks two live NFTs and prints the fight.

## The rules

A trait battle needs two things from a chain: numbers every player can read, and a roll nobody can pick. This game takes the numbers from an NFT's mint address and the name and symbol in its metadata account, and the roll from a recent blockhash. Anyone holding the two mints and the hash replays the same fight.

- Each NFT gets four stats from the first four bytes of `sha256(mint|name|symbol)`: hit points 60 to 100, attack 8 to 20, defense 0 to 7, speed 1 to 20.
- Each round the faster NFT strikes first. A speed tie goes to the NFT listed first.
- A hit deals attack minus the target's defense plus a roll of 0 to 5, never less than 1.
- The roll is one byte of `sha256(seed|mintA|mintB|round|side)`, with a pipe between the parts and no spaces.
- The fight lasts 20 rounds at most. The NFT with more hit points left wins, and one more roll settles an exact tie.

No server table decides who is strong. Two NFTs with the same name still differ, because the mint address is part of the hash.

## Listing a wallet's NFTs

A lobby starts from a wallet. `getTokenAccountsByOwner` with a `programId` filter and `jsonParsed` encoding returns every token account the wallet holds under that program. Each parsed entry carries its mint and a `tokenAmount` with `amount` and `decimals`. A candidate NFT has `decimals` 0 and an `amount` of "1".

- A wallet can own more than one token account for one mint, so collect mints in a set before you draw the list.
- Token-2022 tokens sit under their own program id. The lobby makes a second call with that id and merges the two lists.
- Amount 1 with 0 decimals also matches a fungible token held in tiny numbers. The supply check in the next step separates them: an NFT mint has a total supply of 1.

main.ts skips this step so it can run with no wallet. It finds two NFTs from recent chain activity instead. For reading many NFTs at once, see [Bulk NFT metadata reader](https://carbium.sh/library/howsolana/bulk-nft-metadata-reader).

## Reading the metadata account

A Metaplex NFT keeps its name at a program derived address under the Token Metadata program. Derive it from the seeds `"metadata"`, the Token Metadata program id and the mint. A mint address is all you need to find it.

The account starts with a key byte of 4, then the update authority (32 bytes) and the mint (32 bytes). Three strings follow, each a little-endian u32 length and then the bytes: name, symbol and uri. The program pads them with NUL bytes up to 32, 10 and 200 characters, so the file trims them.

The mint account holds the total supply as a little-endian u64 at byte 36 and the decimals at byte 44. One `getMultipleAccounts` call fetches every candidate mint and its derived metadata address together, and each pubkey costs 10 cells. The file sends at most 100 pubkeys per call, since below Pro the 1024-cell burst caps a call there. Up to 300 pubkeys in one call is Pro's.

## Rolling the fight from a blockhash

Order matters. Fix the two fighters first, then read the seed. A hash that existed before the pairing was set is visible to anyone watching the chain, and a player could pick the NFT that wins against it. For a hash nobody could see at lock time, fix a future slot as in [Blockhash raffle draw](https://carbium.sh/library/blockchainideas/blockhash-raffle-draw).

`getLatestBlockhash` at finalized is the seed. Every call in the file names its commitment: confirmed for the account and transaction reads, finalized for the hash. A finalized hash cannot vanish with a dropped fork.

Publish the seed next to the result. A replay then needs two mints and one hash, set as `SEED`, and makes no call for the roll itself. [Live chain-state game](https://carbium.sh/library/blockchainideas/live-chain-state-game) shows how a game can take its turn clock from slots.

## The build

1. Read the newest 8 signatures for the Token Metadata program with `getSignaturesForAddress` and drop the failed ones.
2. Read each with `getTransaction`, `encoding: "json"` and `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and a call without that value answers -32015 for one. Every read is settled on its own: a failure or a null prints and the run goes on. The address index keeps up to 30 days and reaches below the validator's ledger, so a listed signature can come back null.
3. Gather the account keys, including addresses loaded from lookup tables, remove duplicates and well-known program ids, and keep 50.
4. Send one `getMultipleAccounts` for the 50 mints and their 50 derived metadata addresses. Keep a key when its mint has a supply of 1 and 0 decimals and its metadata account starts with byte 4.
5. Take the first two. With two mints as arguments, the file uses those and skips the first three steps.
6. Read the seed, derive the stats, run up to 20 rounds and print names, stats, seed and winner.

`main.ts` (run: `CARBIUM_KEY=<YOUR_KEY> node main.ts`)

```ts
// BI0083 · NFT trait battle game
// https://carbium.sh/library/blockchainideas/nft-trait-battle-game
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress } from "@solana/kit";
import { createHash } from "node:crypto";
const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const METADATA = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
const PROGRAMS = new Set<string>([METADATA, "11111111111111111111111111111111", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", "Sysvar1nstructions1111111111111111111111111"]);
const why = (e: unknown) => (e instanceof Error ? e.message : String(e));
const sha = (s: string) => createHash("sha256").update(s).digest();
type Tx = { transaction: { message: { accountKeys?: string[] } }; meta?: { loadedAddresses?: { writable: string[]; readonly: string[] } } | null };
type Fighter = { mint: string; name: string; symbol: string; uri: string };
async function recentKeys(): Promise<string[]> {
  const sigs = await rpc.getSignaturesForAddress(METADATA, { limit: 8, commitment: "confirmed" }).send();
  const reads = await Promise.allSettled(
    sigs.filter((s) => !s.err).map((s) => rpc.getTransaction(s.signature, { encoding: "json", commitment: "confirmed", maxSupportedTransactionVersion: 1 }).send()),
  );
  const keys = new Set<string>();
  for (const r of reads) {
    if (r.status === "rejected") {
      console.error("getTransaction failed:", why(r.reason));
      continue;
    }
    const tx = r.value as unknown as Tx | null;
    if (!tx) { console.error("getTransaction returned null"); continue; }
    const loaded = tx.meta?.loadedAddresses;
    for (const k of [...(tx.transaction.message.accountKeys ?? []), ...(loaded?.writable ?? []), ...(loaded?.readonly ?? [])]) keys.add(k);
  }
  return [...keys].filter((k) => !PROGRAMS.has(k));
}
async function fighters(mints: string[]): Promise<Fighter[]> {
  const enc = getAddressEncoder();
  const pdas = await Promise.all(mints.map(async (m) => (await getProgramDerivedAddress({ programAddress: METADATA, seeds: ["metadata", enc.encode(METADATA), enc.encode(address(m))] }))[0]));
  const { value } = await rpc.getMultipleAccounts([...mints.map((m) => address(m)), ...pdas], { encoding: "base64", commitment: "confirmed" }).send();
  const bytes = (i: number) => { const b64 = value[i]?.data[0]; return b64 ? Buffer.from(b64, "base64") : null; };
  const out: Fighter[] = [];
  mints.forEach((mint, i) => {
    const m = bytes(i);
    const d = bytes(mints.length + i);
    if (!m || !d || m.length < 82 || m[44] !== 0 || m.readBigUInt64LE(36) !== 1n || d[0] !== 4) return;
    let o = 65;
    const str = () => {
      const n = d.readUInt32LE(o);
      const s = d.toString("utf8", o + 4, o + 4 + n).replace(/\0+$/, "");
      o += 4 + n;
      return s;
    };
    out.push({ mint, name: str(), symbol: str(), uri: str() });
  });
  return out;
}
const stats = (f: Fighter) => {
  const h = sha(`${f.mint}|${f.name}|${f.symbol}`);
  return { hp: 60 + (h[0] % 41), atk: 8 + (h[1] % 13), def: h[2] % 8, spd: 1 + (h[3] % 20) };
};
try {
  const args = process.argv.slice(2);
  const pair = (await fighters(args.length >= 2 ? args.slice(0, 2) : (await recentKeys()).slice(0, 50))).slice(0, 2);
  if (pair.length < 2) throw new Error("no NFT pair found: run again, or pass two NFT mint addresses");
  const [a, b] = pair as [Fighter, Fighter];
  const st = [stats(a), stats(b)];
  const seed = process.env.SEED ?? (await rpc.getLatestBlockhash({ commitment: "finalized" }).send()).value.blockhash;
  const roll = (...p: (string | number)[]) => sha([seed, a.mint, b.mint, ...p].join("|"))[0]!;
  const hp = [st[0].hp, st[1].hp];
  for (let round = 1; round <= 20 && hp[0] > 0 && hp[1] > 0; round++) {
    for (const i of st[0].spd >= st[1].spd ? [0, 1] : [1, 0]) {
      const j = 1 - i;
      if (hp[0] <= 0 || hp[1] <= 0) break;
      hp[j] -= Math.max(1, st[i].atk - st[j].def + (roll(round, i) % 6));
    }
  }
  const win = hp[0] !== hp[1] ? (hp[0] > hp[1] ? 0 : 1) : roll("tie") % 2;
  [a, b].forEach((f, i) => {
    console.log(`${f.name} (${f.symbol}) ${f.mint}`);
    console.log(`  hp ${st[i].hp} atk ${st[i].atk} def ${st[i].def} spd ${st[i].spd} left ${Math.max(0, hp[i])} uri ${f.uri}`);
  });
  console.log(`seed ${seed}`);
  console.log(`winner ${[a, b][win].name}`);
} catch (e) {
  console.error("fight failed:", why(e));
  process.exit(1);
}
```

The run prints each NFT's name, symbol, mint, stats and uri, then the seed and the winner. Pass two mints to replay a pair, and `SEED` to replay a hash. The same pair with the same seed always lands on the same winner.

## What it costs

A match start is a few calls, and the account read dominates.

| Call | Cells each | Per run |
|---|---|---|
| getSignaturesForAddress | 50 | 1 call, 50 cells |
| getTransaction | 50 | up to 8 calls, 400 cells |
| getMultipleAccounts | 10 per pubkey | 100 pubkeys, 1001 cells |

That is at most 1,451 cells plus one blockhash read. A lobby that starts many matches reads each NFT once and keeps its four numbers in its own store, so a match start needs only the blockhash call. A browser should never call the RPC itself: run the game logic on your server.

## Where it ends

- A leader can influence a blockhash. The leader of a slot builds that block and can try different transaction orderings to steer the hash, or skip a block it dislikes. A replay shows the arithmetic was followed and says nothing about whether the leader picked its hash. Keep stakes small, and give a prize pool a roll that players commit to first.
- Traits in the off-chain JSON are your server's fetch. The `uri` points at a file on someone else's host, and attributes such as color or rarity live there. The file prints the uri and never fetches it. A game that wants those traits fetches from its own server with a timeout and a size cap, and parses the answer as untrusted input.
- Metadata can change. The update authority can usually edit a name, and the stats keyed on it move with it. Save the four numbers when a match is created.
- Ownership is a read at one moment. A player can sell the NFT right after the lobby check, so check the holder again when the match starts.
- Nothing here moves a token. The file reads and computes. Escrow, stakes and payouts are yours to build, and signing or sending is outside this file.
- Token-2022 mints without a Metaplex metadata account are skipped by this file.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A `getTransaction` call answers -32015. | The transaction is v1 and the call left `maxSupportedTransactionVersion` out or set it to 0. The file sets 1; keep it in any copy of the call. |
| A listed signature reads back as null. | The address index keeps up to 30 days and reaches below the validator's ledger, so an older signature can be listed and unreadable. The file skips nulls. Work from the newest signatures. |
| The run ends with `no NFT pair found`. | The 8 newest metadata transactions held fewer than two NFT mints, which happens when most of them touch fungible tokens. Run again, or pass two mint addresses. |
| The first call ends with a 401. | The key was refused at the door. Check CARBIUM_KEY and attach the whole key: an unknown key gets 401. |
| The same pair gives a different winner on a replay. | Compare the seed lines first. A replay needs the published blockhash in `SEED`. If the seeds match, compare the names: an edited name changes the stats. |

## Questions

### Why a blockhash and not a random number from my server?

A server roll is a number the players must take on trust. A replay of a published blockhash proves the arithmetic only, because a server that reads the latest hash itself could read many times and keep the one it likes. The server must first record a future slot and publish that slot's blockhash, as in [Blockhash raffle draw](https://carbium.sh/library/blockchainideas/blockhash-raffle-draw), and then players can check it did not pick the hash.

### Can the stats use the traits in the NFT's JSON file?

Yes, from your game server: fetch the `uri` with a timeout and a size cap, validate the fields and add them to the stat hash. Save the result when the match starts, because the file behind a uri can change.

### How does a match with two real players start?

Each player proves a wallet, the lobby checks the holder, then records both mints and the slot. The seed is read after that record exists, so neither player could see it when picking.

### Do Token-2022 NFTs work?

Only with a Metaplex metadata account. A Token-2022 mint that keeps its name inside the mint needs another read; [Token-2022 metadata lookup](https://carbium.sh/library/howsolana/token-2022-metadata-lookup) shows it.

## Related

- [Bulk NFT metadata reader](https://carbium.sh/library/howsolana/bulk-nft-metadata-reader) (How to use Solana, HS0006)
- [Live chain-state game](https://carbium.sh/library/blockchainideas/live-chain-state-game) (Blockchain ideas, BI0009)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
