Creator royalty income tracker
Read an NFT's seller fee and creator split, find the secondary sales that paid the creators, and keep a running tally in SQLite, with the limits of what the chain can prove about royalties.
How a royalty is recorded
A royalty on Solana is two numbers in the NFT's metadata account and a payment that a marketplace program makes when the NFT sells. The metadata account, owned by the Token Metadata program, stores a seller fee in basis points and a list of creators. Each creator has an address, a verified flag and a share, and the shares add up to 100. A fee of 500 basis points with two creators at 70 and 30 means 5% of the sale price, split 3.5% and 1.5%.
Setting royalties up for an artist happens when the NFT is minted or updated. A Token Metadata CreateV1 (or CreateMetadataAccountV3 on older tooling) writes the creators list with each share and the seller fee. The artist then signs SignMetadata to set the verified flag, and the update authority can change both fields later with UpdateV1 while the metadata is mutable. Nothing in those steps moves money. The seller fee is a declaration, and the marketplace program that settles a secondary sale decides whether it pays the fee and at what rate.
That makes income tracking a read job. A sale is one transaction. When the marketplace pays royalties, each creator address shows a lamport increase in that same transaction, and the metadata names who to look for. The script below matches the two and writes each payment to a local table, so an artist or a studio can see what arrived, from which sale, and what the metadata said it should be.
The reads and their cost
The script makes three kinds of call. getSignaturesForAddress lists the newest transactions of an address, which is a marketplace program or an artist's wallet. getTransaction reads each one with jsonParsed encoding, which returns the token balances after the transaction, the account keys with a signer flag, the log messages and the lamport balances before and after. A token balance of 1 at 0 decimals identifies an NFT-shaped mint. getAccountInfo then reads that mint's metadata account once, and the script keeps the result for the rest of the run.
| Call | Cells | In one script run |
|---|---|---|
| getSignaturesForAddress | 50 | one per address |
| getTransaction | 50 | up to 10 per address |
| getAccountInfo | 10 | one per distinct mint |
Each call is charged in cells at admission, and each class has its own rate on every plan. A class absorbs a burst up to 1,024 cells, or one second of its rate when that is larger. Following one address spends at most 550 cells (50 for the list, 500 for ten transactions) plus 10 for every distinct mint whose seller fee and creators get read. Two marketplace programs read in full come to 1,000 cells of getTransaction, so the default pass fits inside the burst, and it usually stops sooner. If you plan to read every royalty sale of a busy collection, check the signature and transaction rates for your plan first, since they vary widely.
Version 1 transactions also exist on mainnet. For one of them getTransaction answers -32015 and charges nothing unless maxSupportedTransactionVersion is 1, and the script sends 1.
A script in one file
Run it with no argument to scan two public marketplace programs, Magic Eden v2 and Tensor swap, or pass any addresses: a marketplace program, or an artist's wallet to follow that creator. For each address it reads the newest 10 signatures and keeps the successful ones, then reads those transactions one at a time and stops after the first whose log messages show a sale instruction. For every NFT-shaped mint in a transaction it reads the metadata, then checks each creator with a non-zero share. A creator whose account gained lamports in the transaction and did not sign it gets a row in royalties.db, and the run ends with the five largest totals. The key comes from CARBIUM_KEY, and the script exits with a message when it is unset. It signs and sends nothing.
// UC0048 · Creator royalty income tracker// https://carbium.sh/library/usecase/creator-royalty-income-tracker// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: tallies what an NFT's listed creators received in the newest sales of a program or an artist's wallet.import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const targets = process.argv.length > 2 ? process.argv.slice(2) : [ "M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K", "TSWAPaqyCSx2KABk68Shruf4rp7CxcNi8hAsbdwmHbN"];const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const METADATA = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const enc = getAddressEncoder(), dec = getAddressDecoder();const db = new DatabaseSync("royalties.db");db.exec("CREATE TABLE IF NOT EXISTS royalties (signature TEXT, creator TEXT, mint TEXT, lamports INTEGER, PRIMARY KEY (signature, creator))");const insert = db.prepare("INSERT OR IGNORE INTO royalties VALUES (?, ?, ?, ?)");type Creator = { address: string; verified: boolean; share: number };type Meta = { feeBps: number; creators: Creator[] };type Tx = { transaction: { message: { accountKeys: { pubkey: string; signer: boolean }[] } }; meta: { preBalances: readonly (bigint | number)[]; postBalances: readonly (bigint | number)[]; logMessages?: string[]; postTokenBalances?: { mint: string; uiTokenAmount: { amount: string; decimals: number } }[] } | null;};// Token Metadata layout: key, update authority, mint, three length-prefixed strings, seller fee, then the creators.function parseMetadata(b: Buffer): Meta { let p = 65; for (let i = 0; i < 3; i++) p += 4 + b.readUInt32LE(p); const feeBps = b.readUInt16LE(p); p += 2; const creators: Creator[] = []; if (b[p++] === 1) { const n = b.readUInt32LE(p); p += 4; for (let i = 0; i < n; i++, p += 34) creators.push({ address: dec.decode(b.subarray(p, p + 32)), verified: b[p + 32] === 1, share: b[p + 33] }); } return { feeBps, creators };}const cache = new Map<string, Meta | null>();async function metadataOf(mint: string): Promise<Meta | null> { if (cache.has(mint)) return cache.get(mint) ?? null; const [pda] = await getProgramDerivedAddress({ programAddress: METADATA, seeds: ["metadata", enc.encode(METADATA), enc.encode(address(mint))] }); const acc = await rpc.getAccountInfo(pda, { commitment: "confirmed", encoding: "base64" }).send(); const meta = acc.value ? parseMetadata(Buffer.from(acc.value.data[0], "base64")) : null; cache.set(mint, meta); return meta;}const SALE = /Instruction: \w*(Sale|BuyNft|BuySingle|TakeBid)/;async function scan(target: string) { const sigs = await rpc.getSignaturesForAddress(address(target), { limit: 10, commitment: "confirmed" }).send(); let read = 0, mints = 0, paid = 0; for (const s of sigs.filter((s) => s.err === null)) { let tx: Tx | null; try { tx = (await rpc.getTransaction(s.signature, { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Tx | null; } catch (e) { console.error(" getTransaction failed:", String(e)); continue; } if (!tx?.meta) continue; read++; const keys = tx.transaction.message.accountKeys; for (const b of tx.meta.postTokenBalances ?? []) { if (b.uiTokenAmount.decimals !== 0 || b.uiTokenAmount.amount !== "1") continue; mints++; try { const meta = await metadataOf(b.mint); for (const c of meta?.creators ?? []) { const i = keys.findIndex((k) => k.pubkey === c.address); if (c.share === 0 || i < 0 || keys[i].signer) continue; const gained = Number(tx.meta.postBalances[i]) - Number(tx.meta.preBalances[i]); if (gained <= 0) continue; if (!Number(insert.run(s.signature, c.address, b.mint, gained).changes)) continue; paid++; console.log(` ${s.signature.slice(0, 12)} ${c.address} +${gained} lamports (fee ${meta?.feeBps} bps, share ${c.share}, verified ${c.verified})`); } } catch (e) { console.error(` ${b.mint} failed:`, String(e)); } } if (tx.meta.logMessages?.some((l) => SALE.test(l))) break; } console.log(`${target}: ${read} transactions read, ${mints} NFT-shaped mints, ${paid} creator payments`);}for (const t of targets) { try { await scan(t); } catch (e) { console.error(`${t} failed:`, String(e)); }}const top = db.prepare("SELECT creator, COUNT(*) AS sales, SUM(lamports) AS lamports FROM royalties GROUP BY creator ORDER BY lamports DESC LIMIT 5").all() as unknown as { creator: string; sales: number; lamports: number }[];console.log(top.length ? "largest totals:" : "no creator payments recorded yet");for (const t of top) console.log(` ${t.creator} ${t.sales} sales ${t.lamports} lamports`);
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts [address ...]
The metadata parser skips the name, symbol and URI by their length prefixes, reads the seller fee, then reads 34 bytes per creator: a 32-byte address, the verified flag and the share. The table has one row per signature and creator, so a rerun over the same transactions adds nothing and prints no payment line for them, and a bundle of several NFTs in one transaction counts a creator once, against the first mint. Each call settles on its own, so one failed read prints a line and the run goes on. Bulk NFT metadata reader covers reading the metadata of many known mints at once.
Reading the tally
- Lamports: the creator's balance after the sale transaction minus its balance before. A creator that is also the fee payer or a signer is skipped, because that balance moves for other reasons.
- Fee and share: printed beside every payment. Once you have the sale price from the marketplace's own data, multiply it by fee and share. A payment well under that figure means the seller or the marketplace paid less than the metadata declares.
- Unverified creators: the list can name an address that never signed. The script still reads its balance, so check the verified flag before calling the line that artist's income.
- Totals: the sum misses every sale the script did not see, such as one outside the window or one settled in a token, and it can include lamports that are not royalties.
Following one artist over time
Pass an artist's wallet as the argument and the run becomes a per-artist feed. Any sale that paid that wallet appears in its recent signatures, and the creator check finds the match. Schedule the run against the same royalties.db and each pass adds only the new sales. The script stops at the first sale it finds, so delete the break line to record every sale among the ten signatures.
Each pass reads only the newest signatures, so an artist with more than ten transactions between runs loses the older ones. Run it often enough to stay under that count, or page getSignaturesForAddress with before and until back to the newest signature already stored in royalties.db.
To be pushed a notification, open a `logsSubscribe` with a mentions filter on the artist's wallet. A plain SOL wallet gets nothing from accountSubscribe, so the logs subscription plus a read of the transaction is the route. Opening a mentions subscription costs 25 credits, then 20 credits per MiB sent, and each plan caps sockets per account, with 5 on Free. When a notification arrives, fetch the transaction by signature and run the script's check on it. If your server would rather take an HTTP call than hold a socket, Address transaction webhooks covers that path.
Where it ends
- Owed against paid: the chain shows what each creator received. A fee the marketplace skipped leaves no trace, and the sale price sits in that program's own account layout. Anchor instruction decoder shows the method for programs built with Anchor.
- Currency: only lamport increases are counted. A creator share paid in a token shows up in token balances, which the script never compares.
- Programmable NFTs: the script reads one like any other NFT, since it never checks the token standard. Its rule set limits which programs can move it, so only a marketplace that satisfies those rules can settle its sale.
- Edits: the fee and creators come from the metadata as it stands at read time. If the update authority changed either after a sale, the printed fee describes the new state.
- History: the signature list covers 30 days at most. A signature older than the validator's ledger floor can list and still return null from getTransaction, and the script skips null. An empty page past 30 days is the index's age limit, and the address may have older sales.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| getTransaction answers -32015 on a recent sale. | That sale is a version 1 transaction and the request had no maxSupportedTransactionVersion. Send 1 together with an encoding. |
| getTransaction returns null for a signature that getSignaturesForAddress just listed. | The address index reaches below the validator's ledger floor, so an older sale can list with no transaction behind it. Skip the null and try the code on the newest signatures. |
| The run ends with no creator payments. | Most traffic at a marketplace program is listings, bids and cancels. Pass an artist's wallet, raise the signature limit, or run again later. A collection with a seller fee of 0 pays its creators nothing by design. |
| A recorded payment exceeds seller fee times creator share. | The creator got other lamports in that transaction, such as a refund or a second sale. Read the row as an upper bound and compare it with the sale price from the marketplace's data. |
| The metadata read returns no account for an NFT. | Check the seed order: the word metadata, the Token Metadata program id, then the mint. A Token-2022 mint can hold its metadata in the mint when its metadataPointer extension names the mint, and then no Token Metadata account exists. |
Questions
How do I set up royalties for an artist?
List the artist's wallet among the metadata creators with a share, set the seller fee in basis points, and have the artist sign to verify the entry. That records the intent. Each secondary sale pays it only if the marketplace program settling that sale chooses to.
Does the artist have to claim royalties?
Usually the marketplace sends creator shares as direct transfers inside the sale transaction, so the lamports are in the creator's account once the sale lands. The script reads that transfer, and no claim step exists to read.
Can the royalty change after mint?
Yes, while the metadata is mutable the update authority can change the seller fee and the creators list. The script reads the metadata as it is now, so judge older sales against the fee that applied at the time.
How do I get the sale price to check a royalty?
Read it from the marketplace program's instruction data or sale account, whose layout is specific to each program. The seller's lamport gain in the same transaction gives a rough figure, since the fee and royalties come out of the price.