services
Get a key

library / Integrations / I0009

NFT holder Discord roles

A small Node watcher keeps a SQLite list of Discord users and their NFT token accounts, reads those accounts from Carbium in small batches, and removes the Discord role from anyone whose NFT has left the wallet.

By Carbium · Chat and notifications · I0009 · updated 2026-11-22

01

What the watcher does

The watcher is one Node process with one dependency, @solana/kit, and a SQLite file from node:sqlite. The file holds one row per link: a Discord user id, the wallet that user proved they control, the NFT mint, and the token account that should hold it. Your own linking flow writes those rows. The watcher reads them, asks Carbium for the current state of each token account, and removes the role from every Discord user who no longer holds any of their linked NFTs.

  1. Read every row from the links table.
  2. Fetch the token accounts in batches of 10 with getMultipleAccounts at finalized.
  3. Mark a link as held when the account exists, belongs to the linked wallet and carries an amount above zero.
  4. For each Discord user with no held link and no failed batch read, send one role removal to Discord. After Discord answers 204, delete that user's rows.

A scan reads current state and keeps no event history. A stopped watcher needs no replay: its first scan after a restart finds every sale. A user who holds two linked NFTs keeps the role until both have gone.

02

The Solana side: one token account per NFT

Carbium's RPC endpoint is https://services.carbium.sh. The code builds one client at start with your key attached and reuses it for every call.

An NFT is a token with a supply of one, and who holds it is written in a token account. In the account data, bytes 32 to 64 are the owner and bytes 64 to 72 the amount as a little endian u64. When you add a link, the watcher derives the associated token account for that wallet and mint with getProgramDerivedAddress and stores its address. When the NFT is sold or transferred, the seller's account drops to an amount of 0, or the account is closed and getMultipleAccounts returns null for it. The watcher treats both as no longer held.

Every read asks for finalized, so a role is never taken away for a transfer that could still be undone. That level adds about one slot of delay.

03

The Discord side: one DELETE per lost holder

In the Discord developer portal, create an application and add it to your server with the Manage Roles permission. In the server's role list, drag the application's own role above the holder role. Discord refuses a role change on any role at or above the application's highest role.

The removal is DELETE https://discord.com/api/v10/guilds/<guild>/members/<user>/roles/<role> with an x-audit-log-reason header, so the server's audit log says why the role went. Discord answers 204 when it is done. Set DISCORD_AUTH to the full Authorization header value for your application's token: the prefix Discord's authentication page shows, a space, then the token. Treat it as a secret, since it can change roles in your server.

A user's rows are deleted only after the 204. Any other answer, a 429 included, and any request that times out, is logged and the user is tried again in the next scan. After a mass sell-off Discord rate-limits the run of DELETEs, and the code does not pause between them, so removals can stretch over several scans. With DISCORD_AUTH unset the watcher prints the request it would send and changes nothing, which is the way to check a first run.

04

The watcher

Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required and the file exits with a message without it. DISCORD_AUTH turns on live removal, and DISCORD_GUILD_ID and DISCORD_ROLE_ID must be set with it, or the requests go to the placeholder ids GUILD_ID and ROLE_ID. POLL_SECONDS (default 60), CALLS_PER_SECOND (default 1), DB_PATH (default holders.db) and CARBIUM_RPC_URL are optional.

main.ts
// I0009 · NFT holder Discord roles// https://carbium.sh/library/integrate/nft-holder-discord-roles// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder,  getAddressEncoder, getProgramDerivedAddress } from "@solana/kit";import { DatabaseSync } from "node:sqlite";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }const discordAuth = process.env.DISCORD_AUTH; // full Authorization header value; unset means dry runconst guildId = process.env.DISCORD_GUILD_ID ?? "GUILD_ID";const roleId = process.env.DISCORD_ROLE_ID ?? "ROLE_ID";const sleepMs = Number(process.env.POLL_SECONDS ?? 60) * 1000;const pauseMs = 1000 / Number(process.env.CALLS_PER_SECOND ?? 1);const BATCH = 10; // pubkeys per call, 10 cells eachconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));// One client for the life of the process.const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key },}));const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");const enc = getAddressEncoder();const dec = getAddressDecoder();const db = new DatabaseSync(process.env.DB_PATH ?? "holders.db");db.exec("CREATE TABLE IF NOT EXISTS links (discord_id TEXT, wallet TEXT, mint TEXT, ata TEXT, PRIMARY KEY (discord_id, ata))");// node main.ts <discord user id> <wallet> <mint> adds a link, then watches.const [userId, wallet, mint] = process.argv.slice(2);if (userId && wallet && mint) {  const [ata] = await getProgramDerivedAddress({    programAddress: ATA_PROGRAM,    seeds: [enc.encode(address(wallet)), enc.encode(TOKEN_PROGRAM), enc.encode(address(mint))],  });  db.prepare("INSERT OR REPLACE INTO links VALUES (?, ?, ?, ?)").run(userId, wallet, mint, ata);  console.log(`linked ${userId} to ${ata}`);}type Link = { discord_id: string; wallet: string; ata: string };// The token accounts that still hold at least one token for their linked wallet.async function heldAccounts(links: Link[], unsure: Set<string>): Promise<Set<string>> {  const held = new Set<string>();  for (let i = 0; i < links.length; i += BATCH) {    const batch = links.slice(i, i + BATCH);    try {      const { value } = await rpc        .getMultipleAccounts(batch.map((l) => address(l.ata)), { encoding: "base64", commitment: "finalized" })        .send({ abortSignal: AbortSignal.timeout(10_000) });      value.forEach((acct, j) => {        const link = batch[j];        if (!acct || !link) return; // null: the account is closed        const bytes = Buffer.from(acct.data[0], "base64");        const owner = bytes.length >= 72 ? dec.decode(bytes.subarray(32, 64)) : ""; // a short account reads as lost        if (owner === link.wallet && bytes.readBigUInt64LE(64) > BigInt(0)) held.add(link.ata);      });    } catch (e) {      console.error(`batch at ${i} failed: ${msg(e)}`);      batch.forEach((l) => unsure.add(l.discord_id)); // an unread batch must not cost anyone a role    }    await sleep(pauseMs);  }  return held;}async function removeRole(user: string): Promise<boolean> {  const url = `https://discord.com/api/v10/guilds/${guildId}/members/${user}/roles/${roleId}`;  if (!discordAuth) { console.log(`dry run: DELETE ${url}`); return false; }  try {    const res = await fetch(url, { method: "DELETE", signal: AbortSignal.timeout(10_000),      headers: { authorization: discordAuth, "x-audit-log-reason": "NFT no longer held" } });    if (res.status !== 204) console.error(`Discord answered ${res.status} for ${user}`);    return res.status === 204;  } catch (e) {    console.error(`Discord request for ${user} failed: ${msg(e)}`);    return false;  }}async function scan() {  const links = db.prepare("SELECT discord_id, wallet, ata FROM links").all() as Link[];  const unsure = new Set<string>(); // users with a failed batch keep the role this scan  const held = await heldAccounts(links, unsure);  const holders = new Set(links.filter((l) => held.has(l.ata)).map((l) => l.discord_id));  console.log(`${new Date().toISOString()} checked ${links.length} links, ${held.size} still held`);  for (const id of new Set(links.map((l) => l.discord_id))) {    if (holders.has(id) || unsure.has(id) || !(await removeRole(id))) continue;    db.prepare("DELETE FROM links WHERE discord_id = ?").run(id); // only after Discord said 204    console.log(`removed role from ${id}`);  }}for (;;) {  await scan().catch((e: unknown) => console.error("poll failed:", msg(e)));  await sleep(sleepMs);}

run: node main.ts

05

Run it

Run node main.ts <discord user id> <wallet> <mint> once per holder to add a link. With three arguments the file adds the link and then starts watching in the same run. Day to day, start plain node main.ts under a supervisor such as a systemd unit. Add a link before you grant the role. The next scan then reads the account, so a user who linked a mint they do not hold loses the role at once.

To test removal without a real sale, link a wallet to a mint it does not hold, set the three Discord variables for a test server and role, and read the log for removed role from <id>.

A scan of N links is N divided by 10 calls, at one call a second by default, so 600 links take about 60 seconds to scan. On Free, CALLS_PER_SECOND=0.05 spaces the calls 20 seconds apart, so the same 600 links are 60 calls and take about 20 minutes. Removal within minutes at that size needs Dev or higher. Removals run after the whole scan has been read. The worst case for a role is up to two scans plus one sleep: a transfer that finalizes just after its batch was read waits out the rest of that scan, the sleep, and the next full scan before removals run. With 600 links at the defaults that is about 180 seconds. Lower POLL_SECONDS to shorten the sleep.

06

What it costs against your limits

getMultipleAccounts charges 10 cells per pubkey, and account reads are rated at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. Each link costs 10 cells per scan, and each default call of 10 pubkeys costs 100 cells. At 0.5 req/s for a 10-cell call, Free refills about 5 cells a second, so a 100-cell call fits only once every 20 seconds. On Free, set CALLS_PER_SECOND=0.05.

A class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger, so the first ten calls or so at the default rate pass before the 429s start.

Limits are per account, so all your keys share one budget. A call over its rate gets a 429 with a retry-after hint. A 429 fails only that call. The watcher logs the batch, spares its users from removal for that scan and goes on to the next batch, so the rest of the scan still reads and removes. The spared users are read again in the next scan. If it happens often, lower CALLS_PER_SECOND.

07

Where it ends

  • It removes roles and does nothing else. Granting the role, proving that a Discord user controls a wallet with a signed message, and writing the link rows belong to your linking flow.
  • It does not find the mints of a collection. You pass the mint for each link.
  • It reads the associated token account of the wallet under the classic token program. An NFT held in another kind of token account, or under the token-2022 program, reads as lost.
  • A move between two wallets of the same person removes the role until they link the new wallet. An NFT moved into a marketplace escrow does the same. A listing that leaves the NFT in the owner's account keeps the role.
  • A sale followed by a buy-back between two scans goes unseen, which is the right result: the user holds the NFT again.
  • A Discord user who left the server keeps getting a logged 404 each scan until you delete their rows by hand.
  • Run one watcher per database file.
08

When it goes wrong

what goes wrongwhat to do
Every user loses the role on the first scan and the log reads checked 40 links, 0 still held.The links point at accounts that do not hold the NFT. Check that the mint is the NFT's own mint and not a collection address, that the wallet is the holder, and that the stored ata is the account that holds it. An NFT in a non-associated account reads as lost.
The log shows batch at 0 failed with an HTTP error 401 on every scan.Carbium answers 401 for an unknown key, so attach the whole key. Check that CARBIUM_KEY holds the entire key and that nothing else sets CARBIUM_RPC_URL. No role is removed while every batch fails.
The log shows batch at 40 failed with an HTTP error 429 and some links go unchecked.The account's budget is spent, often by app traffic on other keys. Lower CALLS_PER_SECOND, or move to a plan with a higher rate. Users in a failed batch keep the role and are read again next scan.
The log shows Discord answered 403 and the role stays.The application lacks Manage Roles, or its highest role sits below the holder role. Move the application's role above the holder role in the server settings.
The log shows Discord answered 404 for one user, or for all of them.For all users, DISCORD_GUILD_ID or DISCORD_ROLE_ID is wrong. For one user, they left the server: delete their rows with DELETE FROM links WHERE discord_id = '<id>'.
A user still holds the NFT and lost the role.The NFT sits in an account other than the associated token account of the linked wallet, or under token-2022. The scan sees an empty associated account. Link the wallet that holds it in an associated account.
09

Questions

Why poll and not subscribe to each token account?

Each subscription costs 5, 25 or 200 credits to open by filter weight and then 20 credits per MiB sent. Counts are capped per account by tier, and Free carries 5 sockets. One scan of batch reads covers hundreds of links with no sockets to keep alive.

Why finalized and not confirmed?

A removal based on finalized can never be undone by a later slot.

Could it find a sale from the address history?

It could read getSignaturesForAddress on the token account, at 50 cells a call. Carbium serves that from its own address index, which keeps up to 30 days. Current state needs no history and catches sales from any age.