# Detect Buy/Sell Transaction Type on Pump AMM

In the rapid Solana memecoin market, instantly knowing about buy and sell events on Pump AMM offers a crucial edge for traders and analysts. This guide explains how to leverage Solana's Yellowstone gRPC stream to capture and parse live transaction data, ensuring you detect token swaps the moment they happen.

{% 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/PumpFun/Typescript/stream_pump_fun_transactions_and_detect_buy_sell_events)
* [<mark style="color:yellow;">Rust</mark>](https://github.com/Shyft-to/solana-defi/tree/main/PumpFun/Rust/stream_pump_swap_amm_transactions_and_detect_buy_sell_events)

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 Pump.fun Transactions via Yellowstone gRPC
2. Parsing the Received transactions along with events
3. Identifying Buy / Sell transactions based on the Pump Events

### Streaming Transactions 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. You can find out more about [Subscribe Requests](https://docs.shyft.to/docs#what-are-subscribe-requests) here.&#x20;

Subscribe Requests specify what data to stream by the means of filters. When you want to stream **transactions**, you use a **transaction filter**. Inside this filter, you tell it which **program's transactions** you're interested in by providing its **"program ID"** in the **"account" field**. The example below demonstrates how to initiate a gRPC stream by sending a `SubscribeRequest` using a standard gRPC client:

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

```typescript
const req: SubscribeRequest = {
  accounts: {},
  slots: {},
  transactions: {
    pumpFun: {
      vote: false,
      failed: false,
      signature: undefined,
      accountInclude: ["pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"],
      //for our usecase we only need to listen to transaction belonging to one program, so we have added one address
      accountExclude: [],
      accountRequired: [],
    },
  },
  transactionsStatus: {},
  entry: {},
  blocks: {},
  blocksMeta: {},
  accountsDataSlice: [],
  ping: undefined,
  commitment: CommitmentLevel.CONFIRMED,
};
```

{% endcode %}
{% endtab %}

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

```rust
transactions.insert(
   "client".to_owned(),
   SubscribeRequestFilterTransactions {
        vote: Some(false),
        failed: Some(false),
        account_include: vec!["pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA"], 
        //for our usecase we only need to listen to transaction belonging to one program
        account_exclude: vec![],
        account_required: vec![],
        signature: None,
   }
 );
```

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

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).

### Parsing the received transaction

Once a raw Solana transaction is received via the Yellowstone gRPC stream, it must be parsed to extract meaningful, human-readable data. For JavaScript/TypeScript applications, we use [**Shyft's IDL-based transaction parser**](https://www.npmjs.com/package/@shyft-to/solana-transaction-parser), which decodes the transactions received from the gRPC into structured data based on the respective **program's IDL**. On Rust however, we use a interface generated by [solores](https://crates.io/crates/solores) to parse the transaction instruction.&#x20;

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

```typescript
import { SolanaParser } from "@shyft-to/solana-transaction-parser";

const PUMP_FUN_IX_PARSER = new SolanaParser([]);
//initializing the parser

PUMP_FUN_AMM_IX_PARSER.addParserFromIdl(
  "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA",
  pumpFunAmmIdl as Idl
);

const PUMP_FUN_AMM_EVENT_PARSER = new SolanaEventParser([], console);
PUMP_FUN_EVENT_PARSER.addParserFromIdl(
  "pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA",
  pumpFunAmmIdl as Idl
);
//adding pump.fun idl for parsing pumpfun transactions

function decodePumpFunTxn(tx: VersionedTransactionResponse) {
  if (tx.meta?.err) return;
  try{
    const paredIxs = PUMP_FUN_AMM_IX_PARSER.parseTransactionData(
      tx.transaction.message,
      tx.meta.loadedAddresses,
    ); //parsing transaction
  
    const pumpFunIxs = paredIxs.filter((ix) =>
      ix.programId.equals(PUMP_FUN_AMM_PROGRAM_ID) || ix.programId.equals(new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")),
    );
  
    const parsedInnerIxs = PUMP_FUN_AMM_IX_PARSER.parseTransactionWithInnerInstructions(tx);
  
    const pumpfun_amm_inner_ixs = parsedInnerIxs.filter((ix) =>
      ix.programId.equals(PUMP_FUN_AMM_PROGRAM_ID) || ix.programId.equals(new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")),
    ); //parsing inner instructions


    if (pumpFunIxs.length === 0) return;
    const events = PUMP_FUN_AMM_EVENT_PARSER.parseEvent(tx);
    
    const result = { instructions: pumpFunIxs, inner_ixs: pumpfun_amm_inner_ixs, events };
   
    return result;
  }catch(err){
    console.log(err);
  }
}

```

{% endtab %}

{% tab title="Rust" %}

```rust
message: VersionedMessage::V0(
    Message {
        //....shortend for visibility
        instructions: raw_message
            .instructions
            .iter()
            .map(|ix| CompiledInstruction {
                program_id_index: ix.program_id_index as u8,
                accounts: ix.accounts.clone(),
                data: ix.data.clone(),
            })
            .collect(),
        address_table_lookups:
            raw_message
                .address_table_lookups
                .iter()
                .map(|l| MessageAddressTableLookup {
                    account_key: Pubkey::new_from_array(l.account_key.clone().try_into().expect("Failed to convert Vec<u8> to [u8; 32]")),
                    writable_indexes: l.writable_indexes.clone(),
                    readonly_indexes: l.readonly_indexes.clone(),
                })
                .collect(),
    }
),
},
meta: TransactionStatusMeta {
status: Result::Ok(()),
fee: meta.fee,
pre_balances: meta.pre_balances.clone(),
post_balances: meta.post_balances.clone(),
inner_instructions: Some(
    meta.inner_instructions.iter().map(|f| {
        InnerInstructions {
            index: f.index as u8,
            instructions: f.instructions.iter().map(|v| {
                InnerInstruction {
                    instruction: CompiledInstruction {
                        program_id_index: v.program_id_index as u8,
                        accounts: v.accounts.clone(),
                        data: v.data.clone(),
                    },
                    stack_height: Some(v.stack_height.unwrap()),
                }
            }).collect(),
        }
    }).collect()
),
```

{% endtab %}
{% endtabs %}

### Detecting Buy/Sell Events

Once a valid Pump Swap AMM transaction is identified and decoded, `transactionOutput(parsedTxn)` extracts key details about the buy or sell event, such as:

* **`TYPE`**: Whether it was a "buy" or "sell" action.
* **`MINT`**: The token's address involved in the swap.
* **`SIGNER`**: The **wallet address** that initiated the transaction (the buyer or seller).
* **`TOKEN AMOUNT`**: How much of the specific token was bought or sold.
* **`SOL AMOUNT`**: The amount of SOL exchanged in the transaction.
* **`SIGNATURE`**: The unique transaction signature, which can be used to view the transaction on a **Solana block explorer**.

Finally, these critical details are printed to the console in a clear, readable format, providing **instant alerts** for every **buy and sell event** occurring on **Pump.fun**. This allows **traders** and **bots** to react swiftly to **market movements** and **liquidity changes**.

### 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.
