---
id: BI0141
title: "Concentrated pool price stream"
url: https://carbium.sh/library/blockchainideas/concentrated-pool-price-stream
collection: Blockchain ideas
category: Data products
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Concentrated pool price stream

Subscribe to one pool account with accountSubscribe on Carbium's WebSocket, decode the square-root price from each update, and print the price with its tick. You get a price line per change, with no polling and no node of your own.

## Who uses it

Two groups keep a live price open for one concentrated-liquidity pool. A market-making desk watches where the pool price sits against the ranges its positions cover, and it needs a line each time the price moves. A wallet or checkout page shows the pair's price, and it needs that number to be current when the user presses confirm.

Both read one account. A pool is an account, and its price is a field inside it. An `accountSubscribe` on the pool's address sends the account's state each time it changes. The stream carries the price with no polling loop, and the price and the tick come from the same state, so they cannot disagree.

A hackathon team can point the monitor at any pool it likes. The default search finds one, and an address passed as an argument replaces it.

## What the stream carries

The notification returns the whole pool account as base64. Four fields matter here, at fixed offsets in the Whirlpool layout this code reads. Check the offsets against the program's published account layout before you rely on them, since an upgrade can move a field.

| Field | Offset | How it is read |
|---|---|---|
| Square-root price | 65 | u128 little-endian, read as four 32-bit words |
| Tick index | 81 | i32 little-endian |
| Token A mint | 101 | 32 bytes, decoded to a base58 address |
| Token B mint | 181 | 32 bytes, decoded the same way |

The pool stores the square root of the price of token A in token B, scaled by 2^64. The code squares that root and multiplies by ten to the power of the decimal difference, so the printed price is token B per token A in human units. Decimals come from byte 44 of each mint account, read once at start.

The context slot on each notification is the slot the state was read at. Store it with the price if you keep a series, because the price belongs to that slot.

## The build

The monitor is one file that needs `@solana/kit` and what Node 24 ships. It is read-only: it loads no key pair and sends nothing.

1. Find the pool. Use the address in the first argument. Without one, read the newest signatures of the program and take the first transaction that names an account owned by the program with the pool's 653-byte size.
2. Read the pool once with getAccountInfo at confirmed commitment, then the two mints with getMultipleAccounts. Print the starting price, so the run shows a value before the first change.
3. Open one WebSocket to `wss://services.carbium.sh` with the key as `?api-key=`, and send [accountSubscribe](https://carbium.sh/docs/websocket) for the pool, base64 encoded, at confirmed commitment.
4. On each accountNotification, decode the four fields and print the slot, tick and price. A line prints only when the account changes, so a quiet pool prints nothing.
5. On close, wait two seconds and subscribe again.

`main.ts` (run: `CARBIUM_KEY=<YOUR_KEY> node main.ts`)

```ts
// BI0141 · Concentrated pool price stream
// https://carbium.sh/library/blockchainideas/concentrated-pool-price-stream
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, type Address } 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 WS_URL = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);

// Whirlpool-layout concentrated-liquidity program. Pass a pool address as the first argument to skip the search.
const PROGRAM = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc" as Address;
const POOL_LEN = 653; // pool account size in this layout
const short = (a: string): string => a.slice(0, 6);
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));

type Meta = { mintA: string; mintB: string; decA: number; decB: number };

async function findPool(): Promise<Address> {
  if (process.argv[2]) return process.argv[2] as Address;
  const sigs = await rpc.getSignaturesForAddress(PROGRAM, { limit: 10 }).send();
  for (let i = 0; i < sigs.length; i++) {
    if (i > 0) await pause(4200); // getTransaction is 0.24 req/s on Free
    try {
      const tx = await rpc.getTransaction(sigs[i].signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 }).send();
      if (!tx) continue;
      const keys = [...tx.transaction.message.accountKeys];
      const infos = await rpc.getMultipleAccounts(keys, { encoding: "base64" }).send();
      const hit = keys.find((_, j) => {
        const acct = infos.value[j];
        return acct !== null && acct.owner === PROGRAM && Buffer.from(acct.data[0], "base64").length === POOL_LEN;
      });
      if (hit) return hit;
    } catch (e) {
      console.error("skipped one transaction:", e instanceof Error ? e.message : e);
    }
  }
  throw new Error("no pool found in the newest transactions; pass a pool address as the first argument");
}

function read(data: Buffer, m: Meta): { tick: number; price: string } {
  const w = (i: number): number => data.readUInt32LE(65 + 4 * i); // u128 sqrt price as four 32-bit words
  const root = w(2) + w(3) * 2 ** 32 + (w(0) + w(1) * 2 ** 32) / 2 ** 64; // sqrt price / 2^64
  return { tick: data.readInt32LE(81), price: (root * root * 10 ** (m.decA - m.decB)).toPrecision(8) };
}

function subscribe(address: Address, meta: Meta): void {
  const ws = new WebSocket(`${WS_URL}/?api-key=${key}`);
  ws.onopen = () => ws.send(JSON.stringify({
    jsonrpc: "2.0", id: 1, method: "accountSubscribe",
    params: [address, { encoding: "base64", commitment: "confirmed" }],
  }));
  ws.onmessage = (ev) => {
    const msg = JSON.parse(String(ev.data));
    if (msg.id === 1) return console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`);
    if (msg.method !== "accountNotification") return;
    const { context, value } = msg.params.result;
    const p = read(Buffer.from(value.data[0], "base64"), meta);
    console.log(`slot ${context.slot} tick ${p.tick} price ${p.price} ${short(meta.mintB)} per ${short(meta.mintA)}`);
  };
  ws.onclose = () => setTimeout(() => subscribe(address, meta), 2000);
  ws.onerror = () => ws.close();
}

async function main(): Promise<void> {
  const address = await findPool();
  const acct = await rpc.getAccountInfo(address, { encoding: "base64", commitment: "confirmed" }).send();
  if (!acct.value) throw new Error(`no account at ${address}`);
  const data = Buffer.from(acct.value.data[0], "base64");
  const dec = getAddressDecoder();
  const mintA = dec.decode(data.subarray(101, 133));
  const mintB = dec.decode(data.subarray(181, 213));
  const mints = await rpc.getMultipleAccounts([mintA, mintB], { encoding: "base64" }).send();
  const [decA, decB] = mints.value.map((m) => (m ? Buffer.from(m.data[0], "base64")[44] : 0));
  const meta: Meta = { mintA, mintB, decA, decB };
  const first = read(data, meta);
  console.log(`pool ${address} slot ${acct.context.slot} tick ${first.tick} price ${first.price} ${short(mintB)} per ${short(mintA)}`);
  subscribe(address, meta);
}

main().catch((e: unknown) => {
  console.error("failed:", e instanceof Error ? e.message : e);
  process.exit(1);
});
```

Pass a pool address as the first argument to skip the search. The search reads the newest transactions that name the program. A pool whose address sits in a lookup table does not appear in the account list it checks, so pass that pool directly. For a view that must match a snapshot exactly, [snapshot plus subscription sync](https://carbium.sh/library/howsolana/snapshot-plus-subscription-sync) shows the pattern of reading once and then following changes.

## What it costs

The subscription is billed in credits. An account subscription opens at 25 credits, then costs 20 credits per MiB sent. The figures below are the subscription's share, and the startup reads are one time.

Each update carries the whole account, so assume 1 KiB per notification. A pool whose state changes in every slot gets about five updates a second, since a slot is about 200 ms now. That is about 18,000 notifications an hour, or about 17.6 MiB, which comes to about 380 credits with the opening charge. The monitor prints the real MiB total, so check it against that figure.

| Plan | Credits | Subscription credits in one hour at five updates a second |
|---|---|---|
| Free ($0) | 500K once, at sign-up | about 380, about 0.08% of the grant |
| Dev ($20) | 10M per month | about 380, about 0.004% of the month |
| Business ($250) | 50M per month | about 380, about 0.0008% of the month |
| Pro ($500) | 200M per month | about 380, about 0.0002% of the month |

The startup reads are one search of up to ten transactions, each with one getTransaction at 50 cells and one getMultipleAccounts over its account keys at 10 cells per key. Then come one getAccountInfo for the pool and one getMultipleAccounts for the mints. The search waits 4.2 seconds between transactions, which keeps it under the 0.24 req/s that getTransaction allows on Free. The Free plan carries 5 sockets, and this monitor uses one.

## Where it ends

- The stream shows the pool's state after each change. It does not list the individual swaps that caused the change.
- A notification shows the account at a slot. Several changes inside one slot reach the stream as one state, the last one.
- The offsets belong to one layout. Another concentrated-liquidity program keeps its price elsewhere, and the code checks only the owner and the account size.
- The search reads the newest signatures of one program, so a pool that never appears in those transactions is not found. Pass its address.
- The price is the spot price in the pool's state. A quote for a given amount also depends on fees and on the liquidity in each tick the amount crosses, and this stream does not compute that. The [quote method](https://carbium.sh/docs/quote) answers that question on the RPC endpoint.
- The stream starts when you subscribe. getSignaturesForAddress reaches back 30 days at most, so older prices are yours to store as you go.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The search prints 'no pool found', or a 429 appears in its skip lines. | Pass the pool address as the first argument. On Free the search waits 4.2 seconds between transactions. A 429 carries a retry-after hint, so wait that long and run again. |
| The starting line shows a zero decimal value, or the pool read is null. | The address is not a pool of this layout, or it has closed. Check that its owner is the program and its data is 653 bytes. |
| The subscribe reply says 'subscribe refused'. | Check the key and that the account is under its socket cap, since Free carries 5 sockets. A refused subscription costs nothing, so a retry is free. |
| The printed price is off by a power of ten, or the two tokens look swapped. | Decimals come from byte 44 of each mint, and the price is always token B per token A. Confirm the mint order at offsets 101 and 181 against the pool's own mints. |
| Credits run faster than the table. | Read the MiB line and check the address. A token account or other busy account updates on every transfer into it, and that is what the subscription pays for. |
| Prices stop after a network drop, and the first line after reconnect is late. | The stream sends the account only when it changes, so a quiet pool stays silent after a reconnect. Read the pool with getAccountInfo to fill the gap. |

## Questions

### Can I get the price without a WebSocket?

Yes, by reading the pool with getAccountInfo on an interval. Each read costs 10 cells and shows only the state at that moment, so a busy pool will show gaps. The subscription sends every change and nothing between changes.

### Why is the price token B per token A?

The pool stores the square root of the price of token A in token B. The code squares the root and keeps that order, so the output reads as B per A. To print the other way, invert the number or swap the mints.

### Does this stream give a quote for an amount?

No. It shows the spot price in the pool's state. A quote for an amount depends on fees and on liquidity across the ticks that amount crosses, and the [quote method](https://carbium.sh/docs/quote) answers that on the RPC endpoint.

### Can I run this on the Free plan?

Yes, for one pool. The startup reads come to a few hundred cells, the stream uses one of five sockets, and a pool at five updates a second costs about 380 credits an hour. The 500K grant covers more than a thousand hours of that.

## Related

- [Snapshot plus subscription sync](https://carbium.sh/library/howsolana/snapshot-plus-subscription-sync) (How to use Solana, HS0116)
- [Token price alerts](https://carbium.sh/library/blockchainideas/token-price-alerts) (Blockchain ideas, BI0025)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/quote](https://carbium.sh/docs/quote)
