library / Use cases / Analytics and research / UC0116
Pool reserve price series
A price series built from pool reserves: read the base and quote vaults in one call, adjust for decimals, divide, and store each sample with its slot in SQLite, plus the cost on each plan and the pools this method misprices.
The price is a ratio of two balances
A constant-product pool holds a reserve x of a base token and a reserve y of a quote token, and keeps x times y fixed across a swap apart from fees. The marginal price of one base token is y divided by x, with both reserves in whole tokens. A pool holding 40,000 SOL and 6,000,000 USDC prices one SOL at 150 USDC.
The two reserves sit in token accounts that the pool program owns, called vaults. Each vault is an ordinary SPL token account and its balance is the reserve. So a price series is the two balances read at the same moment, divided, and stored with the slot they came from. When you know the vault addresses, no pool-specific decoder is needed, because a vault decodes like any other token account.
Whole tokens matter. Balances are integers in base units and every mint sets its own decimals. SOL has 9 and USDC has 6, so the pool above holds 40,000,000,000,000 and 6,000,000,000,000 base units, and their raw ratio reads 0.15, which is 1,000 times too small. Divide each balance by 10 to the power of its mint's decimals first.
Read both vaults in one call
Read the two vaults in a single request so the balances come from the same state. Two separate reads can straddle a swap, and a ratio of a balance from before it and a balance from after it is a price the pool never quoted. getMultipleAccounts answers every account in the call with one context slot.
With jsonParsed encoding the node decodes each vault for you: the mint, and a tokenAmount holding the integer amount as a string plus the decimals. The decimals arrive with the balance, so the script needs no mint lookup and no hard-coded 9 or 6.
The call is an account read at 10 cells per pubkey, so a two-vault call costs 20 cells. The script reads at confirmed commitment.
A sampler in one file
Install the one dependency with npm i @solana/[email protected]. The script reads CARBIUM_KEY and exits with a message when it is unset. It takes the base vault and the quote vault as its two arguments. The key travels in the x-api-key request header, and CARBIUM_RPC_URL overrides the endpoint. SAMPLES and INTERVAL_S default to 5 and 3. POOL_DB names a file when the rows should outlive the process, and without it SQLite runs in memory.
// UC0116 · Pool reserve price series// https://carbium.sh/library/usecase/pool-reserve-price-series// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: prices a pool's base token in its quote token from the two vault balances read in one call, and keeps the series in SQLite.import { DatabaseSync } from "node:sqlite";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 [baseVault, quoteVault] = process.argv.slice(2);if (!baseVault || !quoteVault || !isAddress(baseVault) || !isAddress(quoteVault)) { console.error("Usage: node main.ts <base vault> <quote vault>"); process.exit(1);}const samples = Number(process.env.SAMPLES ?? 5), everyMs = Number(process.env.INTERVAL_S ?? 3) * 1000;type Vault = { parsed?: { type: string; info: { mint: string; tokenAmount: { amount: string; decimals: number } } } };const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const db = new DatabaseSync(process.env.POOL_DB ?? ":memory:");db.exec("CREATE TABLE IF NOT EXISTS pool_prices (ts INTEGER, slot INTEGER, base TEXT, quote TEXT, price REAL, k TEXT)");const insert = db.prepare("INSERT INTO pool_prices VALUES (?, ?, ?, ?, ?, ?)");const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));async function sample() { // One call, one context slot: both balances describe the same pool state. const { context, value } = await rpc .getMultipleAccounts([address(baseVault!), address(quoteVault!)], { commitment: "confirmed", encoding: "jsonParsed" }) .send(); const [b, q] = value.map((a) => (a?.data as unknown as Vault | undefined)?.parsed); if (b?.type !== "account" || q?.type !== "account") return console.log("a vault is missing or not a token account"); const bx = b.info.tokenAmount, qx = q.info.tokenAmount; // Balances are base units: divide each by 10 to the power of its own decimals before the ratio. const baseWhole = Number(bx.amount) / 10 ** bx.decimals, quoteWhole = Number(qx.amount) / 10 ** qx.decimals; if (!baseWhole) return console.log("base reserve is empty"); const price = quoteWhole / baseWhole; const k = (BigInt(bx.amount) * BigInt(qx.amount)).toString(); insert.run(Date.now(), Number(context.slot), bx.amount, qx.amount, price, k); console.log(`slot ${context.slot} base ${baseWhole} quote ${quoteWhole} price ${price.toPrecision(8)}`);}for (let i = 0; i < samples; i++) { if (i) await sleep(everyMs); try { await sample(); } catch (e) { console.log("read failed:", e instanceof Error ? e.message : e); }}console.table(db.prepare("SELECT COUNT(*) AS rows_kept, MIN(price) AS low, MAX(price) AS high, MAX(slot) - MIN(slot) AS slot_span FROM pool_prices").all());
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts DQyrAcCrDXQ7NeoqGgDCZwBvWDcYmFCjSb9JtteuvPpz HLmqeL62xR1QoZ1HKKbXRrdN1p3phKpxRMb2VVopvBBz
Each row stores the slot, both raw balances as strings, the price and the product of the two balances. The product is the pool's invariant. Between swaps it stays level, and across a swap it grows by the fee, so a row whose product drops sharply points to a withdrawal of liquidity or fees taken out of the vault. The raw balances stay strings because a token with 9 decimals and a large reserve can pass what a float holds exactly. The price itself is a float, which is enough for a chart.
A failed read prints a line and the loop goes on to the next sample. A vault that is closed, missing or not a token account prints a line and stores nothing. The run ends with a summary of the rows kept, the minimum and maximum price, and the slot span.
Checking a sample before you trust it
A ratio of vault balances is the pool's marginal price. Four things decide whether that is the number you want.
- Depth. A swap of 1% of the base reserve executes about 1% worse than the marginal price, before fees. On a thin pool a number that is exact for the pool is a poor guide to what a sale of any size receives.
- Orientation. A price of 150 for SOL in USDC is 0.00667 for USDC in SOL. Label the column with both mints so a later reader does not invert it.
- Stray balances. Some pool programs hold unclaimed fees in the vault or place part of the liquidity elsewhere, so the vault balance can differ from the reserve the program prices with. Compare one sample against the pool's own state before you rely on the series.
- A second opinion. Carbium quotes answer on the same endpoint, and one of their methods is prices. A key needs the QUOTE scope for it. One spot comparison against it shows a wrong pair of vaults or a swapped orientation at once.
Run the comparison once when you add a pool. The series itself needs only the two reads.
What a series costs on each plan
Limits are per account, so every key on the account draws on one rate. A two-vault call is one 20-cell account read. The table divides each plan's account-read rate, in cells a second, by 20 to give the sustained calls a second for one pool. The account-read class also absorbs a burst of up to 1,024 cells or one second of its rate, whichever is larger.
| Plan | Account reads req/s | Cells per second | Two-vault calls per second |
|---|---|---|---|
| Free | 0.5 | 5 | 0.25 |
| Dev | 15 | 150 | 7.5 |
| Business | 50 | 500 | 25 |
| Pro | 400 | 4000 | 200 |
On Free that is one sample every 4 seconds for one pool, and the default INTERVAL_S of 3 polls faster than that, so a long run there drains the burst and reads start to fail. Set it to 4 or more on Free. A short run such as the default 5 samples spends 100 cells and fits the burst. One call can also carry the vaults of several pools: up to 100 pubkeys below Pro, so 50 pools per call, at 10 cells each.
Where it ends
- Concentrated-liquidity pools price from a square-root price kept in the pool's own account, and their vault balances cover liquidity spread over many ranges. The vault ratio is not their price, so read the pool account and decode it instead.
- The series starts at your first sample. An account read returns current state, and no read returns a vault's balance at a past slot.
- Rebuilding history from swaps goes through getSignaturesForAddress, which reaches back 30 days at most because its pages come from an address index. Those pages reach below the validator's ledger floor, so getTransaction can answer null for an older signature they list. The transactions that do come back give amounts for single swaps and need their own parsing.
- The number is one pool's marginal price. A route through several pools, or a swap large enough to cross depth, executes at a different price, and the quote method is where that price comes from.
- The series is as fine as your interval. A price that moves and returns between two samples leaves no trace. A faster poll costs cells, and a stream of vault changes costs credits for each subscription and each MiB sent.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The price is off by a factor of 1,000 or more. | The two mints have different decimals and the raw balances were divided. Divide each balance by 10 to the power of its own decimals first, as the script does, and print both decimals once to confirm them. |
| The series is the inverse of the chart you expected. | The vault arguments are in the wrong order. The first argument is the token being priced and the second is the token it is priced in. Swap them, or store 1 divided by the price, and label the column with both mints. |
| A line says a vault is missing or not a token account. | The address is the pool account, a wallet or a closed vault. Take the vault addresses from the pool's decoded state, and check that the account is owned by a token program. |
| The price sits a little off the pool program's own quote on a busy pool. | Unclaimed fees or liquidity held outside the vault make the vault balance differ from the program's reserve. Compare one sample against the pool state, and apply the adjustment that pool program defines. |
| The product of the balances falls between two samples. | Liquidity or collected fees left the vault, or one of the two vault arguments belongs to another pool. A swap alone never lowers the product, so check the pair first and then the pool's withdrawals. |
| Reads start failing partway through a long run on Free. | Each two-vault call costs 20 cells against a Free rate of 5 cells a second. Lengthen INTERVAL_S to 4 or more, or move to a plan with a higher account-read rate. The script prints the failed read and takes the next sample. |
Questions
How do I get a token price from an LP pair?
Read the pool's two vault balances at the same moment, divide each by 10 to the power of its decimals, and divide the quote reserve by the base reserve. For a constant-product pool that is the marginal price of one base token in the quote token.
Why read both vaults in one call?
One getMultipleAccounts call answers every account at a single slot. Two separate reads can fall on either side of a swap, and the ratio of mismatched balances is a price the pool never held.
Does the ratio work for every pool?
It holds for constant-product pools whose reserves are the vault balances. Concentrated-liquidity pools price from a square-root price in the pool account, and some programs hold fees or liquidity outside the vault, so check one pool against its own state first.
How many pools can I sample at once?
Each vault is a 10-cell account read, so a pool costs 20 cells. One call takes up to 100 pubkeys below Pro and 300 on Pro, and the number of calls a second depends on your plan's account-read rate.