library / How to use Solana / HS0024
Transfer fee calculator
One TypeScript file reads a Token-2022 mint's transfer fee settings, picks the rate in force this epoch, and prints the fee and the amount the receiver gets for any transfer size. It only reads: no keypair, no signature.
How a transfer fee is set
A Token-2022 mint can carry a transferFeeConfig extension. Every transfer of that mint then withholds a cut of the amount, and the receiver is credited the amount minus the cut. The settings live on the mint, so the fee can be worked out from one account read before anything is sent.
The extension holds two fee records, olderTransferFee and newerTransferFee. Each record has three fields.
- epoch: the first epoch in which the record applies.
- transferFeeBasisPoints: the rate in hundredths of a percent, so 100 is 1% and 10000 is 100%.
- maximumFee: a ceiling in base units that the fee never passes, however large the transfer.
Two records exist because a rate change does not apply at once. When the fee authority sets a new rate, it takes effect two epochs later, which gives wallets that already built a transfer time to see it. Until the epoch named in the newer record arrives, the older record governs. From that epoch on, the newer one does. The file reads the current epoch and compares it with the newer record's epoch to choose.
The arithmetic is short. The fee is the amount times the basis points, divided by 10000 and rounded up to the next whole base unit. If that result is larger than maximumFee, the fee is maximumFee. A zero rate or a zero amount gives a zero fee. Because of the rounding up, a transfer of 1 base unit at 1 basis point still pays 1 base unit.
The code
Add @solana/kit 8.6.0 to the project, set CARBIUM_KEY in the environment and run the file on Node 24, which strips TypeScript types by itself. The first argument is a mint and the second is an amount in base units. With no arguments it uses BERN, a public Token-2022 mint with a nonzero transfer fee, and an amount of 1000000001, which does not divide evenly at BERN's rate, so the run shows the rounding at work.
// HS0024 · Transfer fee calculator// https://carbium.sh/library/howsolana/transfer-fee-calculator// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } 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 rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url, headers: { "x-api-key": key } }),);const BERN = "CKfatsPMUf8SkiURsDXs7eK6GWb4Jsd6UDbs7twMCWxo";const mint = address(process.argv[2] ?? BERN);const amountText = process.argv[3] ?? "1000000001";if (!/^\d+$/.test(amountText)) { console.error("The amount must be whole base units, digits only."); process.exit(1);}const amount = BigInt(amountText);type Fee = { epoch: number; maximumFee: number | string; transferFeeBasisPoints: number };type Ext = { extension: string; state: { newerTransferFee?: Fee; olderTransferFee?: Fee } };type Parsed = { parsed?: { type?: string; info?: { decimals?: number; extensions?: Ext[] } } };const show = (v: bigint, d: number) => { if (d === 0) return v.toString(); const s = v.toString().padStart(d + 1, "0"); return `${s.slice(0, -d)}.${s.slice(-d)}`;};const [acct, epochInfo] = await Promise.allSettled([ rpc.getAccountInfo(mint, { encoding: "jsonParsed", commitment: "confirmed" }).send(), rpc.getEpochInfo({ commitment: "confirmed" }).send(),]);if (acct.status === "rejected") console.error(`getAccountInfo failed: ${String(acct.reason)}`);if (epochInfo.status === "rejected") console.error(`getEpochInfo failed: ${String(epochInfo.reason)}`);if (acct.status === "rejected" || epochInfo.status === "rejected") process.exit(1);const account = acct.value.value;const parsed = (account?.data as unknown as Parsed | undefined)?.parsed;if (!account || parsed?.type !== "mint") { console.error(`${mint} is not a mint.`); process.exit(1);}const decimals = parsed.info?.decimals ?? 0;const epoch = epochInfo.value.epoch;console.log(`mint ${mint}, ${decimals} decimals, current epoch ${epoch}`);const config = parsed.info?.extensions?.find((x) => x.extension === "transferFeeConfig")?.state;const { newerTransferFee: newer, olderTransferFee: older } = config ?? {};if (!newer || !older) { console.log("the mint has no transferFeeConfig extension: the fee is 0"); process.exit(0);}const useNewer = epoch >= BigInt(newer.epoch);const rec = useNewer ? newer : older;const bps = BigInt(rec.transferFeeBasisPoints);const max = BigInt(String(rec.maximumFee));console.log( `fee in force: ${useNewer ? "newer" : "older"} record, ${bps} bps, maximumFee ${max}` + (useNewer ? "" : `, newer record starts at epoch ${newer.epoch} with ${newer.transferFeeBasisPoints} bps`),);let fee = amount === 0n || bps === 0n ? 0n : (amount * bps + 9999n) / 10000n;if (fee > max) { fee = max; console.log("fee capped at maximumFee");}console.log(`send ${amount} (${show(amount, decimals)}): fee ${fee} (${show(fee, decimals)})`);console.log(`receiver is credited ${amount - fee} (${show(amount - fee, decimals)})`);
run: node main.ts [mint-address] [amount-in-base-units]
The mint is read with jsonParsed encoding, so the node decodes the extension into named fields and the file never touches the byte layout. The two reads run together with Promise.allSettled: one failing prints its own line and the file stops with a clear message instead of a stack trace. Both reads run at confirmed commitment.
The amount is checked before any request goes out. Only digits are accepted, since a decimal point would mean the caller is thinking in whole tokens and the file works in base units.
Reading the output
Each run prints a header line with the mint, its decimals and the current epoch, then one line for the fee in force, then the result.
| What prints | What it means | Fee |
|---|---|---|
| the mint has no transferFeeConfig extension: the fee is 0 | The mint takes nothing on transfer, or it belongs to the classic Token program | 0 |
| fee in force: newer record, 0 bps, maximumFee 0 | The newer record already applies and its rate is zero | 0 |
| fee in force: older record, X bps, maximumFee M, newer record starts at epoch N with B bps | A rate change is queued and has not started yet | From the older rate |
| fee in force: newer record, X bps, maximumFee M | The newer record applies, either from creation or after a queued change started, and X is above 0 | Rate times amount, rounded up |
| fee capped at maximumFee | The computed cut passed the ceiling | maximumFee |
A mint can carry the extension with a rate of 0, and that is a valid answer. PYUSD is one: it shows a newer record at 0 bps. A zero rate leaves room for a fee later only while the extension's transferFeeConfigAuthority is set. With no authority the rate can never change. When an authority exists it can queue a higher rate, and the file will show it as a newer record with a start epoch in the future while the older one still governs.
The last two lines show the amount sent, the fee and the amount the receiver is credited, all in base units and again scaled by the mint's decimals.
On Carbium
Requests go to https://services.carbium.sh.
getAccountInfo is an account read, priced at 10 cells, and account reads are allowed 0.5 per second on Free, 15 on Dev, 50 on Business and 400 on Pro. One run makes one account read plus one getEpochInfo. A rate class absorbs bursts of at least 1,024 cells, so the account read passes at once on every plan.
To price many mints in one pass, send them through getMultipleAccounts, which charges 10 cells per pubkey. Below Pro the burst caps a call at 100 pubkeys, and 300 per call is Pro's. Read the epoch once for the whole batch, since every mint in it faces the same current epoch.
Where it ends
The number the file prints is a quote, and the chain computes its own at send time. A transfer built with transferCheckedWithFee carries the fee the sender expects, and the program rejects it when that figure differs from its own result. A rate change that starts in the epoch after your read, or a read made just before an epoch boundary, can leave you with a stale figure. Read again right before you build the instruction.
Fees are withheld in the receiving token accounts. They sit there until the withdraw authority collects them, either straight from the token accounts or from the mint once someone has harvested them there. The file does not read the withheld amount. A withheldAmount field exists on the mint's extension and holds the harvested total, and the token accounts hold the rest.
The file goes from the amount sent to the amount received. The reverse question, how much to send so the receiver is credited an exact figure, can always be answered. With bps of 10000 or less the fee grows by 0 or 1 for each extra base unit sent, so every net amount can be reached, and several gross amounts can share one net. Token-2022 inverts the rule as gross = ceil(net * 10000 / (10000 - bps)), which is the smallest gross that works, and uses net + maximumFee once the cap applies. Check the result with the forward formula: the fee on that gross, taken off the gross, must give back the net you wanted.
Only the fee extension is read. A mint can also carry a transfer hook, a pause or other extensions that change what a transfer does or whether it succeeds, and none of that appears in this output. The Token-2022 metadata lookup shows how to list a mint's extensions, and the RWA supply and authority monitor covers watching the authorities on a mint.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The file says the address is not a mint. | You passed a wallet or a token account, or an address with no account on chain. Take the mint from the token account's mint field, which getAccountInfo with jsonParsed returns, check the address for a typo, and run the file on that. |
| The output says the mint has no transferFeeConfig extension. | That mint takes no fee on transfer. A mint of the classic Token program never has the extension, and a Token-2022 mint only has it when its issuer added it at creation. |
| The computed fee differs from the fee the transfer instruction demands. | The rate changed between your read and the send, or an epoch boundary passed. Read the mint and the epoch again, recompute, and pass the new figure to the instruction. |
| The amount is refused before any request goes out. | Pass whole base units as digits only. For 2.5 tokens of a 6-decimal mint, pass 2500000. |
| The output starts with getAccountInfo failed or getEpochInfo failed. | The text after the colon names the cause. For a connection error, check CARBIUM_RPC_URL and the network, then run again. |
Questions
Who pays the transfer fee, the sender or the receiver?
The receiver is credited the amount minus the fee, so the fee comes out of what arrives. The sender's balance drops by the full amount. A sender who wants the receiver to get an exact figure sends more.
Why does the mint hold two fee records?
A rate change takes effect two epochs after the authority sets it. The older record keeps governing until the newer record's epoch arrives, so wallets always see a rate before it applies.
Can the fee ever be larger than maximumFee?
No. The program cuts the computed fee to maximumFee, so large transfers pay a flat ceiling once the rate times the amount passes it.
Do I need a private key to run this?
No. The file reads one mint and the epoch. The Carbium key only identifies your account to the RPC, and nothing is signed or sent.