0
# RPC Communication
1
2
Complete RPC API client with support for all Solana RPC methods, real-time subscriptions, and cluster management for blockchain interactions.
3
4
## Capabilities
5
6
### RPC Client Creation
7
8
Create clients for communicating with Solana RPC endpoints.
9
10
```typescript { .api }
11
/**
12
* Create a Solana RPC client for standard HTTP requests
13
* @param url - RPC endpoint URL
14
* @param config - Optional configuration
15
* @returns RPC client instance with all Solana methods
16
*/
17
function createSolanaRpc<TCluster = void>(
18
url: string,
19
config?: RpcConfig
20
): Rpc<SolanaRpcMethods> & { '~cluster'?: TCluster };
21
22
/**
23
* Create a Solana RPC subscriptions client for WebSocket connections
24
* @param url - WebSocket RPC endpoint URL
25
* @param config - Optional configuration
26
* @returns Subscriptions client for real-time data
27
*/
28
function createSolanaRpcSubscriptions<TCluster = void>(
29
url: string,
30
config?: RpcSubscriptionsConfig
31
): RpcSubscriptions<SolanaRpcSubscriptionsMethods> & { '~cluster'?: TCluster };
32
```
33
34
**Usage Examples:**
35
36
```typescript
37
import { createSolanaRpc, createSolanaRpcSubscriptions } from "@solana/web3.js";
38
39
// Create RPC client
40
const rpc = createSolanaRpc("https://api.devnet.solana.com");
41
42
// Create subscriptions client
43
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
44
45
// Use with cluster typing
46
const mainnetRpc = createSolanaRpc<"mainnet">("https://api.mainnet-beta.solana.com");
47
```
48
49
### Core Account Methods
50
51
Fetch and query account information from the blockchain.
52
53
```typescript { .api }
54
/**
55
* Get account information for a specific address
56
*/
57
interface GetAccountInfoApi {
58
getAccountInfo(
59
address: Address,
60
config?: GetAccountInfoConfig
61
): RpcRequest<AccountInfo | null>;
62
}
63
64
/**
65
* Get multiple accounts in a single request
66
*/
67
interface GetMultipleAccountsApi {
68
getMultipleAccounts(
69
addresses: Address[],
70
config?: GetMultipleAccountsConfig
71
): RpcRequest<(AccountInfo | null)[]>;
72
}
73
74
/**
75
* Get program accounts that match specified criteria
76
*/
77
interface GetProgramAccountsApi {
78
getProgramAccounts<T>(
79
programId: Address,
80
config?: GetProgramAccountsConfig
81
): RpcRequest<RpcProgramAccount<T>[]>;
82
}
83
```
84
85
**Usage Examples:**
86
87
```typescript
88
import { createSolanaRpc, address } from "@solana/web3.js";
89
90
const rpc = createSolanaRpc("https://api.devnet.solana.com");
91
92
// Get single account
93
const accountInfo = await rpc
94
.getAccountInfo(address("11111111111111111111111111111112"))
95
.send();
96
97
// Get multiple accounts
98
const multipleAccounts = await rpc
99
.getMultipleAccounts([
100
address("11111111111111111111111111111112"),
101
address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
102
])
103
.send();
104
105
// Get program accounts
106
const tokenAccounts = await rpc
107
.getProgramAccounts(
108
address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
109
{
110
filters: [
111
{ dataSize: 165 }, // Token account size
112
{ memcmp: { offset: 32, bytes: "your-owner-address" } }
113
]
114
}
115
)
116
.send();
117
```
118
119
### Balance and Token Methods
120
121
Query account balances and token information.
122
123
```typescript { .api }
124
/**
125
* Get the SOL balance of an account
126
*/
127
interface GetBalanceApi {
128
getBalance(
129
address: Address,
130
config?: CommitmentConfig
131
): RpcRequest<Lamports>;
132
}
133
134
/**
135
* Get token account balance for an SPL Token account
136
*/
137
interface GetTokenAccountBalanceApi {
138
getTokenAccountBalance(
139
address: Address,
140
config?: CommitmentConfig
141
): RpcRequest<RpcTokenAccountBalance>;
142
}
143
144
/**
145
* Get token accounts by owner
146
*/
147
interface GetTokenAccountsByOwnerApi {
148
getTokenAccountsByOwner(
149
owner: Address,
150
filter: TokenAccountsFilter,
151
config?: GetTokenAccountsConfig
152
): RpcRequest<RpcTokenAccount[]>;
153
}
154
155
/**
156
* Get token accounts by delegate
157
*/
158
interface GetTokenAccountsByDelegateApi {
159
getTokenAccountsByDelegate(
160
delegate: Address,
161
filter: TokenAccountsFilter,
162
config?: GetTokenAccountsConfig
163
): RpcRequest<RpcTokenAccount[]>;
164
}
165
```
166
167
**Usage Examples:**
168
169
```typescript
170
import { createSolanaRpc, address } from "@solana/web3.js";
171
172
const rpc = createSolanaRpc("https://api.devnet.solana.com");
173
174
// Get SOL balance
175
const balance = await rpc.getBalance(address("your-address")).send();
176
console.log("Balance:", balance.value);
177
178
// Get token accounts by owner
179
const tokenAccounts = await rpc.getTokenAccountsByOwner(
180
address("owner-address"),
181
{ programId: address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA") }
182
).send();
183
```
184
185
### Block and Transaction Methods
186
187
Query blockchain blocks and transaction information.
188
189
```typescript { .api }
190
/**
191
* Get latest blockhash for transaction creation
192
*/
193
interface GetLatestBlockhashApi {
194
getLatestBlockhash(config?: CommitmentConfig): RpcRequest<{
195
blockhash: Blockhash;
196
lastValidBlockHeight: bigint;
197
}>;
198
}
199
200
/**
201
* Get block information by slot
202
*/
203
interface GetBlockApi {
204
getBlock(
205
slot: Slot,
206
config?: GetBlockConfig
207
): RpcRequest<Block | null>;
208
}
209
210
/**
211
* Get transaction details by signature
212
*/
213
interface GetTransactionApi {
214
getTransaction(
215
signature: Signature,
216
config?: GetTransactionConfig
217
): RpcRequest<Transaction | null>;
218
}
219
220
/**
221
* Get signature statuses for multiple transactions
222
*/
223
interface GetSignatureStatusesApi {
224
getSignatureStatuses(
225
signatures: Signature[],
226
config?: { searchTransactionHistory?: boolean }
227
): RpcRequest<(SignatureStatus | null)[]>;
228
}
229
```
230
231
### Transaction Sending
232
233
Send transactions to the blockchain network.
234
235
```typescript { .api }
236
/**
237
* Send a transaction to the network
238
*/
239
interface SendTransactionApi {
240
sendTransaction(
241
transaction: string | Uint8Array,
242
config?: SendTransactionConfig
243
): RpcRequest<Signature>;
244
}
245
246
/**
247
* Simulate a transaction before sending
248
*/
249
interface SimulateTransactionApi {
250
simulateTransaction(
251
transaction: string | Uint8Array,
252
config?: SimulateTransactionConfig
253
): RpcRequest<SimulateTransactionResult>;
254
}
255
```
256
257
**Usage Examples:**
258
259
```typescript
260
import {
261
createSolanaRpc,
262
compileTransaction,
263
createTransactionMessage
264
} from "@solana/web3.js";
265
266
const rpc = createSolanaRpc("https://api.devnet.solana.com");
267
268
// Get recent blockhash
269
const { value: { blockhash } } = await rpc.getLatestBlockhash().send();
270
271
// Create and send transaction
272
const transaction = compileTransaction(
273
createTransactionMessage({
274
version: 0,
275
feePayer: myAddress,
276
blockhash,
277
instructions: [/* your instructions */]
278
})
279
);
280
281
// Simulate first
282
const simulation = await rpc.simulateTransaction(transaction).send();
283
if (simulation.value.err) {
284
console.error("Transaction would fail:", simulation.value.err);
285
return;
286
}
287
288
// Send transaction
289
const signature = await rpc.sendTransaction(transaction).send();
290
console.log("Transaction sent:", signature);
291
```
292
293
### Network and Cluster Methods
294
295
Query network status and cluster information.
296
297
```typescript { .api }
298
/**
299
* Get information about the current epoch
300
*/
301
interface GetEpochInfoApi {
302
getEpochInfo(config?: CommitmentConfig): RpcRequest<RpcEpochInfo>;
303
}
304
305
/**
306
* Get the cluster nodes information
307
*/
308
interface GetClusterNodesApi {
309
getClusterNodes(): RpcRequest<RpcClusterNode[]>;
310
}
311
312
/**
313
* Get the health status of the node
314
*/
315
interface GetHealthApi {
316
getHealth(): RpcRequest<"ok">;
317
}
318
319
/**
320
* Get the current version of the node
321
*/
322
interface GetVersionApi {
323
getVersion(): RpcRequest<RpcVersionInfo>;
324
}
325
326
/**
327
* Get current slot the node is processing
328
*/
329
interface GetSlotApi {
330
getSlot(config?: CommitmentConfig): RpcRequest<Slot>;
331
}
332
333
/**
334
* Get the current slot leader
335
*/
336
interface GetSlotLeaderApi {
337
getSlotLeader(config?: CommitmentConfig): RpcRequest<Address>;
338
}
339
```
340
341
**Usage Examples:**
342
343
```typescript
344
import { createSolanaRpc } from "@solana/web3.js";
345
346
const rpc = createSolanaRpc("https://api.devnet.solana.com");
347
348
// Get current epoch information
349
const epochInfo = await rpc.getEpochInfo().send();
350
console.log("Current epoch:", epochInfo.value.epoch);
351
352
// Check node health
353
const health = await rpc.getHealth().send();
354
console.log("Node health:", health.value); // "ok"
355
356
// Get current slot
357
const slot = await rpc.getSlot().send();
358
console.log("Current slot:", slot.value);
359
```
360
361
### Fee and Economics Methods
362
363
Query fee information and network economics.
364
365
```typescript { .api }
366
/**
367
* Get fee for a transaction message
368
*/
369
interface GetFeeForMessageApi {
370
getFeeForMessage(
371
message: TransactionMessage,
372
config?: CommitmentConfig
373
): RpcRequest<Lamports | null>;
374
}
375
376
/**
377
* Get recent prioritization fees
378
*/
379
interface GetRecentPrioritizationFeesApi {
380
getRecentPrioritizationFees(
381
addresses?: Address[]
382
): RpcRequest<RpcPrioritizationFee[]>;
383
}
384
385
/**
386
* Get minimum balance for rent exemption
387
*/
388
interface GetMinimumBalanceForRentExemptionApi {
389
getMinimumBalanceForRentExemption(
390
dataLength: number,
391
config?: CommitmentConfig
392
): RpcRequest<Lamports>;
393
}
394
```
395
396
**Usage Examples:**
397
398
```typescript
399
import { createSolanaRpc } from "@solana/web3.js";
400
401
const rpc = createSolanaRpc("https://api.devnet.solana.com");
402
403
// Get recent prioritization fees
404
const fees = await rpc.getRecentPrioritizationFees().send();
405
console.log("Recent fees:", fees.value);
406
407
// Get rent exemption minimum
408
const rentExemption = await rpc.getMinimumBalanceForRentExemption(0).send();
409
console.log("Rent exemption for 0 bytes:", rentExemption.value);
410
```
411
412
### Subscription Methods
413
414
Real-time data streaming via WebSocket connections.
415
416
```typescript { .api }
417
/**
418
* Subscribe to account changes
419
*/
420
interface AccountNotificationsApi {
421
accountNotifications(
422
address: Address,
423
config?: AccountNotificationsConfig
424
): RpcSubscription<AccountNotification>;
425
}
426
427
/**
428
* Subscribe to signature status changes
429
*/
430
interface SignatureNotificationsApi {
431
signatureNotifications(
432
signature: Signature,
433
config?: SignatureNotificationsConfig
434
): RpcSubscription<SignatureNotification>;
435
}
436
437
/**
438
* Subscribe to slot changes
439
*/
440
interface SlotNotificationsApi {
441
slotNotifications(): RpcSubscription<SlotNotification>;
442
}
443
444
/**
445
* Subscribe to program account changes
446
*/
447
interface ProgramNotificationsApi {
448
programNotifications(
449
programId: Address,
450
config?: ProgramNotificationsConfig
451
): RpcSubscription<ProgramAccountNotification>;
452
}
453
```
454
455
**Usage Examples:**
456
457
```typescript
458
import { createSolanaRpcSubscriptions, address } from "@solana/web3.js";
459
460
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
461
462
// Subscribe to account changes
463
const accountSubscription = await rpcSubscriptions
464
.accountNotifications(address("your-address-here"))
465
.subscribe();
466
467
// Process notifications
468
for await (const notification of accountSubscription) {
469
console.log("Account updated:", notification);
470
}
471
472
// Subscribe to signature confirmations
473
const signatureSubscription = await rpcSubscriptions
474
.signatureNotifications("your-signature-here")
475
.subscribe();
476
477
for await (const notification of signatureSubscription) {
478
if (notification.err) {
479
console.error("Transaction failed:", notification.err);
480
} else {
481
console.log("Transaction confirmed!");
482
}
483
break; // Exit after first notification
484
}
485
```
486
487
### Airdrop and Testing
488
489
Utilities for requesting SOL airdrops on test networks.
490
491
```typescript { .api }
492
/**
493
* Request an airdrop of SOL to an address
494
*/
495
interface RequestAirdropApi {
496
requestAirdrop(
497
address: Address,
498
lamports: Lamports,
499
config?: CommitmentConfig
500
): RpcRequest<Signature>;
501
}
502
```
503
504
### Cluster Configuration
505
506
Pre-configured endpoints for different Solana clusters.
507
508
```typescript { .api }
509
/**
510
* Get default RPC URL for a cluster
511
* @param cluster - Target cluster
512
* @returns RPC endpoint URL
513
*/
514
function getDefaultRpcUrl(cluster: "mainnet" | "testnet" | "devnet"): string;
515
516
/**
517
* Get default WebSocket URL for a cluster
518
* @param cluster - Target cluster
519
* @returns WebSocket endpoint URL
520
*/
521
function getDefaultRpcSubscriptionsUrl(cluster: "mainnet" | "testnet" | "devnet"): string;
522
523
/**
524
* Create cluster-specific RPC client
525
* @param cluster - Target cluster
526
* @param config - Optional configuration
527
* @returns Configured RPC client
528
*/
529
function createSolanaRpcFromCluster(
530
cluster: "mainnet" | "testnet" | "devnet",
531
config?: RpcConfig
532
): Rpc<SolanaRpcMethods>;
533
```
534
535
**Usage Examples:**
536
537
```typescript
538
import {
539
createSolanaRpcFromCluster,
540
getDefaultRpcUrl
541
} from "@solana/web3.js";
542
543
// Use pre-configured cluster endpoints
544
const devnetRpc = createSolanaRpcFromCluster("devnet");
545
const mainnetRpc = createSolanaRpcFromCluster("mainnet");
546
547
// Get cluster URLs
548
const devnetUrl = getDefaultRpcUrl("devnet");
549
console.log("Devnet URL:", devnetUrl);
550
```
551
552
## Configuration Types
553
554
```typescript { .api }
555
/**
556
* Base RPC configuration
557
*/
558
interface RpcConfig {
559
/**
560
* Request timeout in milliseconds
561
* @default 30000
562
*/
563
timeout?: number;
564
565
/**
566
* HTTP headers to include with requests
567
*/
568
headers?: Record<string, string>;
569
570
/**
571
* Custom request transformer
572
*/
573
requestTransformer?: RpcRequestTransformer;
574
575
/**
576
* Custom response transformer
577
*/
578
responseTransformer?: RpcResponseTransformer;
579
}
580
581
/**
582
* WebSocket subscriptions configuration
583
*/
584
interface RpcSubscriptionsConfig {
585
/**
586
* Connection timeout in milliseconds
587
* @default 30000
588
*/
589
timeout?: number;
590
591
/**
592
* Whether to auto-reconnect on disconnect
593
* @default true
594
*/
595
autoReconnect?: boolean;
596
597
/**
598
* Maximum reconnection attempts
599
* @default 5
600
*/
601
maxReconnectAttempts?: number;
602
}
603
604
/**
605
* Commitment configuration for RPC requests
606
*/
607
interface CommitmentConfig {
608
/**
609
* Commitment level
610
* @default "finalized"
611
*/
612
commitment?: Commitment;
613
}
614
615
/**
616
* Account information query configuration
617
*/
618
interface GetAccountInfoConfig extends CommitmentConfig {
619
/**
620
* Data encoding format
621
* @default "base64"
622
*/
623
encoding?: "base58" | "base64" | "jsonParsed";
624
625
/**
626
* Data slice to return
627
*/
628
dataSlice?: {
629
offset: number;
630
length: number;
631
};
632
}
633
```