# Solana Raydium AMM Account Parsing

To truly understand Raydium AMM, you need to see what's happening with its accounts and liquidity pools right now. This guide shows you how to get **live updates from these accounts using Solana gRPC**, and then how to **read that data clearly** to see what's going on.

{% 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_all_raydium_accounts)
* [<mark style="color:yellow;">Rust</mark>](https://github.com/Shyft-to/solana-defi/tree/main/Raydium/Rust/stream_and_parse_raydium_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 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](https://docs.shyft.to/docs#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 ](https://docs.shyft.to/docs#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": ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"] // 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!["pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"],
        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 %}

For example, to stream Raydium accounts, you can set the `owner` field to the Raydium AMM program ID. This ensures that only accounts associated with the Raydium program are streamed in real-time—ideal for use cases like crypto trading bots, on-chain analytics, or DeFi dashboards requiring program-specific data.

Once established, the stream will begin sending data directly to your application. You have the flexibility to [**modify your subscription**](https://docs.shyft.to/solana-yellowstone-grpc/docs/getting-started/modify-grpc-subscribe-request) **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**](https://docs.shyft.to/solana-yellowstone-grpc/docs/getting-started/replaying-slots-with-grpc)**, or** [**closing your gRPC connection**](https://docs.shyft.to/solana-yellowstone-grpc/docs/getting-started/gracefully-closing-a-grpc-connection), you can find additional information in our [documentation](https://docs.shyft.to/solana-yellowstone-grpc/docs).

### 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](https://docs.shyft.to/solana-yellowstone-grpc/examples/pumpfun/solana-grpc-pumpfun-transaction-parsing) example.

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

```typescript
const accountCoder = struct([
  u64('status'),
  u64('nonce'),
  u64('maxOrder'),
  u64('depth'),
  u64('baseDecimal'),
  u64('quoteDecimal'),
  u64('state'),
  u64('resetFlag'),
  u64('minSize'),
  u64('volMaxCutRatio'),
  u64('amountWaveRatio'),
  u64('baseLotSize'),
  u64('quoteLotSize'),
  u64('minPriceMultiplier'),
  u64('maxPriceMultiplier'),
  u64('systemDecimalValue'),
  u64('minSeparateNumerator'),
  u64('minSeparateDenominator'),
  u64('tradeFeeNumerator'),
  u64('tradeFeeDenominator'),
  u64('pnlNumerator'),
  u64('pnlDenominator'),
  u64('swapFeeNumerator'),
  u64('swapFeeDenominator'),
  u64('baseNeedTakePnl'),
  u64('quoteNeedTakePnl'),
  u64('quoteTotalPnl'),
  u64('baseTotalPnl'),
  u64('poolOpenTime'),
  u64('punishPcAmount'),
  u64('punishCoinAmount'),
  u64('orderbookToInitTime'),
  // u128('poolTotalDepositPc'),
  // u128('poolTotalDepositCoin'),
  u128('swapBaseInAmount'),
  u128('swapQuoteOutAmount'),
  u64('swapBase2QuoteFee'),
  u128('swapQuoteInAmount'),
  u128('swapBaseOutAmount'),
  u64('swapQuote2BaseFee'),
  // amm vault
  publicKey('baseVault'),
  publicKey('quoteVault'),
  // mint
  publicKey('baseMint'),
  publicKey('quoteMint'),
  publicKey('lpMint'),
  // market
  publicKey('openOrders'),
  publicKey('marketId'),
  publicKey('marketProgramId'),
  publicKey('targetOrders'),
  publicKey('withdrawQueue'),
  publicKey('lpVault'),
  publicKey('owner'),
  // true circulating supply without lock up
  u64('lpReserve'),
  seq(u64(), 3, 'padding'),
])

const decodedData = accountCoder.decode(data.account.account.data); //decode received data
```

{% endcode %}
{% endtab %}

{% tab title="Rust" %}

```rust
use raydium_amm_interface::{accounts::{AmmInfo, Fees, TargetOrders};

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

    let data = AmmInfo::try_from_slice(buf)
    .map_err(|e| AccountDecodeError {
        message: format!("Failed to deserialize AmmInfoAccount: {}", e),
    })?;
    println!("\nDecoded Amm Info Structure: {:#?}", data);
    Ok(DecodedAccount::AmmInfo(data))

}
```

{% endtab %}
{% endtabs %}

### Important Links

* [**Solana gRPC Documentation**](https://docs.shyft.to/solana-yellowstone-grpc/docs) – 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.
