Subscription allowance monitor
How to think about a monthly subscription on Solana: why the customer approves a delegate allowance, which fields to check before each charge, what the reads cost on Carbium, and a read-only Node script that reports the months covered.
What a subscription is on Solana
A token transfer needs the owner's signature, so a merchant cannot reach into a wallet on a schedule the way a card processor does. Monthly billing therefore comes down to three patterns. The customer signs a transfer each cycle after an invoice. The customer pre-funds a balance that your service draws down. Or the customer approves a delegate once, which is the pattern that behaves like a subscription.
The SPL Token program's Approve instruction writes two fields on the customer's token account: delegate, an address, and delegatedAmount, the most that address may move. The delegate can then call Transfer against that account without the owner signing, and each transfer lowers delegatedAmount by what it moved. Once the allowance is used up the program clears the delegate. Token-2022 accounts carry the same two fields.
The allowance is the subscription's budget, and it is only permission. The owner can still move the whole balance at any moment, and Revoke cancels the arrangement. A token account holds one delegate, so a second Approve to another service replaces yours. The token program sends the delegate no notice of a Revoke or a new Approve, so your service has to read the account or subscribe to it to see the change.
Three ways to bill monthly
| Pattern | Who signs each month | What you watch | How it fails |
|---|---|---|---|
| Invoice and pay | The customer | Whether a transfer to you landed | The customer forgets or is away |
| Pre-funded balance | Nobody, your service spends | The remaining balance | The balance runs out |
| Delegate allowance | Nobody, your service pulls | Delegate, allowance and balance on the customer's account | Allowance used up, revoked, replaced, or balance moved |
The first pattern needs no allowance monitor, and it is the right one when a customer wants to approve every payment. The second holds customer funds in an account you control, which makes you a custodian. The third keeps the money in the customer's wallet until the day of the charge, and it is the pattern the monitor below checks.
What to check before each charge
One read of the customer's token account answers all of these. Amounts are strings of base units, so compare them as BigInt integers: USDC has 6 decimals, and 5 USDC is 5000000.
- state: a frozen account rejects transfers whatever the allowance says, since the mint's freeze authority can freeze it.
- delegate: it must equal your merchant address. Another address means the customer approved something else after you.
- delegatedAmount: the remaining allowance. Divide it by the monthly price and round down for the months it covers.
- tokenAmount.amount: the balance. The allowance can be larger than the balance, so the charge is bounded by the smaller of the two.
- mint: the token the customer approved. Confirm it is the one you bill in.
Alert when either figure covers fewer than two months, which means at most one charge is left, since 0 covered months means the next charge already fails. With an alert below one month, a twelve-month allowance would read OK until its last pull cleared the delegate, and then jump to NO DELEGATE unwarned. The two-month alert shows ALLOWANCE LOW for one cycle first: OK at 2 months, ALLOWANCE LOW at 1, NO DELEGATE after the 12th pull. That gives the customer a full cycle to top up or approve again. Asking for twelve months of allowance at sign-up keeps the renewals rare and the exposure bounded.
A monitor in one file
The script takes an optional token account and an optional merchant address, and reads your monthly price in base units from MONTHLY_BASE_UNITS. It calls getAccountInfo in jsonParsed encoding, and every call reads at finalized commitment, so the check sees settled state. The key travels in the x-api-key header to the services.carbium.sh endpoint.
// UC0024 · Subscription allowance monitor// https://carbium.sh/library/usecase/subscription-allowance-monitor// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: how many monthly charges a token account's delegate allowance and balance still cover.import { 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 price = BigInt(process.env.MONTHLY_BASE_UNITS ?? "5000000");if (price <= 0n) { console.error("MONTHLY_BASE_UNITS must be above 0."); process.exit(1); }const [accountArg, merchant] = process.argv.slice(2);const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));type Key = string | { pubkey: string };type Tx = { meta: { postTokenBalances?: { accountIndex: number; mint: string }[] | null } | null; transaction: { message: { accountKeys: Key[] } } };type Info = { mint: string; owner: string; state: string; tokenAmount: { amount: string }; delegate?: string; delegatedAmount?: { amount: string } };// With no argument, take a token account from the newest successful transactions of a busy mint.async function discover(): Promise<string> { const page = await rpc.getSignaturesForAddress(address(USDC), { limit: 10, commitment: "finalized" }).send(); for (const s of page) { if (s.err) continue; try { // Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one. const tx = (await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" }).send()) as unknown as Tx | null; const hit = tx?.meta?.postTokenBalances?.find((b) => b.mint === USDC); const k = tx && hit ? tx.transaction.message.accountKeys[hit.accountIndex] : undefined; if (k) return typeof k === "string" ? k : k.pubkey; } catch (e) { console.error("getTransaction failed:", e instanceof Error ? e.message : e); } } console.error("No recent USDC token account found; pass one as the first argument."); process.exit(1);}try { const acct = accountArg ?? (await discover()); const res = await rpc.getAccountInfo(address(acct), { encoding: "jsonParsed", commitment: "finalized" }).send(); const parsed = (res.value?.data as unknown as { parsed?: { type: string; info: Info } } | undefined)?.parsed; if (!parsed || parsed.type !== "account") { console.error(`${acct} is not a parsed token account at finalized.`); process.exit(1); } const i = parsed.info; const balance = BigInt(i.tokenAmount.amount); const allowance = i.delegate ? BigInt(i.delegatedAmount?.amount ?? "0") : 0n; const byBalance = balance / price; const byAllowance = allowance / price; // Below 1 month the next charge already fails; an exact 12x allowance clears the delegate on its last pull. Alert at fewer than 2. const verdict = i.state === "frozen" ? "FROZEN" : !i.delegate ? "NO DELEGATE" : merchant && i.delegate !== merchant ? "WRONG DELEGATE" : byAllowance < 2n ? "ALLOWANCE LOW" : byBalance < 2n ? "BALANCE LOW" : "OK"; console.log(`account ${acct}\nmint ${i.mint}, owner ${i.owner}, state ${i.state}`); console.log(`balance ${balance} base units, covers ${byBalance} months at ${price}`); console.log(`delegate ${i.delegate ?? "none"}, allowance ${allowance} base units, covers ${byAllowance} months`); console.log(verdict);} catch (e) { console.error("Read failed:", e instanceof Error ? e.message : e); process.exit(1);}
run: CARBIUM_KEY=$CARBIUM_KEY MONTHLY_BASE_UNITS=5000000 node main.ts [tokenAccount] [merchantAddress]
With no account it lists the newest successful transactions of the USDC mint, reads the first USDC token account from one of them and reports on that. Mainnet carries v1 transactions, so that lookup passes maxSupportedTransactionVersion: 1, because with the value absent or 0 Carbium answers -32015 for one, uncharged. A failed lookup is printed and the next signature is tried.
The output is the balance, the delegate, the allowance, the months each one covers and a verdict: OK, NO DELEGATE, WRONG DELEGATE, FROZEN, ALLOWANCE LOW or BALANCE LOW. The two LOW verdicts fire when fewer than two months are covered, so OK means at least two charges are left. An ordinary wallet's account answers NO DELEGATE, which is true of most accounts. Point it at a customer's account and your merchant address for the real check. The script prints the mint and leaves the comparison with your billing token to you.
Reading many subscribers
Poll on the billing calendar. A day or two before each charge, read every subscriber once and message the low ones. A continuous poll adds cost and no information, because the state only moves when the customer or your own pull changes it.
getMultipleAccounts reads many accounts in one call and charges 10 cells per pubkey, which is 1000 cells for 100 pubkeys. Below Pro the 1024-cell burst caps a call at 100 pubkeys, so send at most 100 a call. A call of 300 pubkeys is Pro's.
| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getAccountInfo | 10 | 0.5 | 15 | 50 | 400 |
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |
The first row is the account-read class that getMultipleAccounts shares, charged per pubkey. Up to 100 JSON-RPC calls can go in one batch with no added envelope.
To confirm that a charge landed, list the subscriber's token account with getSignaturesForAddress. A delegate's pull names that account in its keys, with the delegate as the authority. Carbium serves these pages from its own address index, which keeps up to 30 days, so a check run soon after each charge is well inside the window. An empty page past 30 days marks the index limit, so keep your own record of older charges. Stablecoin settlement checks reads the balance diff of a transaction you find this way.
Where it ends
- The script reads state and cannot charge. The pull is a transaction signed with your merchant key, built and sent by your own service.
- A passing check is a snapshot. The owner can move the balance between your read and your pull, so read again just before charging and treat a failed pull as a normal event.
- One delegate per token account. A customer who subscribes to two services needs a separate token account for each, and you monitor the one they approved.
- A wallet can own more than one token account for a mint. The monitor reports the account you give it.
- The script covers token accounts. SOL has no delegate, so a SOL subscription needs a different design.
- Dunning, receipts, refunds and tax are your service's job.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The check says OK and the pull still fails, because the customer moved the balance after the read. | Read again just before charging, at finalized, and send the pull only if the covered months are at least 1. Treat a failed pull as a retry and a customer notice. |
| The delegate field shows another address and the subscription is assumed active. | Compare the delegate with your merchant address on every read. A second Approve replaced yours, so ask the customer to approve again. |
| The allowance is compared as a float and a 5 USDC price misses by rounding. | Use the amount strings as BigInt base units. USDC has 6 decimals, so 5 USDC is 5000000. |
| A customer pays from a second token account for the same mint, so the monitored account shows no delegate and the subscription looks lapsed. | Store the token account the customer approved at sign-up and read that one. A wallet can own several token accounts for a mint, and the monitor reports only the account you give it. |
| Finding an account fails with -32015 on a v1 transaction. | Pass maxSupportedTransactionVersion: 1 on every getTransaction call. With the value absent or 0, Carbium answers -32015 for a v1 transaction. |
| A customer who revoked the approval is logged as an error. | A revoked or used-up allowance clears the delegate, so the monitor prints NO DELEGATE. Record it as a cancellation or lapse and stop charging. |
Questions
Can a service pull a monthly payment from a Solana wallet by itself?
Only with an approval the customer signed earlier. Approve sets a delegate and a cap on one token account, and the delegate can transfer up to the cap with no further signature. Without it, every payment needs the customer's signature.
How large should the allowance be?
Approve a fixed number of cycles, such as twelve times the monthly price in base units, and alert when fewer than two months are covered. At most one charge is left then, so the customer has a full cycle to top up or approve again before the charge fails or the delegate clears. A larger allowance gives a compromised merchant key more to move, so a bounded one limits the exposure.
How do I see that a customer cancelled?
A revoked or used-up allowance clears the delegate field, so the monitor reports NO DELEGATE. Treat that as a cancellation or lapse.
What does checking many subscribers cost?
getMultipleAccounts charges 10 cells per pubkey, so a call of 100 pubkeys is 1000 cells. Below Pro a call carries at most 100 pubkeys, and 300 is Pro's.