library / Blockchain ideas / BI0048
Token liquidity depth chart
A depth chart built from quotes at five sizes, so a token page shows what a swap of each size costs in price impact. Vault balances for pools you name sit beside it as a second panel.
Depth as price impact
A token page or launch dashboard usually has to answer one question: how large can a swap get before the rate gives way? Pool reserves look like the answer, but a reserve figure says little about the path a swap takes. A router splits a large order over several pools and may add hops, so the depth a buyer meets at 1,000 SOL can differ from the depth at 1 SOL while every reserve stays the same.
The measurement that matches what a user feels is price impact. Ask for a quote at a series of sizes and compare the rate each size returns with the rate the smallest size returns. A token with deep liquidity returns nearly the same rate at every size. A thin one gives up a larger share as the size grows. Impact against size is the depth chart.
The quote method answers on the RPC endpoint under the same key as every other call. The ladder spends no credits and draws only on the account's quote-plan rate, and anyone can check a number by asking for the same swap.
The size ladder and effective price
The ladder is five sizes, each ten times the one before: a tenth of a unit of the source token, then 1, 10, 100 and 1,000 whole units. For SOL into USDC that runs from 0.1 to 1,000 SOL. Sizes are integer base units (1,000,000,000 per SOL), so the arithmetic stays in whole numbers.
| Column | Meaning | How it is computed |
|---|---|---|
| Size | Whole source tokens sold | the ladder step |
| Effective price | Output base units received per whole source token | output times one unit, divided by the input |
| Impact | How far the effective price sits below the smallest size's, in basis points | (smallest price minus this price) times 10,000, divided by the smallest price |
The router's platformFee is 5 bps, charged on chain in the transaction. It is the same share at every size, so it cancels when each size is compared with the smallest, and the impact column shows the move caused by size alone. For the legs behind a single size, see swap route breakdown.
The code asks one size at a time, in order, each call in its own try. A size with no route prints as failed and the others still draw. With no arguments it also reads the two Raydium SOL-USDC pool vaults; pass your own vault addresses as arguments to read those instead.
// BI0048 · Token liquidity depth chart// https://carbium.sh/library/blockchainideas/token-liquidity-depth-chart// 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 SRC = process.env.SRC_MINT ?? "So11111111111111111111111111111111111111112";const DST = process.env.DST_MINT ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const UNIT = BigInt(process.env.SRC_UNIT ?? "1000000000"); // base units in one whole source tokenconst rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));// 0.1, 1, 10, 100 and 1000 whole tokens, as integer base units.const sizes = [UNIT / 10n, UNIT, UNIT * 10n, UNIT * 100n, UNIT * 1000n];const whole = (size: bigint) => String(Number(size) / Number(UNIT));const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));const quoteOut = async (amountIn: bigint): Promise<bigint> => { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "quote", params: { src_mint: SRC, dst_mint: DST, amount_in: amountIn.toString(), slippage_bps: 50 }, }), }); const body = (await res.json().catch(() => ({}))) as { result?: Record<string, unknown>; error?: { code: number; message: string } }; if (body.error) throw new Error(`${body.error.code} ${body.error.message}`); if (!res.ok || !body.result) throw new Error(`HTTP ${res.status}`); // The output amount is the first whole-number field with "out" in its name. const hit = Object.entries(body.result).find(([k, v]) => /out/i.test(k) && /^\d+$/.test(String(v))); if (!hit) throw new Error(`no output amount in ${JSON.stringify(body.result).slice(0, 200)}`); return BigInt(String(hit[1]));};// One size at a time, each in its own try: a size with no route does not stop the rest.const quoted: { size: bigint; price: bigint }[] = [];for (const size of sizes) { try { quoted.push({ size, price: (await quoteOut(size) * UNIT) / size }); } catch (e) { console.log(`${whole(size).padStart(7)} tokens failed: ${msg(e)}`); }}const base = quoted[0]?.price;if (!base) { console.error("no size answered"); process.exit(1);}const rows = quoted.map((r) => ({ ...r, bps: ((base - r.price) * 10000n) / base }));const worst = rows.reduce((m, r) => (r.bps > m ? r.bps : m), 1n);console.log(`${SRC.slice(0, 6)} into ${DST.slice(0, 6)}, effective price in output base units per whole token`);for (const r of rows) { const bar = "#".repeat(Number(((r.bps > 0n ? r.bps : 0n) * 40n) / worst)); console.log(`${whole(r.size).padStart(7)} tokens ${String(r.price).padStart(12)} ${String(r.bps).padStart(5)} bps ${bar}`);}// Second panel: reserves of the vaults passed as arguments, else the two Raydium SOL-USDC vaults.const defaults = ["DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz", "HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz"];for (const vault of process.argv.length > 2 ? process.argv.slice(2) : defaults) { try { const { value } = await rpc.getTokenAccountBalance(address(vault), { commitment: "confirmed" }).send(); console.log(`vault ${vault.slice(0, 8)} ${value.uiAmountString} (${value.amount} base units, ${value.decimals} decimals)`); } catch (e) { console.log(`vault ${vault.slice(0, 8)} failed: ${msg(e)}`); }}
run: CARBIUM_KEY=<YOUR_KEY> node main.ts [vault-address ...]
With no arguments it quotes SOL into USDC. SRC_MINT, DST_MINT and SRC_UNIT (base units in one whole source token) switch the pair. The smallest size that answered is the baseline for the impact column.
Vault balances for pools you name
A pool holds its two sides in token accounts called vaults. getTokenAccountBalance reads one and returns the raw amount, the decimals and a display string, at the commitment the call names. The code asks for confirmed. It takes the vault addresses as given, since finding them means decoding each pool's own account layout, which differs by dex.
Read both panels together. A small vault next to a flat ladder means the router found depth in other pools. A large vault next to a steep ladder can mean the router is not sending the swap through that pool at that size, or that the liquidity sits outside the active range of a concentrated pool.
Each vault read is one of the account reads at 10 cells a call, so the rate is 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. Free holds one vault read every 2 seconds sustained. The burst covers only a first load of many reads at once, so a steady few vaults every few seconds runs past Free once the burst is spent.
Drawing the curve
The script prints one row per size with a bar of up to 40 characters, scaled to the largest impact in the run. In a browser the same rows go to any chart library as JSON, once the bigint size, price and bps values are turned into strings or numbers, since JSON.stringify throws on a bigint.
- Put size on a log axis. Each step is ten times the last, so a linear axis crushes the first three points into one corner.
- Draw impact in basis points and mark 100 bps as 1 percent, so a visitor can read it without a legend.
- Show a failed size as a gap in the line with the error text on hover, instead of drawing it as zero impact.
- Stamp the chart with the time of the quotes. It is a snapshot, and a visitor should see how old it is.
- Put the vault balances under the curve as a small table of amount and decimals, one row per named pool.
Refresh pace inside the quote plan
One ladder is five quote calls. Quote plans are per account: Free $0 at 10 quotes/s, Starter $7 at 50/s, Pro $28 at 150/s and Elite $104 at 500/s. One token refreshed every 5 seconds draws 1 quote/s. Ten tokens at that pace draw 10 quotes/s, the whole of Free's rate. The sum is five times the number of tokens, divided by the seconds between refreshes.
Serve visitors from a cache that one background loop fills. The quote rate then follows the number of tokens and the refresh gap, and a thousand visitors on the page add no quote calls. The loop in the code runs the five calls one after another and never in parallel.
Where it ends
- The route changes with size. The router may use one pool at 0.1 SOL and several at 1,000, so the curve can bend or step, and it is no single pool's formula.
- A quote is a snapshot. By the time a visitor swaps, reserves have moved and the quoted size may land differently.
- There is no order book. The chart shows what a swap returns now, and it has no resting orders or depth at chosen prices.
- In a concentrated-liquidity pool the vault holds liquidity outside the active price range, so a big vault can overstate what is usable near the current rate.
- One direction is measured, selling the source token. The reverse direction is a second ladder with its own quotes.
- The vault panel covers the pools you pass. Pools the router uses that you did not name are visible only through the ladder.
- getTokenLargestAccounts is not served and answers -32601, so a holder concentration panel needs a different source.
- Sizes above the top rung are not shown, and a token with no route at 1,000 units draws a gap there.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| One size prints failed while the others draw. | The router found no route for that size, usually the largest. Keep the gap on the chart, and lower the top rung of the ladder if the token is thin. SRC_UNIT is 10 to the power of the mint's decimals, 1000000 for a 6-decimal mint. |
| Every size fails with -32001 and a message about the api key. | The key lacks the QUOTE scope. Give the key that scope, then run again. |
| Every size fails with a message saying no output amount was found. | The code takes the first whole-number field with out in its name. The message prints the start of the reply, so rename the match to the field your reply carries. |
| A vault read fails with an invalid account error. | The address is the pool account or a wallet. Pass the token account that holds the pool's reserve. |
| Impact reads zero or negative at a larger size. | The router found a better split at that size, or the smallest rung rounds badly in a token with few decimals. Raise the first rung of the ladder so it is a clear amount, and set SRC_UNIT to 10 to the power of the mint's decimals, 1000000 for a 6-decimal mint. |
| A call answers -32601. | The method is not served. Do not retry it. Check the method name against the served list. |
Questions
Why quote instead of computing impact from pool reserves?
A constant-product formula describes one pool. The router splits across pools and mixes pool types, so a quote returns what a swap gets. The vault panel keeps the reserves in view next to it.
Does asking for quotes cost credits?
No. The quote plane spends no credits and its plan is the meter. The vault reads are account reads and do count against your rate and credits.
Can I chart a pair other than SOL and USDC?
Yes. Set SRC_MINT and DST_MINT, and SRC_UNIT to the base units in one whole source token. The ladder and the impact column follow.
Which commitment do the vault balances use?
Confirmed, which the code names in the call. Change it in the one place if you want finalized.
How many tokens can one account chart on Free?
Ten, refreshed every 5 seconds, using all of the 10 quotes/s. Slow the refresh or move up a quote plan for more.