# Solana Raydium CPMM Account Parsing

Beyond just tracking transactions, understanding the live state of Raydium's Constant Product Market Maker (CPMM) liquidity pools and their associated accounts is essential. These accounts hold critical, up-to-the-minute details about the pool's assets, configuration, and other vital metrics. This document will guide you through streaming and parsing real-time account updates for Raydium CPMM, providing immediate insights into its core liquidity mechanisms..

{% hint style="success" %}
The complete source code for this project is available on GitHub.&#x20;

* [<mark style="color:yellow;">TypeScript</mark>](https://github.com/Shyft-to/solana-defi/tree/main/Raydium/Typescript/stream_and_parse_cpmm_accounts)
* [<mark style="color:yellow;">Rust</mark>](https://github.com/Shyft-to/solana-defi/tree/main/Raydium/Rust/stream_and_parse_raydium_cp_accounts)

Please feel free to clone the repository and try it out. Additionally, you will find other relevant and useful code examples related to gRPC and streaming [<mark style="color:yellow;">here</mark>](https://github.com/Shyft-to/solana-defi).
{% endhint %}

## Step-by-Step Breakdown

This project consists of two key components:

1. Streaming Raydium CPMM Accounts via Yellowstone gRPC
2. Decoding those accounts using the program's IDL

### Streaming Accounts Using gRPC

The first step involves initializing the Solana Yellowstone Client. You can get Solana Yellowstone gRPC access from the Shyft Dashboard. Please check out our [gRPC Authentication Docs](/solana-yellowstone-grpc/docs.md#authentication) for more details.&#x20;

#### Initializing the Client

Once you have the authentication details, you can initialize the client in the following manner,

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import Client from "@triton-one/yellowstone-grpc";

const client = new Client(
  "YOUR-GRPC-ENDPOINT", //yellowstone grpc url
  "GRPC-ACCESS-TOKEN", //authentication token
  undefined
);
```

{% endtab %}

{% tab title="Rust" %}

```rust
use yellowstone_grpc_client::{GeyserGrpcClient, Interceptor}

async fn connect(&self) -> anyhow::Result<GeyserGrpcClient<impl Interceptor>> {
     GeyserGrpcClient::build_from_shared(self.endpoint.clone())? //grpc url
            .x_token(Some(self.x_token.clone()))? //grpc auth token
            .connect_timeout(Duration::from_secs(10))
            .timeout(Duration::from_secs(10))
            .tls_config(ClientTlsConfig::new().with_native_roots())?
            .max_decoding_message_size(1024 * 1024 * 1024)
            .connect()
            .await
            .map_err(Into::into)
}
```

{% endtab %}
{% endtabs %}

You can use any **Yellowstone** gRPC endpoint with this client. An access token is **optional**, as some gRPC services don't require authentication.

The Rust client supports several additional options, as demonstrated in the example above. Most of these options are also available for the TS client, where they are passed as the third argument to the `Client` constructor.

#### Specifying what data to stream from gRPC

To specify what on-chain data,  we send a `SubscribeRequest` over the existing **Solana Yellowstone gRPC** client. These Request allows you to filter for specific **accounts**, **transactions**, **slots**, or other **Solana on-chain events**, giving you full control over the data you receive.

[SubscribeRequests ](/solana-yellowstone-grpc/docs.md#what-are-subscribe-requests)use filters to determine what type of on-chain data to stream. When streaming account-level data, the <mark style="color:yellow;">account filter</mark> plays a crucial role. Specifically, the `owner` field within the filter allows you to stream data for accounts owned by a particular Solana program.

{% tabs %}
{% tab title="TypeScript" %}
{% code overflow="wrap" %}

```typescript
const req: SubscribeRequest = {
  "slots": {},
  "accounts": {
    "pumpfun": {
      "account": [],
      "filters": [],
      "owner": ["CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"] // This field indicates 
    }
  },
  "transactions": {},
  "blocks": {},
  "blocksMeta": {},
  "accountsDataSlice": [],
  "commitment": CommitmentLevel.PROCESSED, // Subscribe to processed blocks for the fastest updates
  "entry": {},
  "transactionsStatus": {}
}
```

{% endcode %}
{% endtab %}

{% tab title="Rust" %}
{% code overflow="wrap" %}

```rust
let mut accounts: AccountFilterMap = HashMap::new();

accounts.insert(
    "accountData".to_owned(),
    SubscribeRequestFilterAccounts {
        account: vec![],
        owner: vec!["CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C"],
        nonempty_txn_signature: None,
        filters: vec![]
    },
);
Ok(SubscribeRequest {
    accounts,
    slots: HashMap::default(),
    transactions: HashMap::default(),
    transactions_status: HashMap::default(),
    blocks: HashMap::default(),
    blocks_meta: HashMap::default(),
    entry: HashMap::default(),
    commitment: Some(CommitmentLevel::Processed as i32),
    accounts_data_slice: Vec::default(),
    ping: None,
    from_slot: None,
})
```

{% endcode %}
{% endtab %}
{% endtabs %}

Once established, the stream will begin sending data directly to your application. You have the flexibility to [**modify your subscription**](/solana-yellowstone-grpc/docs/getting-started/modify-grpc-subscribe-request.md) **on the fly**, allowing you to change the data specifications you receive without stopping your stream. For more details on [**reconnecting and re-starting the stream from a specific slot**](/solana-yellowstone-grpc/docs/getting-started/replaying-slots-with-grpc.md)**, or** [**closing your gRPC connection**](/solana-yellowstone-grpc/docs/getting-started/gracefully-closing-a-grpc-connection.md), you can find additional information in our [documentation](/solana-yellowstone-grpc/docs.md).

### Decoding the received accounts

When account data updates on-chain, it's immediately sent over the stream. To make sense of this raw information, we need to decode it. In JavaScript/TypeScript, we typically use `BorshAccountCoder` from <mark style="color:yellow;">`@coral-xyz/anchor`</mark> to parse the account data like this. But in cases where the IDL is not available, we define the account structure. This is one such case.

On Rust however, we can use the Solores generated IDL like in our [transaction parsing](/solana-yellowstone-grpc/examples/pumpfun/solana-grpc-pumpfun-transaction-parsing.md) example.

{% tabs %}
{% tab title="TypeScript" %}
{% code overflow="wrap" %}

```typescript

import base58 from "bs58";
import { blob, bool, i128, i64, publicKey, s32, seq, struct, u128, u16, u32, u64, u8 } from "../layout-type";
import { bnLayoutFormatter } from "./bn-layout-formatter";



export const CpPoolInfoLayout = struct([
  blob(8),

  publicKey("configId"),
  publicKey("poolCreator"),
  publicKey("vaultA"),
  publicKey("vaultB"),

  publicKey("mintLp"),
  publicKey("mintA"),
  publicKey("mintB"),

  publicKey("mintProgramA"),
  publicKey("mintProgramB"),

  publicKey("observationId"),

  u8("bump"),
  u8("status"),

  u8("lpDecimals"),
  u8("mintDecimalA"),
  u8("mintDecimalB"),

  u64("lpAmount"),
  u64("protocolFeesMintA"),
  u64("protocolFeesMintB"),
  u64("fundFeesMintA"),
  u64("fundFeesMintB"),
  u64("openTime"),

  seq(u64(), 32),
]);
export function decodeRaydiumCpPool(buffer: Buffer) {
  const cpDecode =  CpPoolInfoLayout.decode(buffer);
  bnLayoutFormatter(cpDecode);
  return cpDecode;
}

export function base64ToBase58(data: string) {
  return base58.encode(Buffer.from(data, 'base64'));
}
```

{% endcode %}
{% endtab %}

{% tab title="Rust" %}

```rust
use raydium_cp_swap_interface::{accounts::{PoolState,
            AMM_CONFIG_ACCOUNT_DISCM,
            AmmConfig,
            AmmConfigAccount,
            PoolStateAccount,
            POOL_STATE_ACCOUNT_DISCM,
            OBSERVATION_STATE_ACCOUNT_DISCM,
            ObservationState,              
            ObservationStateAccount
}};

pub fn decode_account_data(buf: &[u8]) -> Result<DecodedAccount, AccountDecodeError> {
    if buf.len() < 8 {
        return Err(AccountDecodeError {
            message: "Buffer too short to contain a valid discriminator.".to_string(),
        });
    }

    let discriminator: [u8; 8] = buf[..8].try_into().expect("Failed to extract first 8 bytes");

    match discriminator {
        POOL_STATE_ACCOUNT_DISCM => {
            let data = PoolStateAccount::deserialize(buf)
                .map_err(|e| AccountDecodeError {
                    message: format!("Failed to deserialize PoolState: {}", e),
                })?;
            println!("\nDecoded PoolState Structure: {:#?}", data);
            Ok(DecodedAccount::PoolState(data.0))
        }
        AMM_CONFIG_ACCOUNT_DISCM => {
            let data = AmmConfigAccount::deserialize(buf)
                .map_err(|e| AccountDecodeError {
                    message: format!("Failed to deserialize AmmConfig: {}", e),
                })?;
            println!("\nDecoded AmmConfig Structure: {:#?}", data);
            Ok(DecodedAccount::AmmConfig(data.0))
        }
        _ => Err(AccountDecodeError {
            message: "Account discriminator not found.".to_string(),
        }),
    }
}
```

{% endtab %}
{% endtabs %}

### Important Links

* [**Solana gRPC Documentation**](/solana-yellowstone-grpc/docs.md) – In-depth technical docs for implementing real-time streaming with **Yellowstone gRPC** and **Geyser plugin** on Solana.
* [**Blogs on Solana gRPC Streaming**](https://blogs.shyft.to/) – Guides, use cases, and performance benchmarks for building **low-latency Solana applications** using **gRPC-based infrastructure**.
* [**Solana DeFi Code Snippets & Examples**](https://github.com/Shyft-to/solana-defi/) – Ready-to-use code snippets and integrations for common **DeFi protocols**, **transaction parsers**, and **real-time Solana data streaming** use cases.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.shyft.to/solana-yellowstone-grpc/examples/raydium-cpmm/streaming-and-parsing-accounts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
