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();
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);
}
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(())
}
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())
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))
}
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide 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.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);
}