services
Get a key

library / Use cases / UC0023

USD-pegged checkout pricing

Charge a fixed USD fee in an Anchor checkout by pricing it in a stablecoin's base units, keep the amount in a config account, and verify the payment from the server. A short script converts dollars to base units from the mint's decimals.

By Carbium · Payments and checkout · UC0023 · updated 2026-11-22

01

Pick the unit the fee is written in

A program cannot hold a dollar. Its balances are integers in the base units of a mint, so a fixed USD fee ends up as one of two things: a fixed number of base units of a USD stablecoin, or a SOL amount recomputed from a price at each checkout. The first is fixed by construction. The second moves with the market and is exact to the cent only at the moment it is quoted.

For a checkout with a flat fee, take the first. A fee of 2.50 USD in a mint with 6 decimals is 2,500,000 base units, and it stays that amount whatever SOL does. Amounts in code stay integers, so the conversion is a multiplication on integers and no float touches the price.

The mint's decimals decide the multiplier, and mints differ. Read them from the chain so the same fee works for every stablecoin you accept.

02

Keep the fee in a config account

In Anchor, hold the fee in an account the program owns, so repricing is a transaction and needs no program upgrade. One config account per fee mint is enough. It stores the mint, the treasury token account that receives the fee, the amount in base units, the decimals that amount was computed with and the admin allowed to change it. Anchor puts an 8-byte discriminator in front of those fields, which matters when you decode the account off chain.

  • The pay instruction takes the payer's token account, the treasury token account and the mint, and reads the amount from the config account. Constraints check that the treasury and the mint are the ones the config names.
  • It moves the amount with transfer_checked and passes the decimals stored in the config account. The token program compares them with the mint's own decimals, so an amount written for other decimals fails on chain and cannot charge a million times too little.
  • The amount never arrives as an instruction argument. A client that supplies the amount sets its own price.
  • An update_fee instruction checks the admin signer and rejects a zero amount.
03

Convert dollars to base units

The script takes the fee as text in FEE_USD, default 2.50, and the fee mint in MINT, default USDC. TREASURY is optional and names the token account that collects the fee. It makes up to three reads on the RPC endpoint and settles each one, so a failed read is printed and the others still run. Exit code 1 means a missing or invalid setting or a failed mint read, and 2 means a FEE_USD it cannot parse into cents or a mint with fewer than 2 decimals.

main.ts
// UC0023 · USD-pegged checkout pricing// https://carbium.sh/library/usecase/usd-pegged-checkout-pricing// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: turn a fixed USD fee into stablecoin base units from the mint's own decimals.import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } 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 feeUsd = process.env.FEE_USD ?? "2.50"; // dollars as text, at most 2 decimalsconst mint = address(process.env.MINT ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); // USDCconst treasury = process.env.TREASURY; // optional: the token account that receives the feeif (treasury && !isAddress(treasury)) { console.error("TREASURY must be a valid token account address."); process.exit(1); }if (!/^\d+(\.\d{1,2})?$/.test(feeUsd)) { console.error("FEE_USD must look like 2.50 (dollars, at most 2 decimals)."); process.exit(2); }const [whole, frac = ""] = feeUsd.split(".");const cents = BigInt(whole!) * 100n + BigInt(frac.padEnd(2, "0"));const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const [supply, rent, balance] = await Promise.allSettled([  rpc.getTokenSupply(mint).send(),  rpc.getMinimumBalanceForRentExemption(165n).send(), // size of a token account  treasury ? rpc.getTokenAccountBalance(address(treasury)).send() : Promise.resolve(undefined),]);for (const r of [supply, rent, balance]) {  if (r.status === "rejected") console.error("call failed:", r.reason instanceof Error ? r.reason.message : r.reason);}if (supply.status !== "fulfilled") process.exit(1);const decimals = supply.value.value.decimals;if (decimals < 2) { console.error(`Mint has ${decimals} decimals, too few for a cent.`); process.exit(2); }const units = cents * 10n ** BigInt(decimals - 2); // integers only, no floatsconsole.log(`fee ${feeUsd} USD = ${units} base units of ${mint} (${decimals} decimals)`);if (rent.status === "fulfilled") console.log(`new token account rent: ${rent.value} lamports`);if (balance.status === "fulfilled" && balance.value) console.log(`treasury holds ${balance.value.value.amount} base units`);

run: CARBIUM_KEY=$CARBIUM_KEY FEE_USD=2.50 node main.ts

The fee is parsed from the string into whole cents with BigInt, so 2.30 is 230 and never 229.99999999999997. The mint's decimals come from getTokenSupply, and the base units are cents times ten to the power of the decimals minus 2. A mint with fewer than 2 decimals cannot express a cent, so the script stops there.

The rent line comes from getMinimumBalanceForRentExemption for a 165-byte token account. The merchant pays it once, when creating the treasury token account before the first payment. A payer who pays in the stablecoin already holds a token account for it, so the payer needs the fee and the transaction fee and nothing more.

04

Verify the payment on your server

The client reports a signature, and your server confirms it before releasing anything. Read the transaction with getTransaction at finalized before releasing goods, because @solana/kit fills in confirmed when a call leaves commitment out. Pass maxSupportedTransactionVersion: 1, because mainnet carries v1 transactions and the call answers -32015 for one when the value is absent or 0. Then run four checks: the transaction has no error, it carries the reference key or memo your server issued for this order as in Solana Pay confirmation, the treasury token account is in it, and the treasury's token balance rose by at least the fee in base units for that mint. Store each verified signature once and refuse it when it comes again.

A treasury balance includes every other payer, so compare the treasury's balance before and after this one transaction. The token balance rows list mint, owner and amount as a string of base units, so the difference is a BigInt subtraction of the pre row from the post row. When the transaction created the treasury token account, it has no pre row, and the pre amount counts as 0. A token transfer to an existing token account lists the token accounts and the sender's authority and leaves out the receiving wallet, so match the treasury by its token account or by the owner field of the balance rows.

ReadRPC methodCells per callFree req/sDev req/sBusiness req/sPro req/s
Treasury balancegetTokenAccountBalance100.51550400
Payment transactiongetTransaction500.241.2525

All keys on an account share one budget, so the verify read per paid order is what sizes your plan. At 5 orders a second on Business or 25 on Pro, every order gets its own read. Subscribe to the client's signature with signatureSubscribe at finalized: it sends one confirmation and the subscription then ends, and your server does its single getTransaction after that notification.

05

When the fee has to be in SOL

Some checkouts want SOL from the payer and a fixed dollar value anyway. The program then needs a price, and it cannot call out for one. Pass a price oracle account to the pay instruction, read it in the program, reject a stale update, and compute the lamports there with integer math. The config account stores the feed's address, and a constraint rejects any other account passed as the oracle. A server may show the buyer a price, but the program has to enforce the amount from its own oracle account.

The fixed-to-the-cent promise is also weaker in SOL. The charge follows the oracle's last update, so the staleness bound the program enforces sets how far the charge can drift from the cent. In a stablecoin the question never comes up, which is why the script above handles only that case.

06

Where it ends

  • A stablecoin is fixed in USD only as far as it holds its peg. The script converts dollars to base units and does not check the mint's market price.
  • The script reads and converts. It builds no Anchor program, and it signs and sends nothing.
  • A Token-2022 mint with a transfer fee extension delivers less than the sender's amount. Verify the treasury's balance difference, and set the fee high enough that the net amount covers your price.
  • The fee is expressed in whole cents. A fee with fractions of a cent needs its own rule for rounding.
  • The treasury token account has to exist before the first payment, and the script prints the rent a new token account needs but does not create one.
  • A SOL-denominated fee needs an oracle account in the program, and the script has no part in that.
07

When it goes wrong

what goes wrongwhat to do
The fee is charged a million times too small or too large.The amount was written with the wrong decimals. Derive base units from the mint's decimals as the script does, store those decimals in the config account, and call transfer_checked with the stored value so the token program rejects a mismatch.
A fee computed in JavaScript numbers is off by a base unit.Float math gives 2.3 times 100 as 229.99999999999997. Parse the dollar text into whole cents with BigInt and keep every amount an integer.
The verify read answers -32015.The transaction is v1 and the call left the version out. Pass maxSupportedTransactionVersion: 1 with an encoding on every getTransaction and getBlock.
The verify read returns null right after the client sends the signature.The transaction may not have landed yet. Subscribe to the signature, then read it once after the notification.
A payment verifies but the treasury received less than the fee.The mint has a Token-2022 transfer fee. Check the treasury's balance difference from the transaction, and price the fee so the net amount is enough.
Verify reads start returning 429 at busy times.Read the retry-after hint, sleep for it, then retry. Move confirmation to signatureSubscribe so each paid order costs one read.
08

Questions

Do I need an oracle for a fixed USD fee?

Not when the fee is charged in a USD stablecoin, because the fee is a constant number of base units. You need one only for a SOL-denominated fee, and it belongs in the program's accounts.

Can the client send the fee amount in the instruction?

No. The program reads the amount from its config account, and the client only picks the payer and token accounts. A client-supplied amount lets a buyer pay what they choose.

Can one config serve several stablecoins?

Use one config account per mint, each holding the same fee in cents converted with that mint's decimals. The pay instruction then checks the mint against its config.

Is the treasury balance enough to confirm an order?

No, because the balance includes every payer. Read the transaction and compare the treasury's balance before and after, which ties the amount to one signature.