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

# Subscribing to Events

> Learn how to subscribe to events in the Solana network.

Websockets provide an interface where you can listen for certain events. Instead
of pinging a HTTP endpoint at an interval to get frequent updates, you can
instead receive those updates only when they happen.

<CodeGroup>

```ts Kit highlight={19-21}
import {
  createSolanaRpc,
  createSolanaRpcSubscriptions,
  generateKeyPairSigner,
  lamports,
} from "@solana/kit";

const LAMPORTS_PER_SOL = lamports(1_000_000_000n);

const rpc = createSolanaRpc("http://localhost:8899");
const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");

const wallet = await generateKeyPairSigner();

// Unsubscribe after the first notification, or after 30 seconds without one
const abortController = new AbortController();
const timeout = setTimeout(() => abortController.abort(), 30_000);

const notifications = await rpcSubscriptions
  .accountNotifications(wallet.address, { commitment: "confirmed" })
  .subscribe({ abortSignal: abortController.signal });

await rpc.requestAirdrop(wallet.address, LAMPORTS_PER_SOL).send();

for await (const notification of notifications) {
  console.log(notification);
  break;
}

clearTimeout(timeout);
abortController.abort();
```

```ts title="Web3.js v3" highlight={14-23}
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";

const connection = new Connection("http://localhost:8899", "confirmed");

const wallet = await Keypair.generate();

// Resolves on the first notification, rejects after 30 seconds without one
let subscriptionId = 0;
const notified = new Promise<void>((resolve, reject) => {
  const timeout = setTimeout(
    () => reject(new Error("No account notification within 30 seconds")),
    30_000,
  );
  subscriptionId = connection.onAccountChange(
    wallet.publicKey,
    (accountInfo, context) => {
      clearTimeout(timeout);
      console.log("Context:", context);
      console.log("AccountInfo:", accountInfo);
      resolve();
    },
    { commitment: "confirmed" },
  );
});

// Give the subscription a moment to register before the airdrop
await new Promise((resolve) => setTimeout(resolve, 1000));

await connection.requestAirdrop(wallet.publicKey, LAMPORTS_PER_SOL);

// Wait for the notification, then stop listening
try {
  await notified;
} finally {
  await connection.removeAccountChangeListener(subscriptionId);
}
```

```rust Rust
use anyhow::Result;
use solana_client::{
    nonblocking::pubsub_client::PubsubClient, nonblocking::rpc_client::RpcClient,
    rpc_config::RpcAccountInfoConfig,
};
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{native_token::LAMPORTS_PER_SOL, signature::Signer, signer::keypair::Keypair};
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> Result<()> {
    let wallet = Keypair::new();
    let pubkey = wallet.pubkey();

    let connection = RpcClient::new_with_commitment(
        "http://localhost:8899".to_string(),
        CommitmentConfig::confirmed(),
    );
    let ws_client = PubsubClient::new("ws://localhost:8900").await?;

    let subscriber = tokio::spawn(async move {
        let config = RpcAccountInfoConfig {
            commitment: Some(CommitmentConfig::confirmed()),
            encoding: None,
            data_slice: None,
            min_context_slot: None,
        };

        let (mut stream, _) = ws_client
            .account_subscribe(&pubkey, Some(config))
            .await
            .expect("Failed to subscribe to account updates");

        // Print the first notification, then finish
        if let Some(account) = stream.next().await {
            println!("{:#?}", account);
        }
    });

    // Give the subscription time to register before the airdrop
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;

    let airdrop_signature = connection
        .request_airdrop(&wallet.pubkey(), LAMPORTS_PER_SOL)
        .await?;
    loop {
        let confirmed = connection.confirm_transaction(&airdrop_signature).await?;
        if confirmed {
            break;
        }
    }

    // Wait for the subscriber to receive the notification
    subscriber.await?;
    Ok(())
}
```

```py Python
import asyncio

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solana.rpc.websocket_api import SolanaWsClient
from solders.keypair import Keypair

LAMPORTS_PER_SOL = 1_000_000_000


async def main():
    wallet = Keypair()

    async with (
        AsyncClient("http://localhost:8899") as rpc,
        SolanaWsClient("ws://localhost:8900") as websocket,
    ):
        # Returns once the server confirms the subscription
        subscription = await websocket.account_subscribe(
            pubkey=wallet.pubkey(), commitment=Confirmed
        )

        await rpc.request_airdrop(wallet.pubkey(), LAMPORTS_PER_SOL)

        # Print the first notification (or give up after 30 seconds)
        notification = await asyncio.wait_for(websocket.recv(), timeout=30)
        print(notification)

        await websocket.unsubscribe(subscription)


asyncio.run(main())
```

```go Go
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/solana-foundation/solana-go/v2"
	"github.com/solana-foundation/solana-go/v2/rpc"
	"github.com/solana-foundation/solana-go/v2/rpc/ws"
)

func main() {
	ctx := context.Background()
	client := rpc.New("http://localhost:8899")
	wsClient, err := ws.Connect(ctx, "ws://localhost:8900")
	if err != nil {
		panic(err)
	}
	defer wsClient.Close()

	wallet := solana.NewWallet()

	sub, err := wsClient.AccountSubscribe(wallet.PublicKey(), rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}
	defer sub.Unsubscribe()

	_, err = client.RequestAirdrop(ctx, wallet.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
	if err != nil {
		panic(err)
	}

	notification, err := sub.Recv(ctx)
	if err != nil {
		panic(err)
	}
	out, _ := json.MarshalIndent(notification, "", "  ")
	fmt.Println(string(out))
}
```

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

```ts title="Web3.js (legacy)" highlight={14-23}
import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";

const connection = new Connection("http://localhost:8899", "confirmed");

const wallet = Keypair.generate();

// Resolves on the first notification, rejects after 30 seconds without one
let subscriptionId = 0;
const notified = new Promise<void>((resolve, reject) => {
  const timeout = setTimeout(
    () => reject(new Error("No account notification within 30 seconds")),
    30_000,
  );
  subscriptionId = connection.onAccountChange(
    wallet.publicKey,
    (accountInfo, context) => {
      clearTimeout(timeout);
      console.log("Context:", context);
      console.log("AccountInfo:", accountInfo);
      resolve();
    },
    { commitment: "confirmed" },
  );
});

// Give the subscription a moment to register before the airdrop
await new Promise((resolve) => setTimeout(resolve, 1000));

await connection.requestAirdrop(wallet.publicKey, LAMPORTS_PER_SOL);

// Wait for the notification, then stop listening
try {
  await notified;
} finally {
  await connection.removeAccountChangeListener(subscriptionId);
}
```

</CodeGroup>
