0
# High-Level Utilities
1
2
Ready-to-use utilities for common Solana operations including airdrops, transaction sending, compute limit estimation, and address lookup table management.
3
4
## Capabilities
5
6
### Airdrop Utilities
7
8
Request SOL airdrops on test networks with confirmation.
9
10
```typescript { .api }
11
/**
12
* Airdrop function signature
13
*/
14
type AirdropFunction = (config: {
15
/** Address to receive airdrop */
16
recipientAddress: Address;
17
/** Amount in lamports */
18
lamports: Lamports;
19
/** Commitment level for confirmation */
20
commitment?: Commitment;
21
/** Custom confirmation timeout */
22
confirmationTimeout?: number;
23
}) => Promise<Signature>;
24
25
/**
26
* Configuration for airdrop factory
27
*/
28
interface AirdropFactoryConfig<TCluster> {
29
/** RPC client with airdrop and signature status APIs */
30
rpc: Rpc<RequestAirdropApi & GetSignatureStatusesApi> & { '~cluster'?: TCluster };
31
/** Subscriptions client for signature notifications */
32
rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi> & { '~cluster'?: TCluster };
33
}
34
35
/**
36
* Create airdrop function for devnet
37
* @param config - Factory configuration
38
* @returns Configured airdrop function
39
*/
40
function airdropFactory(config: AirdropFactoryConfig<'devnet'>): AirdropFunction;
41
42
/**
43
* Create airdrop function for testnet
44
* @param config - Factory configuration
45
* @returns Configured airdrop function
46
*/
47
function airdropFactory(config: AirdropFactoryConfig<'testnet'>): AirdropFunction;
48
49
/**
50
* Create airdrop function for any cluster
51
* @param config - Factory configuration
52
* @returns Configured airdrop function
53
*/
54
function airdropFactory<TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void>(
55
config: AirdropFactoryConfig<TCluster>
56
): AirdropFunction;
57
```
58
59
**Usage Examples:**
60
61
```typescript
62
import {
63
airdropFactory,
64
createSolanaRpc,
65
createSolanaRpcSubscriptions,
66
address,
67
lamports
68
} from "@solana/web3.js";
69
70
// Create clients
71
const rpc = createSolanaRpc("https://api.devnet.solana.com");
72
const rpcSubscriptions = createSolanaRpcSubscriptions("wss://api.devnet.solana.com");
73
74
// Create airdrop function
75
const airdrop = airdropFactory({ rpc, rpcSubscriptions });
76
77
// Request airdrop
78
const signature = await airdrop({
79
recipientAddress: address("your-address-here"),
80
lamports: lamports(2_000_000_000n), // 2 SOL
81
commitment: "confirmed",
82
confirmationTimeout: 60000 // 60 seconds
83
});
84
85
console.log("Airdrop confirmed:", signature);
86
```
87
88
### Transaction Sending with Confirmation
89
90
Send transactions and wait for confirmation with various strategies.
91
92
```typescript { .api }
93
/**
94
* Send and confirm transaction function signature
95
*/
96
type SendAndConfirmTransactionFunction = (
97
transaction: FullySignedTransaction & TransactionWithBlockhashLifetime,
98
config?: {
99
/** Commitment level for confirmation */
100
commitment?: Commitment;
101
/** Skip preflight checks */
102
skipPreflight?: boolean;
103
/** Maximum confirmation timeout */
104
confirmationTimeout?: number;
105
/** Maximum retries for sending */
106
maxRetries?: number;
107
}
108
) => Promise<void>;
109
110
/**
111
* Factory configuration for transaction sending
112
*/
113
interface SendAndConfirmTransactionFactoryConfig<TCluster> {
114
/** RPC client with transaction APIs */
115
rpc: Rpc<GetEpochInfoApi & GetSignatureStatusesApi & SendTransactionApi> & { '~cluster'?: TCluster };
116
/** Subscriptions client for notifications */
117
rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi & SlotNotificationsApi> & { '~cluster'?: TCluster };
118
}
119
120
/**
121
* Create transaction sending function
122
* @param config - Factory configuration
123
* @returns Configured send and confirm function
124
*/
125
function sendAndConfirmTransactionFactory<TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void>(
126
config: SendAndConfirmTransactionFactoryConfig<TCluster>
127
): SendAndConfirmTransactionFunction;
128
```
129
130
**Usage Examples:**
131
132
```typescript
133
import {
134
sendAndConfirmTransactionFactory,
135
createTransactionMessage,
136
compileTransaction,
137
signTransaction
138
} from "@solana/web3.js";
139
140
// Create send function
141
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({
142
rpc,
143
rpcSubscriptions
144
});
145
146
// Create and sign transaction
147
const message = createTransactionMessage({
148
version: 0,
149
feePayer: signer.address,
150
blockhash,
151
instructions: [/* your instructions */]
152
});
153
154
let transaction = compileTransaction(message);
155
transaction = await signTransaction(transaction, [signer]);
156
157
// Send and confirm
158
await sendAndConfirmTransaction(transaction, {
159
commitment: "confirmed",
160
confirmationTimeout: 30000,
161
maxRetries: 3
162
});
163
164
console.log("Transaction confirmed!");
165
```
166
167
### Fire-and-Forget Transaction Sending
168
169
Send transactions without waiting for confirmation.
170
171
```typescript { .api }
172
/**
173
* Send transaction without confirming function signature
174
*/
175
type SendTransactionWithoutConfirmingFunction = (
176
transaction: FullySignedTransaction,
177
config?: {
178
/** Skip preflight checks */
179
skipPreflight?: boolean;
180
/** Maximum retries */
181
maxRetries?: number;
182
/** Custom retry delay */
183
retryDelay?: number;
184
}
185
) => Promise<void>;
186
187
/**
188
* Factory configuration for fire-and-forget sending
189
*/
190
interface SendTransactionWithoutConfirmingFactoryConfig {
191
/** RPC client with send transaction API */
192
rpc: Rpc<SendTransactionApi>;
193
}
194
195
/**
196
* Create fire-and-forget send function
197
* @param config - Factory configuration
198
* @returns Configured send function
199
*/
200
function sendTransactionWithoutConfirmingFactory(
201
config: SendTransactionWithoutConfirmingFactoryConfig
202
): SendTransactionWithoutConfirmingFunction;
203
```
204
205
### Durable Nonce Transaction Sending
206
207
Send transactions with durable nonce lifetime management.
208
209
```typescript { .api }
210
/**
211
* Durable nonce transaction sending function signature
212
*/
213
type SendAndConfirmDurableNonceTransactionFunction = (
214
transaction: FullySignedTransaction & TransactionWithDurableNonceLifetime,
215
config?: {
216
/** Commitment level */
217
commitment?: Commitment;
218
/** Confirmation timeout */
219
confirmationTimeout?: number;
220
/** Maximum retries */
221
maxRetries?: number;
222
}
223
) => Promise<void>;
224
225
/**
226
* Factory configuration for durable nonce transactions
227
*/
228
interface SendAndConfirmDurableNonceTransactionFactoryConfig<TCluster> {
229
/** RPC client with required APIs */
230
rpc: Rpc<GetAccountInfoApi & GetSignatureStatusesApi & SendTransactionApi> & { '~cluster'?: TCluster };
231
/** Subscriptions client */
232
rpcSubscriptions: RpcSubscriptions<AccountNotificationsApi & SignatureNotificationsApi> & { '~cluster'?: TCluster };
233
}
234
235
/**
236
* Create durable nonce transaction sender
237
* @param config - Factory configuration
238
* @returns Configured sender function
239
*/
240
function sendAndConfirmDurableNonceTransactionFactory<TCluster extends 'devnet' | 'mainnet' | 'testnet' | void = void>(
241
config: SendAndConfirmDurableNonceTransactionFactoryConfig<TCluster>
242
): SendAndConfirmDurableNonceTransactionFunction;
243
```
244
245
### Compute Unit Estimation
246
247
Estimate compute units required for transaction execution.
248
249
```typescript { .api }
250
/**
251
* Compute unit estimation function signature
252
*/
253
type ComputeUnitEstimateFunction = (
254
transactionMessage: CompilableTransactionMessage | (ITransactionMessageWithFeePayer & TransactionMessage),
255
config?: {
256
/** Commitment level for simulation */
257
commitment?: Commitment;
258
/** Accounts to include in simulation */
259
accounts?: {
260
encoding?: "base64" | "jsonParsed";
261
addresses?: Address[];
262
};
263
/** Replace recent blockhash */
264
replaceRecentBlockhash?: boolean;
265
}
266
) => Promise<number>;
267
268
/**
269
* Factory configuration for compute estimation
270
*/
271
interface ComputeUnitEstimateFactoryConfig {
272
/** RPC client with simulate transaction API */
273
rpc: Rpc<SimulateTransactionApi>;
274
}
275
276
/**
277
* Create compute unit estimation function
278
* @param config - Factory configuration
279
* @returns Configured estimation function
280
*/
281
function getComputeUnitEstimateForTransactionMessageFactory(
282
config: ComputeUnitEstimateFactoryConfig
283
): ComputeUnitEstimateFunction;
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
import {
290
getComputeUnitEstimateForTransactionMessageFactory,
291
createTransactionMessage
292
} from "@solana/web3.js";
293
294
// Create estimation function
295
const getComputeUnitEstimate = getComputeUnitEstimateForTransactionMessageFactory({ rpc });
296
297
// Create transaction message
298
const message = createTransactionMessage({
299
version: 0,
300
feePayer: myAddress,
301
blockhash,
302
instructions: [/* complex instructions */]
303
});
304
305
// Estimate compute units
306
const estimatedUnits = await getComputeUnitEstimate(message, {
307
commitment: "processed",
308
replaceRecentBlockhash: true
309
});
310
311
console.log("Estimated compute units:", estimatedUnits);
312
313
// Add compute budget instruction if needed
314
if (estimatedUnits > 200000) {
315
const computeBudgetInstruction = createComputeBudgetInstruction({
316
units: estimatedUnits + 10000 // Add buffer
317
});
318
319
message.instructions.unshift(computeBudgetInstruction);
320
}
321
```
322
323
### Address Lookup Table Decompilation
324
325
Decompile transaction messages while fetching address lookup tables.
326
327
```typescript { .api }
328
/**
329
* Decompile transaction message with automatic lookup table fetching
330
* @param compiledMessage - Compiled transaction message
331
* @param rpc - RPC client for fetching lookup tables
332
* @param config - Optional configuration
333
* @returns Promise resolving to decompiled message
334
*/
335
function decompileTransactionMessageFetchingLookupTables(
336
compiledMessage: CompiledTransactionMessage,
337
rpc: Rpc<GetMultipleAccountsApi>,
338
config?: {
339
/** Commitment level for account fetching */
340
commitment?: Commitment;
341
/** Last valid block height */
342
lastValidBlockHeight?: bigint;
343
/** Account fetch configuration */
344
accountsConfig?: FetchAccountsConfig;
345
}
346
): Promise<CompilableTransactionMessage>;
347
```
348
349
**Usage Examples:**
350
351
```typescript
352
import { decompileTransactionMessageFetchingLookupTables } from "@solana/web3.js";
353
354
// Received compiled message from network
355
const compiledMessage = /* compiled transaction with lookup tables */;
356
357
// Decompile with automatic lookup table resolution
358
const decompiled = await decompileTransactionMessageFetchingLookupTables(
359
compiledMessage,
360
rpc,
361
{
362
commitment: "confirmed",
363
lastValidBlockHeight: 200000000n
364
}
365
);
366
367
console.log("Decompiled instructions:", decompiled.instructions.length);
368
console.log("Fee payer:", decompiled.feePayer);
369
```
370
371
### Utility Combinations
372
373
Combine utilities for complete workflows.
374
375
```typescript { .api }
376
/**
377
* Complete transaction workflow: build, send, and confirm
378
* @param config - Workflow configuration
379
* @returns Promise resolving to transaction signature
380
*/
381
function executeTransactionWorkflow(config: {
382
/** RPC clients */
383
rpc: Rpc<SendTransactionApi & GetSignatureStatusesApi>;
384
rpcSubscriptions: RpcSubscriptions<SignatureNotificationsApi>;
385
/** Transaction instructions */
386
instructions: IInstruction[];
387
/** Signers */
388
signers: TransactionSigner[];
389
/** Fee payer */
390
feePayer: Address;
391
/** Transaction options */
392
options?: {
393
commitment?: Commitment;
394
skipPreflight?: boolean;
395
confirmationTimeout?: number;
396
};
397
}): Promise<Signature>;
398
399
/**
400
* Batch transaction sending with retry logic
401
* @param transactions - Transactions to send
402
* @param config - Batch configuration
403
* @returns Promise resolving to signature results
404
*/
405
function sendTransactionBatch(
406
transactions: FullySignedTransaction[],
407
config: {
408
rpc: Rpc<SendTransactionApi>;
409
batchSize?: number;
410
retryConfig?: RetryConfig;
411
delayBetweenBatches?: number;
412
}
413
): Promise<Array<{ signature?: Signature; error?: Error }>>;
414
```
415
416
## Transaction Lifetime Types
417
418
```typescript { .api }
419
/**
420
* Transaction with blockhash-based lifetime
421
*/
422
interface TransactionWithBlockhashLifetime {
423
/** Recent blockhash */
424
blockhash: Blockhash;
425
/** Last valid block height */
426
lastValidBlockHeight: bigint;
427
}
428
429
/**
430
* Transaction with durable nonce lifetime
431
*/
432
interface TransactionWithDurableNonceLifetime {
433
/** Nonce account address */
434
nonceAccount: Address;
435
/** Nonce authority address */
436
nonceAuthority: Address;
437
/** Current nonce value */
438
nonceValue: string;
439
}
440
441
/**
442
* Fully signed transaction ready for sending
443
*/
444
interface FullySignedTransaction {
445
/** Transaction signatures */
446
signatures: Signature[];
447
/** Compiled message bytes */
448
messageBytes: Uint8Array;
449
}
450
451
/**
452
* Transaction message with fee payer
453
*/
454
interface ITransactionMessageWithFeePayer {
455
/** Fee payer address */
456
feePayer: Address;
457
}
458
```
459
460
**Advanced Usage Examples:**
461
462
```typescript
463
import {
464
executeTransactionWorkflow,
465
sendTransactionBatch,
466
createTransferInstruction,
467
generateKeyPair,
468
createSignerFromKeyPair
469
} from "@solana/web3.js";
470
471
// Complete workflow example
472
const keyPair = await generateKeyPair();
473
const signer = await createSignerFromKeyPair(keyPair);
474
475
const signature = await executeTransactionWorkflow({
476
rpc,
477
rpcSubscriptions,
478
instructions: [
479
createTransferInstruction({
480
fromPubkey: signer.address,
481
toPubkey: recipientAddress,
482
lamports: lamports(1_000_000n)
483
})
484
],
485
signers: [signer],
486
feePayer: signer.address,
487
options: {
488
commitment: "confirmed",
489
confirmationTimeout: 30000
490
}
491
});
492
493
console.log("Workflow completed:", signature);
494
495
// Batch sending example
496
const transactions = [/* array of signed transactions */];
497
498
const results = await sendTransactionBatch(transactions, {
499
rpc,
500
batchSize: 5,
501
delayBetweenBatches: 1000,
502
retryConfig: {
503
maxRetries: 3,
504
baseDelay: 1000,
505
backoffMultiplier: 2
506
}
507
});
508
509
console.log("Batch results:", results);
510
results.forEach((result, index) => {
511
if (result.error) {
512
console.error(`Transaction ${index} failed:`, result.error);
513
} else {
514
console.log(`Transaction ${index} succeeded:`, result.signature);
515
}
516
});
517
```