library / AI and blockchain / SI0051
Prepaid MCP tool credits, vendor-neutral
You get a prepaid balance for MCP tool calls, funded by USDC sent to a token account you own. Each deposit is credited once by its signature, each call is debited locally, and the balance is a query over both logs.
Two logs, one balance
A prepaid balance needs two records per customer: what they paid in and what they have used. Keep those two and derive the rest. The balance is a query over them and never a column you update, so a crash between a credit and a debit cannot leave a number that matches neither log.
The deposits log is keyed by transaction signature. A signature is unique on chain, so the key does the deduplication. A restart, a scan that overlaps the previous one and two scanners running together can all read the same transfer, and the table accepts it once. The debits log is local to your service. Each row holds a payer, a tool name and a price in tool credits.
The customer sends USDC straight to a token account you own, and the scan reads that account's transactions. Your service reads that one account and writes the two logs, plus a table of the signatures it has already fetched.
Crediting a deposit by signature
A scan lists the five newest signatures of the treasury token account with getSignaturesForAddress, drops every signature already stored in scanned, then fetches each remaining one with getTransaction. Both calls pass finalized. A credit lets a customer spend, and @solana/kit 8.6.0 would otherwise fill in confirmed for a call that leaves commitment out.
Every signature that was fetched goes into scanned: an incoming deposit, an outgoing transfer, a deposit under 0.001 USDC and a null answer alike. A fetch that fails is left out, so the next pass tries it again. The balance query reads deposits only, so the extra rows never touch a balance.
getTransaction takes maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with the value absent or 0 the call answers -32015 for one, uncharged. The answer can also be null. Pages of getSignaturesForAddress come from an address index that reaches below the validator's ledger floor, so a listed signature may have no transaction behind it. The scan skips a null, credits nothing for it and records it as fetched. A transaction below the ledger floor answers null on every retry, so a deposit that comes back null needs a record kept outside the scan.
The amount comes from the token balances in the transaction metadata. A transfer instruction names token accounts and the sender's authority, never the receiving wallet, so the balances are where each owner is written down. The treasury's credit is its post balance minus its pre balance for the USDC mint. The payer is the owner of the account whose balance fell the most in the same transaction. A transfer, a transferChecked and a transfer inside an inner instruction read the same way, because the balances already include them. A failed transaction leaves the balances equal and credits nothing.
The insert is INSERT OR IGNORE into a table whose primary key is the signature. The changes count it returns says whether the row was new, and the scan adds those counts up. Run the same scan twice, or from two processes, and the second insert changes nothing. The sample's second scan hands the first scan's signatures back in and skips the scanned check, so the primary key alone does the deduplication.
Debiting a call
A debit reads the balance, compares it with the price and writes the row if the balance covers it, all under one write lock. BEGIN IMMEDIATE takes the lock before the read, so two calls arriving together cannot both spend the last credits. A call the balance cannot cover is refused before the tool runs, and nothing is written. If anything throws after the lock is taken, the debit rolls back, so a failed write cannot leave a transaction open.
The sample prices are 1, 10 and 50 tool credits for get_slot, get_account_info and get_signatures. They copy the 1, 10 and 50 cells that the RPC call behind each tool costs, the same three tools as the read-only MCP server.
Debit first and run the tool second. If the tool then fails, append a second row with a negative amount. The log stays append-only, the balance query still sums correctly and the history shows the refund. Editing the original row erases the record of what happened.
The file
Node 24 runs the file directly. @solana/kit 8.6.0 is the only dependency, and node:sqlite ships with Node. Set CARBIUM_KEY first; the file exits with a message when it is missing. CARBIUM_RPC_URL overrides the endpoint, which defaults to https://services.carbium.sh. The database is credits.db in the working directory, opened with a 5,000 ms busy timeout so a second process waits for a lock.
// SI0051 · Prepaid MCP tool credits, vendor-neutral// https://carbium.sh/library/si/prepaid-mcp-tool-credits-vendor-neutral// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Prepaid tool credits from USDC deposits. Run: CARBIUM_KEY=... node main.ts [treasury-token-account]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Signature } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");const PER_CREDIT = 1000; // raw USDC units per tool credit: 1 credit = 0.001 USDCconst cfg = { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: "finalized" } as const;const db = new DatabaseSync("credits.db", { timeout: 5000 }); // wait up to 5 s for another process's lockdb.exec(`CREATE TABLE IF NOT EXISTS deposits (signature TEXT PRIMARY KEY, payer TEXT NOT NULL, credits INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS debits (id INTEGER PRIMARY KEY, payer TEXT NOT NULL, tool TEXT NOT NULL, credits INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS scanned (signature TEXT PRIMARY KEY);`); // every fetched signature, credited or not// USDC balance change per account index in one transaction, with the account's owner.function usdcDeltas(tx: any): Map<number, { delta: number; owner: string }> { const out = new Map<number, { delta: number; owner: string }>(); for (const [list, sign] of [[tx.meta?.preTokenBalances, -1], [tx.meta?.postTokenBalances, 1]] as const) for (const b of list ?? []) if (b.mint === USDC) { const e = out.get(b.accountIndex) ?? { delta: 0, owner: b.owner }; out.set(b.accountIndex, { owner: e.owner, delta: e.delta + sign * Number(b.uiTokenAmount.amount) }); } return out;}const keysOf = (tx: any): string[] => tx.transaction.message.accountKeys.map((k: any) => k.pubkey);// The payer owns the account that lost the most USDC in a transaction that credited the treasury.function credit(tx: any, treasury: string) { const d = usdcDeltas(tx), to = d.get(keysOf(tx).indexOf(treasury)); const from = [...d.values()].sort((a, b) => a.delta - b.delta)[0]; return !tx.meta?.err && to && to.delta >= PER_CREDIT && from && from.delta < 0 ? { payer: from.owner, credits: Math.floor(to.delta / PER_CREDIT) } : null;}async function findTreasury(): Promise<string> { // the largest USDC credit in the mint's newest transactions for (const s of await rpc.getSignaturesForAddress(USDC, { limit: 3, commitment: "finalized" }).send()) { const tx = await rpc.getTransaction(s.signature, cfg).send(); const top = tx && [...usdcDeltas(tx)].sort(([, a], [, b]) => b.delta - a.delta)[0]; if (top && top[1].delta > 0) return keysOf(tx)[top[0]] as string; } throw new Error("no USDC credit among the mint's newest transactions");}// `again` is a list from an earlier scan: it is fetched as given, so INSERT OR IGNORE does the deduplication.async function scan(treasury: string, again?: Signature[]): Promise<[number, Signature[]]> { const listed = again ?? (await rpc.getSignaturesForAddress(address(treasury), { limit: 5, commitment: "finalized" }).send()).map((s) => s.signature); const seen = db.prepare("SELECT 1 FROM scanned WHERE signature = ?"); const sigs = again ? listed : listed.filter((s) => !seen.get(s)); // a recorded signature is never fetched again const got = await Promise.allSettled(sigs.map((s) => rpc.getTransaction(s, cfg).send())); const add = db.prepare("INSERT OR IGNORE INTO deposits VALUES (?, ?, ?)"), mark = db.prepare("INSERT OR IGNORE INTO scanned VALUES (?)"); let rows = 0; got.forEach((g, i) => { const sig = sigs[i]!; if (g.status === "rejected") return console.log("failed", sig.slice(0, 8), String(g.reason).slice(0, 80)); // retried next pass const c = g.value ? credit(g.value, treasury) : null; // null: a listed signature below the ledger floor if (c) rows += Number(add.run(sig, c.payer, c.credits).changes); mark.run(sig); // outgoing transfers, small deposits and null answers are recorded too }); return [rows, listed];}type Row = { payer: string; credited: number; spent: number };const balances = () => db.prepare(`SELECT payer, SUM(credits) AS credited, (SELECT COALESCE(SUM(credits), 0) FROM debits d WHERE d.payer = deposits.payer) AS spent FROM deposits GROUP BY payer`).all() as unknown as Row[];function debit(payer: string, tool: string, cost: number): boolean { // balance check and insert under one write lock db.exec("BEGIN IMMEDIATE"); try { const row = balances().find((r) => r.payer === payer); const ok = !!row && row.credited - row.spent >= cost; if (ok) db.prepare("INSERT INTO debits (payer, tool, credits) VALUES (?, ?, ?)").run(payer, tool, cost); db.exec("COMMIT"); return ok; } catch (e) { db.exec("ROLLBACK"); throw e; } // a throw never leaves the lock held}try { const treasury = process.argv[2] ?? (await findTreasury()); const [first, listed] = await scan(treasury); console.log("treasury", treasury, "| first scan, new rows:", first); const top = balances().sort((a, b) => b.credited - b.spent - (a.credited - a.spent))[0]; if (!top) console.log("no deposit among the newest 5 signatures"); else for (const [tool, cost] of [["get_slot", 1], ["get_account_info", 10], ["get_signatures", 50]] as const) console.log(top.payer.slice(0, 8), tool, cost, debit(top.payer, tool, cost) ? "debited" : "refused"); for (const r of balances()) console.log(r.payer.slice(0, 8), "credited", r.credited, "spent", r.spent, "balance", r.credited - r.spent); console.log("second scan, new rows:", (await scan(treasury, listed))[0]);} catch (e) { console.error("failed:", (e as Error).message); process.exitCode = 1;}
run: node main.ts
With no argument the file finds a treasury itself. It lists the newest signatures of the USDC mint, takes the first transaction that credited a USDC token account and uses the account with the largest credit. For real use, pass your own treasury token account as the first argument.
A run prints the treasury and the rows the first scan added. Then come three sample debits against the payer with the largest balance, one line per payer with credited, spent and balance, and a second scan that reuses the first scan's five signatures and adds 0. A later run finds credits.db already filled and fetches only signatures it has not recorded.
What a scan costs
| Call in one scan | Cells each | Calls |
|---|---|---|
| getSignaturesForAddress | 50 | 1 |
| getTransaction | 50 | 5 |
A full scan is 300 cells. A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger, so one scan fits inside a burst. Polling is the steady cost, and the five getTransaction calls set the pace. They run at 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, so a full scan fits about once every 21 s on Free and about once every 4.2 s on Dev.
Limits are per account, so other keys on the account spend the same budget. Signatures already in scanned are skipped before any fetch, so a pass over a treasury with nothing new costs one list call, 50 cells.
Where it ends
- The payer is whoever owned the source token account. A deposit sent from an exchange hot wallet or a program-owned account credits that owner, who may not be your customer. Give each customer a deposit address and credit by receiving account, as in the multi-address deposit monitor.
- The scan reads the newest five signatures. A treasury that receives more than five transfers between scans hides the rest until you page back with before to a stored signature.
- getSignaturesForAddress on Carbium reaches back 30 days at most, from its own address index. An empty page past that is the index's age limit, and the address may hold older transactions. A scanner that stays down longer than 30 days needs your own copy of what it missed.
- Nothing here sends USDC back. A transfer to the treasury is final, so a return is a new transfer signed somewhere else. This file has no key and signs nothing.
- One mint, whole credits, one file on one machine. A deposit under 0.001 USDC is ignored, PER_CREDIT must stay fixed after the first deposit, and two machines need a shared database where the same primary key does the same job.
- The file prices nothing by itself. Your MCP server has to call debit before it runs a tool and treat a refusal as the answer to the call.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A scan or a debit stops with "database is locked". | Another process holds the write lock and node:sqlite waits 0 ms by default. Open the file with { timeout: 5000 }, as the sample does, and keep each write short. |
| A listed signature comes back null and its deposit never appears. | The address index lists signatures below the validator's ledger floor, and such a transaction answers null on every retry. Scan more often than your deposit rate fills the page, and keep a record of that deposit outside the scan. |
| A small deposit adds no row. | Under 0.001 USDC it floors to 0 credits and the scan skips it. Set PER_CREDIT before the first deposit and leave it, since stored rows hold credits. |
| Scans fail with 429 after you shorten the poll interval. | Poll no faster than a full five-call scan fits: about once every 21 s on Free and about once every 4.2 s on Dev, since polling at the per-call getTransaction rate of 0.24 or 1.2 req/s would overrun it. Skip signatures already recorded, and check whether other keys on the account share the budget. |
| A balance goes negative. | A write bypassed debit. Spend only through that one function, which checks the balance and inserts under BEGIN IMMEDIATE. |
| Every call returns 401. | An unknown key gets 401 at the door. Attach the whole key in the x-api-key header. |
Questions
Why not keep a balance column and add to it?
Two writers and a crash make a column drift, and nothing says which write was lost. A balance computed from the two logs is right by construction, and a wrong number traces back to a row.
Can two processes scan the same treasury?
Yes. Both insert with the signature as the primary key, so the second insert changes nothing. Debits take one write lock per database file, and a process waits up to 5 seconds for it.
Are tool credits the same as Carbium credits?
No. Carbium credits meter RPC, WebSocket, stream and webhook work, and unspent ones stay. Tool credits are rows in your own file, priced by you.
How do I know which customer paid?
By the receiving account. Give each customer a deposit token account and key the deposits by it, or match the payer's wallet to the customer when they sign in. The sample keys on the payer's owner address.