---
id: UC0012
title: "NFT membership gate"
url: https://carbium.sh/library/usecase/nft-membership-gate
collection: Use cases
category: Loyalty, rewards and memberships
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# NFT membership gate

A server-side check that a visitor's wallet holds a member NFT: the exact token account to read, a signature that proves the visitor controls the wallet, what each check costs on Carbium, and how to keep access current after a transfer.

## What the gate checks

An NFT gate answers one question for a server: does this wallet hold this token right now. On Solana an NFT is an SPL token with 0 decimals and a supply of 1. A holder usually keeps it in the associated token account. For the original token program that account sits at a derived address built from three seeds: the owner wallet, the token program id and the mint. Your server computes the address itself, so a visitor never tells you where to look.

Read that one account and apply four rules.

- The account exists. A wallet that never held the mint has no associated token account, and the read returns null for it.
- The mint field equals the mint you gate on, and the owner field equals the wallet.
- The state is not uninitialized. A frozen account that holds the token still passes, because programmable NFTs keep their token account frozen by design. A gate that must refuse frozen holders compares the state with initialized instead.
- The amount is at least 1 and the decimals are 0. A fungible token with decimals above 0 is no pass, so a stray token with a balance of 1 cannot open the door.

A collection gate keeps your own list of member mints, taken from your mint run or a snapshot, and the visitor names the mint to use. You look the mint up in the list in memory, then read one account. When the visitor names no mint, `getTokenAccountsByOwner` with the token program id lists every token account the wallet holds under that program in one call, including accounts outside the associated address. Match the mints in that result against your list in memory.

## Prove the visitor controls the wallet

Holding is public. Anyone can paste the address of a wallet that holds a member NFT, so the address alone proves nothing. Make the visitor sign a message with that wallet. Issue a random nonce on your server, store it with a short expiry, put your domain and the nonce in the message text, and accept a given nonce once.

A wallet signs with ed25519 and the wallet address is the public key, so Node's `node:crypto` verifies the signature with no extra library: put the 32 address bytes behind the fixed ed25519 key header and call `verify`. The browser asks the wallet to sign message text. That sends no transaction, spends no fee and involves no RPC call, and a signed message cannot be replayed as a transfer.

## The gate in one file

The script runs on your server. It reads `CARBIUM_KEY`, takes a wallet and a comma-separated list of mints as arguments, and sends one `getMultipleAccounts` call with `jsonParsed` encoding to [`https://services.carbium.sh`](https://carbium.sh/docs#endpoints), with the key in the [`x-api-key` header](https://carbium.sh/docs#auth). Two optional environment variables carry the wallet proof: `MESSAGE`, the signed text, and `SIGNATURE`, its signature in base64. With no arguments it looks through the newest Token Metadata program transactions for a wallet that holds an NFT in its associated token account, so you can watch the read work on a live holder.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY MESSAGE=<nonce message> SIGNATURE=<base64 signature> node main.ts [<wallet> <mint>[,<mint>...]]`)

```ts
// UC0012 · NFT membership gate
// https://carbium.sh/library/usecase/nft-membership-gate
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only NFT membership gate: does a wallet hold a member NFT, and does the caller control that wallet?
import { createPublicKey, verify } from "node:crypto";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress, 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 [walletArg, mintsArg] = process.argv.slice(2);

const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({
  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
  headers: { "x-api-key": key },
}));

const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const METADATA_PROGRAM = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
const ED25519_SPKI = Buffer.from("302a300506032b6570032100", "hex"); // fixed header before a raw ed25519 key
const enc = getAddressEncoder();
const bytes = (a: Address) => Buffer.from(enc.encode(a));

type Token = { owner: string; mint: string; state: string; tokenAmount: { amount: string; decimals: number } };
type Bal = { accountIndex: number; mint: string; owner?: string; uiTokenAmount: { amount: string; decimals: number } };
type Tx = { meta?: { postTokenBalances?: Bal[] } | null; transaction: { message: { accountKeys: { pubkey: string }[] } } };

// The associated token account of (owner, mint): where a standard holder keeps the balance.
const ataOf = async (owner: Address, mint: Address) =>
  (await getProgramDerivedAddress({
    programAddress: ATA_PROGRAM,
    seeds: [bytes(owner), bytes(TOKEN_PROGRAM), bytes(mint)],
  }))[0];

// Demo input: scan the newest Token Metadata transactions for an NFT sitting in its owner's associated token account.
async function findHolder(): Promise<[string, string]> {
  const sigs = await rpc.getSignaturesForAddress(METADATA_PROGRAM, { limit: 40, commitment: "finalized" }).send();
  for (const s of sigs.filter((x) => !x.err)) {
    try {
      const res = await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send();
      const tx = res as unknown as Tx | null;
      for (const b of tx?.meta?.postTokenBalances ?? []) {
        if (!b.owner || b.uiTokenAmount.decimals !== 0 || b.uiTokenAmount.amount !== "1") continue;
        const ata = await ataOf(address(b.owner), address(b.mint));
        if (ata === tx?.transaction.message.accountKeys[b.accountIndex]?.pubkey) return [b.owner, b.mint];
      }
    } catch (e) { console.error(`skipped ${s.signature.slice(0, 8)}: ${(e as Error).message}`); }
  }
  throw new Error("no NFT holder found in the newest transactions");
}

// One getMultipleAccounts call (10 cells per pubkey), read at finalized.
async function holdings(wallet: Address, mints: Address[]) {
  const atas = await Promise.all(mints.map((m) => ataOf(wallet, m)));
  const { value } = await rpc.getMultipleAccounts(atas, { encoding: "jsonParsed", commitment: "finalized" }).send();
  return mints.map((mint, i) => {
    const t = (value[i]?.data as unknown as { parsed?: { info?: Token } } | undefined)?.parsed?.info;
    // A frozen account still holds the token: programmable NFTs keep theirs frozen by design.
    const ok = !!t && t.owner === wallet && t.mint === mint && t.state !== "uninitialized"
      && t.tokenAmount.decimals === 0 && BigInt(t.tokenAmount.amount) >= 1n;
    const seen = t ? `${t.tokenAmount.amount} (decimals ${t.tokenAmount.decimals}, ${t.state})` : "no token account";
    return { mint, ok, seen };
  });
}

// The wallet address is its ed25519 public key, so the message signature verifies locally.
function controls(wallet: Address, message: string, signatureB64: string) {
  const pub = createPublicKey({ key: Buffer.concat([ED25519_SPKI, bytes(wallet)]), format: "der", type: "spki" });
  return verify(null, Buffer.from(message), pub, Buffer.from(signatureB64, "base64"));
}

const [walletStr, mintsStr] = walletArg && mintsArg ? [walletArg, mintsArg] : await findHolder();
const wallet = address(walletStr);
const rows = await holdings(wallet, mintsStr.split(",").map((m) => address(m)));
for (const r of rows) console.log(`${r.ok ? "pass   " : "no pass"} ${r.mint}: ${r.seen}`);

const { MESSAGE, SIGNATURE } = process.env;
const proven = !!MESSAGE && !!SIGNATURE && controls(wallet, MESSAGE, SIGNATURE);
console.log(proven ? "wallet control: proven by signature" : "wallet control: not proven (set MESSAGE and SIGNATURE)");
console.log(proven && rows.some((r) => r.ok) ? "ACCESS GRANTED" : "ACCESS DENIED");
```

It prints one line per mint, then ACCESS GRANTED only when a mint passes and the signature verifies. With no signature it still prints the holdings and denies access, which lets you test the read before the wallet side exists. For a gate in front of paid content, wire the same two checks into your login route and keep the nonce handling there.

## What it costs on Carbium

getMultipleAccounts is an [account read](https://carbium.sh/docs#rpc): 10 cells per pubkey, up to 300 pubkeys in one call on Pro and up to 100 per call on the other plans, because of the 1024-cell burst. A one-mint check costs 10 cells and a three-mint check costs 30, and a higher plan raises the req/s at its [monthly price](https://carbium.sh/docs#limits).

| Plan | Price per month | Account reads, req/s |
|---|---|---|
| Free | $0 | 0.5 |
| Dev | $20 | 15 |
| Business | $250 | 50 |
| Pro | $500 | 400 |

Read only the mint the visitor names. Cache a pass for the length of the session, so a page load does not read the chain again. Send independent checks together: one POST carries a single call or a batch of up to 100.

Keep the key on your server. A key in a browser bundle is public, and every key on the account draws on one budget, so a leaked one spends the allowance of your gate.

## Keep access current after a transfer

An NFT can be sold or moved a minute after the check. Decide how stale a pass may be and re-read on that schedule.

- Check at the action. Read the token account when the member asks for the gated thing and keep nothing between requests. It is the simplest pattern, and the account-read cost lands on each action.
- Short sessions. Issue a session that lasts minutes and re-read at renewal. A transfer ends access at the next renewal.
- Watch the token account. Open an [`accountSubscribe`](https://carbium.sh/docs#websocket) on the member's token account and end the session when it changes. `accountSubscribe` sends account state only for streamed accounts, so try it on your own token accounts before you depend on it. A subscription for an account opens at 25 credits and then costs 20 credits per MiB sent. Free carries 5 sockets, and counts are capped per account by plan, so keep this for long sessions with few members online.

A pass granted from a finalized read does not roll back later, so the only staleness left is the time between your reads.

## Where it ends

- The script reads token accounts of the original token program at the associated address. A token under another token program uses that program's id in the address seeds and needs its own derivation.
- A wallet can own several token accounts for one mint, and only one of them is the associated token account. The script reads an NFT held in any other token account as not held. `getTokenAccountsByOwner` finds those accounts.
- Core-standard NFTs are single accounts with no token account, so this read does not see them. A gate for such a collection reads the asset account's owner field instead.
- The script checks the mints you name. To find who holds a mint you would reach for getTokenLargestAccounts or getProgramAccountsV2, and both are among eight methods Carbium does not serve; they answer [-32601](https://carbium.sh/docs#errors), so a retry gets the same answer.
- An NFT that sits in a marketplace escrow or a vault reads as not held by the member's wallet. Decide whether those members get in.
- To confirm that a mint belongs to your collection without a list of your own, read the Token Metadata account of the mint and check the verified flag on its collection field. The script reads token accounts only.
- Who held a pass in the past comes from getSignaturesForAddress on the token account. It lists the signatures that touched one wallet's token account, so it shows when that wallet held the pass, and you read each signature with getTransaction for the detail. It costs 50 cells per call, and its pages come from the address index, which keeps up to 30 days. An empty page past that is the index's age limit and does not mark the account's first transaction.
- The script verifies a signature. It issues no nonce and stores no session, and both belong to your server. The holder it picks when run with no arguments is a demo input and has no place in a gate.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A visitor pastes the address of a holder and gets in. | Require the signed message. Issue a fresh nonce for each attempt, expire it and accept it once. |
| A member sells the NFT and keeps access. | Set a pass lifetime and re-read at renewal or at the action. Watch the token account for long sessions. |
| A fungible token with a balance of 1 opens the gate. | Compare the mint with your list and require decimals 0, as the script does. |
| A member is refused because the token account of a programmable NFT is frozen. | Accept a frozen account that holds the token, as the script does: it requires the state not to be uninitialized. |
| Checks are refused during a busy period, such as a mint or a launch event. | Cache a pass for the session, check only the mint the visitor names, then compare your account-read rate with the next plan. |
| The key ships in the front-end bundle. | Move the call behind your own endpoint, create a new key on the [account page](https://carbium.sh/docs#account-api-keys) and delete the leaked key on the same page, because a new key alone leaves the leaked one working. |

## Questions

### Can I gate on any NFT from a collection?

Yes. Keep the collection's mint list, let the visitor name a mint from it and read that one token account. The script checks the mints you pass it and does not list the wallet's holdings.

### Does the wallet signature cost anything?

No. The wallet signs message text and your server verifies it locally with Node. Nothing is sent to the chain and no Carbium call is involved.

### How many mints can one call check?

getMultipleAccounts takes up to 300 pubkeys and charges 10 cells per pubkey. Only Pro reaches 300. Free, Dev and Business check at most 100 mints per call, because of the 1024-cell burst, and 100 mints cost 1000 cells, 1001 over a 4 KiB body.

### Do I need the WebSocket?

Only to end a session the moment a token account changes. The check itself is one HTTP call, and a subscription has its own credit cost. For the balance read alone, see [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance).

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#account-api-keys](https://carbium.sh/docs#account-api-keys)
