library / Blockchain ideas / BI0072
Realizable value calculator
A script that quotes SOL to USDC at 1, 100 and 10,000 SOL, sets each quote against the listed price times the amount, and prints the gap in basis points. Give it a SOL amount or a wallet address and it quotes that too.
Price times amount
A balance screen that multiplies SOL by a listed price shows the value of a position. A user who asks what the SOL would fetch in USDC wants a different figure, the amount a swap would return now. A wallet or portfolio builder needs both numbers, and needs to know how far apart they are.
The second figure is the realizable value. It comes from a quote at the real size and it moves with that size. The calculator asks for both and prints the gap in basis points, where one basis point is 0.01%.
| Figure | Where it comes from | Moves with size |
|---|---|---|
| Listed price times amount | one prices call, then a multiplication | No, it is linear |
| Quoted USDC out | one quote call per size | Yes, the route fills against pool reserves |
| Gap | the two figures together, in bps | Yes, it widens as the size grows |
Three places use the gap. A portfolio header can carry the headline balance with a realizable line under it. A holdings list can flag positions where the gap passes a limit you choose. A confirm screen before a swap can show the user what the number on the balance screen would turn into.
Quoting a ladder of sizes
One quote answers for one size, so the script sends one per rung. The ladder is 1, 100 and 10,000 SOL, which shows the gap growing as the order grows. Amounts go in as integer base units in amount_in, at 1,000,000,000 lamports to the SOL, and the output comes back in USDC base units, six decimals.
The quote plane has four methods on the RPC endpoint, quote, swap, health and prices. The quote method takes a source mint, a destination mint and an amount in, and it needs a key with the QUOTE scope. The prices method returns the listed SOL price in USD.
The calls go out together and each settles on its own. A rung that fails prints its reason and the other rungs still print. Quotes are metered by plan, from 10 a second on Free to 500 a second on Elite, and they spend no credits, so a run of four or five calls fits any plan.
What sits in the gap
The gap has three parts. The first is the pools' own swap fees, taken on each hop of the route. The second is the difference between the listed price source and the pool prices the route fills against. The third is route impact: a route fills against pool reserves, a bigger order pushes each pool further along its curve, and the average price drops as the size grows.
A quote's platformFee is 5 bps, 0.05%, charged on chain in the transaction. Count it in the gap only if the out amount you read is net of it. On a 100 SOL swap, 5 bps is 0.05 SOL of value.
Pool fees and the price-source difference act close to a fixed rate, so they add about the same bps at every rung. Growth in the gap from one rung to the next comes from depth. A flat gap across the ladder says the route is deep at these sizes. A steep one says a large holder will see a smaller number than the balance screen shows.
Amounts and wallet mode
Pass a number as the first argument and it becomes one more rung in SOL, so node main.ts 2.5 quotes 2.5 SOL. Nobody has to edit the size list to price an amount they have in mind.
Pass an address instead and the script reads its SOL balance with getBalance at confirmed commitment, then quotes that balance as one more rung. getBalance returns lamports, so the same integer goes straight into amount_in with no conversion. A wallet with no SOL prints one line and skips the rung.
The balance rung is an upper bound. A wallet has to keep lamports for fees and rent, so a product that shows what a user can actually swap should quote the balance minus a reserve it chooses.
Other tokens in the wallet take the token-account path in Full-balance swap quote, and Multi-wallet USD net worth sums several wallets into one figure. This script stays with SOL so the first run needs only an address.
The script
Install @solana/[email protected] and run node main.ts [amount or wallet] on Node 24, which strips the types on load. CARBIUM_KEY is required. The quote answer is read at destAmountOut, the USDC amount in base units.
// BI0072 · Realizable value calculator// https://carbium.sh/library/blockchainideas/realizable-value-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 SOL = "So11111111111111111111111111111111111111112";const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const LAMPORTS = 1_000_000_000n; // lamports per SOLconst SIZES = [1n, 100n, 10_000n]; // the ladder, in SOLconst rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const arg = process.argv[2];const amount = arg && /^\d+(\.\d+)?$/.test(arg) ? arg : undefined; // a number is a SOL amountconst wallet = arg && !amount ? address(arg) : undefined; // anything else is a wallet addressconst why = (e: unknown) => (e instanceof Error ? e.message : String(e));async function call(method: string, params: unknown): Promise<any> { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key as string }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), }); const body: any = await res.json().catch(() => ({})); if (body.error) throw new Error(`${method} ${body.error.code} ${body.error.message}`); if (!res.ok) throw new Error(`${method} HTTP ${res.status}`); return body.result;}// The quote's output amount, in USDC base units.function outOf(answer: any): bigint { const v = String(answer?.destAmountOut); if (!/^\d+$/.test(v)) throw new Error(`no destAmountOut in ${JSON.stringify(answer).slice(0, 200)}`); return BigInt(v);}const toLamports = (s: string) => { const [w = "0", f = ""] = s.split("."); return BigInt(w) * LAMPORTS + BigInt(f.padEnd(9, "0").slice(0, 9));};const sol = (l: bigint) => `${l / LAMPORTS}.${(l % LAMPORTS).toString().padStart(9, "0").slice(0, 4)}`;const usdc = (u: bigint) => `${u / 1_000_000n}.${(u % 1_000_000n).toString().padStart(6, "0").slice(0, 2)}`;const [prices, balance] = await Promise.allSettled([ call("prices", []), wallet ? rpc.getBalance(wallet, { commitment: "confirmed" }).send() : Promise.resolve(undefined),]);let listed = NaN; // USD per SOLif (prices.status === "fulfilled") { listed = Number(prices.value?.solUsd ?? prices.value?.rows?.find((r: unknown[]) => r[0] === SOL)?.[1]);} else { console.error(`prices failed: ${why(prices.reason)}`);}if (listed > 0) console.log(`listed price ${listed.toFixed(4)} USD per SOL`);else console.error("no listed price, gaps print as n/a");const rungs: { label: string; lamports: bigint }[] = SIZES.map((s) => ({ label: `${s}`, lamports: s * LAMPORTS }));if (amount) rungs.push({ label: amount, lamports: toLamports(amount) });if (balance.status === "rejected") { console.error(`getBalance failed: ${why(balance.reason)}`);} else if (balance.value) { const lamports = balance.value.value; if (lamports > 0n) rungs.push({ label: `wallet ${sol(lamports)}`, lamports }); else console.log("wallet holds no SOL, nothing to quote");}const quotes = await Promise.allSettled( rungs.map((r) => call("quote", { src_mint: SOL, dst_mint: USDC, amount_in: r.lamports.toString(), slippage_bps: 50 })),);quotes.forEach((q, i) => { const r = rungs[i]!; if (q.status === "rejected") { console.error(`${r.label} SOL: quote failed: ${why(q.reason)}`); return; } try { const out = outOf(q.value); const effective = Number(out) / 1e6 / (Number(r.lamports) / 1e9); // USDC per SOL actually returned const gap = listed > 0 ? `${((1 - effective / listed) * 1e4).toFixed(1)} bps` : "n/a"; console.log(`${r.label} SOL ${usdc(out)} USDC effective ${effective.toFixed(4)} gap ${gap}`); } catch (e) { console.error(`${r.label} SOL: ${why(e)}`); }});if (quotes.every((q) => q.status === "rejected")) process.exitCode = 1;
run: CARBIUM_KEY=<YOUR_KEY> node main.ts [WALLET_ADDRESS_OR_SOL_AMOUNT]
Each line shows the size, the USDC out, the effective price, which is USDC out divided by SOL sold, and the gap in bps against the listed price. A negative gap means the quote landed above the listed figure.
Where it ends
- The printed figure is a quote. The swap method builds an unsigned transaction that you sign and send yourself, and pools move between the quote and the landing, so the amount received can differ from the line printed here.
- USDC is a token. Moving it into a bank account takes an exchange or off-ramp with its own fees and limits, outside this calculator.
- The script quotes one direction, an amount of SOL in and USDC out. It takes no USDC target and does not solve for the SOL that would reach it.
- The pair is fixed at SOL to USDC. The listed price comes from one prices call per run, and nothing is stored, so there is no history to chart.
- The script only reads. It signs nothing, sends nothing and holds no private key.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every rung prints a quote failure with 401. | An unknown key is turned away at the door, so attach the whole key in CARBIUM_KEY. On a quote call, a 401 with code -32001 means the key is unknown or lacks the QUOTE scope, which you give it in your account. |
| One or two rungs print 429 while the others print. | The call went over its quote rate and the wait did not clear. Run again after the retry-after wait the answer names. Limits are per account, so other tools on the same keys draw on the same budget. |
| Every gap prints n/a. | The prices call failed or its answer carried no SOL price. The quotes still print, so read the prices line on stderr and run again. |
| The 1 SOL gap prints negative or swings between runs. | The price and the quote are separate calls made at slightly different moments. Round the gap to whole bps, or repeat the run, and judge the larger rungs against that baseline. |
| The 10,000 SOL rung fails or returns a very thin amount. | A size that large can find little depth on the route. Read the printed reason, then edit the SIZES list to the amounts your users hold. |
Questions
Why quote when I can multiply by the price?
Price times amount is linear, so 10,000 SOL looks like 10,000 times one SOL. A quote runs the real route at that size, so it shows what the pools would hand back, and the gap between the two is the number worth putting in front of a user.
Does the 5 bps router fee apply at every size?
A quote's platformFee is 5 bps, 0.05%, charged on chain in the transaction, and it is a rate, so it takes the same share at each rung. It sits in the gap only if the out amount you read is net of it, and growth in the gap across rungs comes from route depth.
Does a run spend credits?
The quote plane spends none, because its plan is the meter. The getBalance read for a wallet is metered RPC work, so it draws on the account's credits.
Can I price a wallet's USDC or other tokens this way?
This script handles SOL in and USDC out. For token balances, read the token accounts and quote each mint as in Full-balance swap quote, then set the quote against a price for that mint.
Is the quoted figure what the user receives?
No. It is the answer to a request made now. The swap lands later against pools that have moved, so the received amount can differ.