> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# programSubscribe

> Subscribe to notifications for accounts owned by a given program.

<Info>
  **Source**

  [`program_subscribe`](https://github.com/anza-xyz/agave/blob/v4.3.2/rpc/src/rpc_pubsub.rs#L452)
</Info>

<RequestExample>
  ```json WebSocket
  {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "programSubscribe",
    "params": [
      "11111111111111111111111111111111",
      {
        "encoding": "base64",
        "filters": [{ "dataSize": 80 }]
      }
    ]
  }
  ```

  ```ts Kit
  import { address, createSolanaRpcSubscriptions } from "@solana/kit";

  const rpc = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");

  const subscription = await rpc
    .programNotifications(address("11111111111111111111111111111111"), {
      encoding: "base64",
      filters: [{ dataSize: 80n }]
    })
    .subscribe({ abortSignal: AbortSignal.timeout(5_000) });

  for await (const notification of subscription) {
    console.log(notification);
  }
  ```

  ```ts web3.js
  import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js";

  const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

  const programId = new PublicKey("11111111111111111111111111111111");

  const subscriptionId = connection.onProgramAccountChange(
    programId,
    (keyedAccountInfo, context) => {
      console.log("Account changed:", keyedAccountInfo);
      console.log("Context:", context);
    },
    "finalized",
    [{ dataSize: 80 }]
  );
  ```

  ```rs Rust
  use anyhow::Result;
  use futures::StreamExt;
  use solana_account_decoder::UiAccountEncoding;
  use solana_client::{
      nonblocking::pubsub_client::PubsubClient, rpc_config::RpcProgramAccountsConfig,
      rpc_filter::RpcFilterType,
  };
  use solana_commitment_config::CommitmentConfig;
  use solana_sdk::pubkey::Pubkey;
  use std::str::FromStr;

  #[tokio::main]
  async fn main() -> Result<()> {
      let pubsub_client = PubsubClient::new("wss://api.devnet.solana.com/").await?;

      let program_id = Pubkey::from_str("11111111111111111111111111111111")?;

      let config = RpcProgramAccountsConfig {
          filters: Some(vec![RpcFilterType::DataSize(80)]),
          account_config: solana_client::rpc_config::RpcAccountInfoConfig {
              encoding: Some(UiAccountEncoding::Base64),
              commitment: Some(CommitmentConfig::finalized()),
              ..Default::default()
          },
          ..Default::default()
      };

      let (mut notifications, unsubscribe) = pubsub_client
          .program_subscribe(&program_id, Some(config))
          .await?;

      while let Some(notification) = notifications.next().await {
          println!("{:?}", notification);
      }

      unsubscribe().await;

      Ok(())
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Response
  {
    "jsonrpc": "2.0",
    "result": 24040,
    "id": 1
  }
  ```
</ResponseExample>

## Parameters

<ParamField body="0" type="string" required>
  Pubkey of the `program_id`, as base-58 encoded string
</ParamField>

<ParamField body="1" type="object">
  Optional configuration object.

  <Expandable title="properties" defaultOpen>
    <ParamField body="commitment" type="string" default="finalized">
      Values: `processed`, `confirmed`, `finalized`

      The commitment describes how finalized a block is at that point in time. See
      [Configuring State Commitment](/developers/docs/rpc#configuring-state-commitment).
    </ParamField>

    <ParamField body="filters" type="array">
      Filter results using up to 4 filter objects. See
      [Filtering](/developers/docs/rpc/http/getprogramaccounts#param-filters). All filters must match for a given
      account to be included.

      <Info>
        The node validates and optimizes the supplied filters before the subscription
        is created.
      </Info>
    </ParamField>

    <ParamField body="encoding" type="string" default="binary">
      Values: `base58`, `base64`, `base64+zstd`, `binary`, `jsonParsed`

      Encoding format for account data.

      - `base58` is slow.
      - `jsonParsed` encoding attempts to use program-specific state parsers to return
        more human-readable and explicit account state data.
      - If `jsonParsed` is requested but no parser is available, the RPC node falls
        back to `[data, "base64"]`.
      - `binary` is a deprecated legacy alias for base58 data returned as a plain
        string.
    </ParamField>

    <ParamField body="dataSlice" type="object">
      Request a slice of each returned account's data.

      | Field    | Type    | Description                                           |
      | -------- | ------- | ----------------------------------------------------- |
      | `offset` | `usize` | Byte offset from which to start reading account data. |
      | `length` | `usize` | Number of bytes to return.                            |

      <Info>
        Data slicing is only available for `base58`, `base64`, `base64+zstd`, and
        `binary` encodings.
      </Info>

      <Info>
        `base58` and `binary` use base-58 encoding and fail if the selected payload is
        more than 128 bytes after slicing. Use `base64` for larger accounts.
      </Info>
    </ParamField>

    <ParamField body="withContext" type="bool" default="false">
      Values: `true`, `false`

      Accepted for compatibility.

      <Info>
        Unlike [getProgramAccounts](/developers/docs/rpc/http/getprogramaccounts),
        `programNotification` messages already include `context`. `withContext`,
        `minContextSlot`, and `sortResults` are accepted for compatibility, but PubSub
        subscriptions do not currently change behavior based on those fields.
      </Info>
    </ParamField>
  </Expandable>
</ParamField>

## Result

<ResponseField name="result" type="integer">
  Subscription id. Pass this to
  [programUnsubscribe](/developers/docs/rpc/websocket/programunsubscribe).
</ResponseField>

## Notification format

Notifications are delivered as `programNotification`.

```json
{
  "jsonrpc": "2.0",
  "method": "programNotification",
  "params": {
    "result": {
      "context": {
        "slot": 583
      },
      "value": {
        "pubkey": "BpdYYo2Vw1NVbzE2DqJxCX2xEfr42xvMYFU2dKd1CW57",
        "account": {
          "lamports": 499997095000,
          "data": ["", "base64"],
          "owner": "11111111111111111111111111111111",
          "executable": false,
          "rentEpoch": 18446744073709551615,
          "space": 0
        }
      }
    },
    "subscription": 11
  }
}
```

<ResponseField name="jsonrpc" type="string">
  Always `"2.0"`.
</ResponseField>

<ResponseField name="method" type="string">
  Always `"programNotification"`.
</ResponseField>

<ResponseField name="params" type="object">
  Notification wrapper with a single matching account and the subscription id.

  <Expandable title="properties" defaultOpen>
    <ResponseField name="result" type="object">
      Notification result object with `context` and `value`. For PubSub notifications,
      `context` includes `slot` and omits `apiVersion`.

      <Expandable title="properties">
        <ResponseField name="context" type="object">
          Context for the bank slot that produced the notification.

          <Expandable title="properties">
            <ResponseField name="slot" type="u64">
              Slot associated with the notification.
            </ResponseField>
          </Expandable>
        </ResponseField>

        <ResponseField name="value" type="object">
          Single matching account returned for the subscription.

          <Expandable title="properties">
            <ResponseField name="pubkey" type="string">
              Address of the matching account, as a base-58 encoded string.
            </ResponseField>

            <ResponseField name="account" type="object">
              Account data using the same structure documented in
              [Account Data](/developers/docs/rpc/json-structures#account-data).
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="subscription" type="integer">
      Subscription id that produced this notification.
    </ResponseField>
  </Expandable>
</ResponseField>
