library / Blockchain ideas / BI0046
NFT collection authenticity check
A gate that answers one question for a marketplace, mint gate or reward list: does this NFT belong to this collection. It checks the key, the verified flag and the collection's own metadata account, then returns member, claims unverified, other collection or none.
Why the key alone proves nothing
Every NFT made through Token Metadata has a metadata account, and that account holds an optional collection field: a public key and a verified boolean. The creator writes the key at creation, with nobody's approval. A token can name the key of any famous collection and still be a well-formed account.
Wallets and explorers that read only the key file such a token under that collection. A gate that does the same lets a counterfeit through.
A second attack needs no forged key. Someone creates a collection mint of their own, copies the name and image of a popular one, verifies their own items under it and lists them. Every flag reads true. Only the key differs, so the key you compare against comes from your own configuration and never from the item under test.
- The item's collection key equals the collection key you expect.
- The verified flag on that field is set.
- The collection mint has a metadata account of its own, and its update authority is the party that could have set the flag.
Each part closes a gap the others leave. A fake key fails the first, self-claimed membership fails the second, and a collection whose metadata account is gone, as after its collection NFT was burned, fails the third while the flags on its old members stay set.
The verified flag and who sets it
The flag cannot be set when the item is created. Afterwards the collection's update authority, or an authority it delegated, signs a verify instruction, and only then does the flag turn true on the item's metadata account. Until that signature lands, the item names a collection and the flag stays false.
Each metadata account sits at an address derived from its mint. The seeds are the text metadata, the Token Metadata program id (metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s) and the mint, derived under that program. The collection is itself a mint, so it has a metadata account at the same derivation, and the update_authority field of that account is the wallet that can verify members.
The account is Borsh. It holds a kind byte, 32 bytes of update authority, 32 bytes of mint, three length-prefixed strings (name, symbol, uri), a two-byte fee, an optional list of 34-byte creators, two booleans and two optional single bytes. The collection option follows: a tag byte, the verified byte and the 32-byte key. The code walks to that offset by hand.
The gate's four outcomes
| Result | What the accounts say | What the gate does |
|---|---|---|
| member | The collection key equals the expected key, the flag is set and the collection's metadata account was found | Let the item in |
| claims unverified | The key matches, but the flag is false or the collection has no metadata account to name an authority | Refuse: the item points at the collection and nobody with authority vouched for it |
| other collection | The key differs from the expected one | Refuse, and show the key it names so a reviewer can look at the lookalike |
| none | No collection field, or no Token Metadata account at the item's address | Refuse |
A set flag against a collection with no metadata account lands in claims unverified, because nobody can be named as the one who verified. An item that names a different collection is other collection even when its flag is true, since that flag vouches for a collection you did not ask about.
The check in code
The script takes two arguments, the item mint and the expected collection mint. One getMultipleAccounts call reads the item's mint account and its metadata account, and one getAccountInfo call reads the collection's metadata account. They run together. A failed collection read is printed, and the result then falls to claims unverified.
// BI0046 · NFT collection authenticity check// https://carbium.sh/library/blockchainideas/nft-collection-authenticity-check// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, type Address,} from "@solana/kit";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 TOKEN_METADATA = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const enc = getAddressEncoder();const metadataPda = async (mint: Address): Promise<Address> => (await getProgramDerivedAddress({ programAddress: TOKEN_METADATA, seeds: [getUtf8Encoder().encode("metadata"), enc.encode(TOKEN_METADATA), enc.encode(mint)],}))[0];// Borsh walk over a Token Metadata account, down to its collection option.function parseMetadata(base64: string) { const d = Buffer.from(base64, "base64"); if (d[0] !== 4) return null; // key 4 is MetadataV1 let o = 65; // key, update authority, mint for (let i = 0; i < 3; i++) o += 4 + d.readUInt32LE(o); // name, symbol, uri o += 2; // seller_fee_basis_points if (d[o++]) o += 4 + 34 * d.readUInt32LE(o); // creators: address, verified, share o += 2; // primary_sale_happened, is_mutable o += d[o] ? 2 : 1; // edition_nonce o += d[o] ? 2 : 1; // token_standard const dec = getAddressDecoder(); const authority = dec.decode(d, 1); return d[o] ? { authority, collection: { verified: d[o + 1] === 1, key: dec.decode(d, o + 2) } } : { authority };}// The newest Token Metadata transactions touch 0-decimal mints; take the first that names a collection.async function findItem(): Promise<Address[]> { const sigs = await rpc.getSignaturesForAddress(TOKEN_METADATA, { limit: 12 }).send(); const txs = await Promise.allSettled(sigs.filter((s) => !s.err).map((s) => rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send())); const mints = new Set<Address>(); for (const t of txs) { if (t.status === "rejected") console.error("getTransaction failed:", t.reason?.message ?? t.reason); else for (const b of t.value?.meta?.postTokenBalances ?? []) if (b.uiTokenAmount.decimals === 0) mints.add(b.mint); } const list = Array.from(mints).slice(0, 100); // 100 pubkeys is the most one call carries below Pro const { value } = await rpc.getMultipleAccounts(await Promise.all(list.map((m) => metadataPda(m))), { encoding: "base64" }).send(); for (let i = 0; i < value.length; i++) { const acc = value[i]; const c = acc && parseMetadata(acc.data[0])?.collection; if (c) return [list[i], c.key]; } throw new Error("no 0-decimal mint with a collection in the newest transactions; pass two addresses");}async function check(item: Address, expected: Address): Promise<void> { const [itemRes, colRes] = await Promise.allSettled([ metadataPda(item).then((pda) => rpc.getMultipleAccounts([item, pda], { encoding: "base64" }).send()), metadataPda(expected).then((pda) => rpc.getAccountInfo(pda, { encoding: "base64" }).send()), ]); if (colRes.status === "rejected") console.error("collection read failed:", colRes.reason?.message ?? colRes.reason); if (itemRes.status === "rejected") throw itemRes.reason; const [mintAcc, metaAcc] = itemRes.value.value; const meta = mintAcc && metaAcc?.owner === TOKEN_METADATA ? parseMetadata(metaAcc.data[0]) : null; const colAcc = colRes.status === "fulfilled" ? colRes.value.value : null; const authority = colAcc?.owner === TOKEN_METADATA ? parseMetadata(colAcc.data[0])?.authority : undefined; const c = meta?.collection; const result = !c ? "none" : c.key !== expected ? "other collection" : c.verified && authority ? "member" : "claims unverified"; for (const [k, v] of Object.entries({ item, expected, collection: c?.key ?? "none", verified: c?.verified ?? false, authority: authority ?? "collection metadata not found", result })) console.log(k.padEnd(11), v);}const [a, b] = process.argv.slice(2);const pair = a && b ? Promise.resolve([address(a), address(b)]) : findItem();pair.then(([item, expected]) => check(item, expected)).catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1);});
run: CARBIUM_KEY=<YOUR_KEY> node main.ts
With no arguments it finds its own sample. It lists the newest signatures of the Token Metadata program, fetches up to 12 of those transactions with maxSupportedTransactionVersion: 1, and collects the mints whose token balances have 0 decimals. One getMultipleAccounts call reads their metadata accounts, and the first that names a collection supplies both the item and the expected key. The run prints member for a live NFT, and every rejected transaction call is printed and skipped.
A getTransaction call costs 50 cells, and a Free key may make 0.24 of them a second, so on Free some of the 12 can come back as 429 while the rest still feed the sample.
Using it in a mint gate
A wallet connects, and the server lists its token accounts with getTokenAccountsByOwner. Each mint with an amount of 1 and 0 decimals goes through the check against the collection key from your config, and the first member opens the gate. The check proves the mint belongs to the collection. The token account proves the wallet holds it, and NFT membership gate covers that half end to end.
The collection read is the same for every item, so cache its authority for a few minutes and spend one account read per item after that. For a wallet with many NFTs, or a reward list with thousands of mints, put the item metadata addresses into getMultipleAccounts and run the same parser over each result. A call carries at most 100 pubkeys below Pro, and Pro takes up to 300. Bulk NFT metadata reader shows the batching on its own.
An account read costs 10 cells, and getMultipleAccounts charges 10 per pubkey, the same as one getAccountInfo per item. A batch saves round trips and leaves the cell charge unchanged, and caching the collection read is what lowers it. Limits are per account: Free runs account reads at 0.5 req/s, Dev at 15, Business at 50 and Pro at 400, and every key on the account shares that budget. A gate on Free that spends account reads on every item at that rate can reach a 429 quickly.
Where it ends
- The check names the update authority. A delegated collection authority can also set the flag, and its approval lives in a separate record that the code does not read. To see who signed a verification, read the verify transaction through getSignaturesForAddress on the item's metadata address, which reaches back 30 days.
- A flag set by a former authority stays set after the collection changes hands. The check shows today's authority and cannot show who held it when the item was verified.
- It proves nothing about the holder. Pair it with a token account read to learn who owns the NFT, and with getTokenSupply to confirm the mint has a supply of 1 and 0 decimals.
- A mint whose name and image live inside the mint under Token-2022 has no Token Metadata account at the derived address and reads as none.
- Sample mode looks at the newest transactions only. Signature pages reach below the validator's ledger floor, so getTransaction can answer null for an older signature; the code skips nulls and the sample still comes from recent ones.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The result is none for an NFT you know is in a collection. | Check that the first argument is the NFT's mint address and not its token account or a wallet. The metadata account is derived from the mint, so any other address derives an account that does not exist. |
| The result is claims unverified for a collection you trust. | Check that the expected key is the collection mint and not a candy machine address or the collection's token account. If the printed collection matches and the flag is false, the authority never ran verification for that item. |
| getTransaction answers -32015 in sample mode or in your own code. | Pass maxSupportedTransactionVersion: 1 with an encoding. Absent or 0, a v1 transaction or a block holding one answers -32015. |
| Calls answer 429. | Cache the collection read, space item reads to your plan's account-read rate, and retry after the retry-after hint on the 429. Batching item reads into getMultipleAccounts saves round trips and still charges 10 cells per pubkey. |
| Sample mode ends with an error that no 0-decimal mint has a collection. | Run it again so it reads newer transactions, or pass two addresses. The sample keeps what it finds in 12 transactions, and on Free some of those calls can come back as 429. |
Questions
Is the verified flag enough on its own?
No. The flag says some collection authority vouched for the item under the key it names. Compare that key to the one you expect first, because anyone can run their own authority and verify items into a lookalike collection.
Where does the expected collection key come from?
From the project that owns the collection, through a source you trust, saved in your gate's config. Never read it from the item you are checking, since a copied collection passes any test that borrows its key from the item.
How many NFTs can one call check?
One getMultipleAccounts call carries up to 100 metadata addresses below Pro and up to 300 on Pro. Parse each result with the same function and read the collection's metadata once.
Do I need the Metaplex library for this?
Not for this field. The walk to the collection option is a dozen lines of offsets. A client library helps when you need other fields further along the account, such as uses or programmable config.