0
# Utilities and Helpers
1
2
Essential utilities for Solana development including cluster configuration, validation helpers, constants, error handling, and development tools. These utilities provide the foundation for robust Solana applications.
3
4
## Capabilities
5
6
### Constants and Program IDs
7
8
Core constants and program identifiers used throughout the Solana ecosystem.
9
10
```python { .api }
11
# Core Solana constants
12
LAMPORTS_PER_SOL: int = 1_000_000_000 # Number of lamports in one SOL
13
14
# Program IDs
15
SYSTEM_PROGRAM_ID: Pubkey # System Program for account creation and transfers
16
CONFIG_PROGRAM_ID: Pubkey # Config Program for network configuration
17
STAKE_PROGRAM_ID: Pubkey # Stake Program for staking operations
18
VOTE_PROGRAM_ID: Pubkey # Vote Program for validator voting
19
ADDRESS_LOOKUP_TABLE_PROGRAM_ID: Pubkey # Address Lookup Table Program
20
BPF_LOADER_PROGRAM_ID: Pubkey # BPF Loader Program for program deployment
21
ED25519_PROGRAM_ID: Pubkey # Ed25519 signature verification program
22
SECP256K1_PROGRAM_ID: Pubkey # Secp256k1 signature verification program
23
24
# SPL Token constants
25
TOKEN_PROGRAM_ID: Pubkey # SPL Token Program
26
TOKEN_2022_PROGRAM_ID: Pubkey # SPL Token 2022 Program
27
ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey # Associated Token Program
28
WRAPPED_SOL_MINT: Pubkey # Native SOL mint for wrapped SOL
29
NATIVE_DECIMALS: int = 9 # Decimal places for SOL
30
31
# Account size constants
32
MINT_LEN: int = 82 # Size of token mint account data
33
ACCOUNT_LEN: int = 165 # Size of token account data
34
MULTISIG_LEN: int = 355 # Size of multisig account data
35
36
# SPL Memo constants
37
MEMO_PROGRAM_ID: Pubkey # SPL Memo Program
38
```
39
40
### Cluster Configuration
41
42
Utilities for configuring and connecting to different Solana network clusters including mainnet, testnet, and devnet.
43
44
```python { .api }
45
def cluster_api_url(cluster: Optional[Cluster] = None, tls: bool = True) -> str:
46
"""
47
Get API URL for a Solana cluster.
48
49
Parameters:
50
- cluster: Cluster name ("mainnet-beta", "testnet", "devnet"), defaults to "devnet"
51
- tls: Whether to use HTTPS (True) or HTTP (False)
52
53
Returns:
54
str: Cluster API URL
55
"""
56
57
# Cluster type definition
58
Cluster = Literal["mainnet-beta", "testnet", "devnet"]
59
60
# Pre-configured cluster endpoints
61
ENDPOINT: Dict[str, ClusterUrls] # Dictionary of cluster configurations
62
63
class ClusterUrls(NamedTuple):
64
http: str # HTTP RPC endpoint
65
https: str # HTTPS RPC endpoint
66
ws: str # WebSocket endpoint
67
wss: str # Secure WebSocket endpoint
68
69
class Endpoint(NamedTuple):
70
http: str # HTTP endpoint
71
https: str # HTTPS endpoint
72
```
73
74
### Validation Utilities
75
76
Helper functions for validating instructions, parameters, and other Solana-specific data structures.
77
78
```python { .api }
79
def validate_instruction_keys(instruction: Instruction, expected: int) -> None:
80
"""
81
Validate that an instruction has the expected number of keys.
82
83
Parameters:
84
- instruction: Instruction to validate
85
- expected: Expected number of keys
86
87
Raises:
88
ValueError: If instruction doesn't have expected number of keys
89
"""
90
91
def validate_instruction_type(parsed_data: Any, expected_type: Any) -> None:
92
"""
93
Validate that parsed instruction data matches expected type.
94
95
Parameters:
96
- parsed_data: Parsed instruction data
97
- expected_type: Expected data type or structure
98
99
Raises:
100
ValueError: If parsed data doesn't match expected type
101
"""
102
```
103
104
### Exception Handling
105
106
Structured exception handling system for Solana operations with specific error types and decorator utilities.
107
108
```python { .api }
109
class SolanaExceptionBase(Exception):
110
"""Base exception class for all Solana-related errors."""
111
pass
112
113
class SolanaRpcException(SolanaExceptionBase):
114
"""Exception class for RPC-specific errors."""
115
def __init__(self, message: str, error_code: Optional[int] = None, error_data: Optional[Any] = None):
116
"""
117
Initialize RPC exception.
118
119
Parameters:
120
- message: Error message
121
- error_code: RPC error code
122
- error_data: Additional error data
123
"""
124
super().__init__(message)
125
self.error_code = error_code
126
self.error_data = error_data
127
128
def handle_exceptions(func: Callable) -> Callable:
129
"""
130
Decorator for handling synchronous exceptions in Solana operations.
131
132
Parameters:
133
- func: Function to wrap with exception handling
134
135
Returns:
136
Callable: Wrapped function with exception handling
137
"""
138
139
def handle_async_exceptions(func: Callable) -> Callable:
140
"""
141
Decorator for handling asynchronous exceptions in Solana operations.
142
143
Parameters:
144
- func: Async function to wrap with exception handling
145
146
Returns:
147
Callable: Wrapped async function with exception handling
148
"""
149
```
150
151
### Security Text Parsing
152
153
Utilities for parsing and validating security.txt metadata from on-chain programs.
154
155
```python { .api }
156
def parse_security_txt(data: bytes) -> SecurityTxt:
157
"""
158
Parse security.txt data from program account.
159
160
Parameters:
161
- data: Raw security.txt data from program account
162
163
Returns:
164
SecurityTxt: Parsed security information
165
166
Raises:
167
NoSecurityTxtFoundError: If security.txt data is not found or invalid
168
"""
169
170
class SecurityTxt:
171
"""
172
Dataclass containing security.txt information.
173
174
Attributes:
175
- name: Program name
176
- project_url: Project website URL
177
- contacts: List of security contact methods
178
- policy: Security policy URL
179
- preferred_languages: Preferred languages for security reports
180
- source_code: Source code repository URL
181
- source_revision: Source code revision/commit
182
- source_release: Source code release version
183
- auditors: List of security auditors
184
- acknowledgments: Security acknowledgments URL
185
- expiry: Expiry date for security information
186
"""
187
188
class NoSecurityTxtFoundError(Exception):
189
"""Exception raised when security.txt is not found in program data."""
190
191
# Security.txt format constants
192
HEADER: str # Security.txt file header marker
193
FOOTER: str # Security.txt file footer marker
194
```
195
196
### Vote Program Utilities
197
198
Utilities for interacting with the Solana Vote Program for validator operations.
199
200
```python { .api }
201
def withdraw_from_vote_account(params: WithdrawFromVoteAccountParams) -> Instruction:
202
"""
203
Create instruction to withdraw from a vote account.
204
205
Parameters:
206
- params: Withdrawal parameters
207
208
Returns:
209
Instruction: Withdraw instruction for transaction
210
"""
211
212
class WithdrawFromVoteAccountParams(NamedTuple):
213
vote_account_pubkey: Pubkey # Vote account to withdraw from
214
authorized_withdrawer_pubkey: Pubkey # Authorized withdrawer
215
to_pubkey: Pubkey # Destination for withdrawn funds
216
lamports: int # Amount to withdraw
217
```
218
219
### Commitment Levels
220
221
Commitment level constants for controlling transaction and query confirmation requirements.
222
223
```python { .api }
224
# Commitment type and constants
225
Commitment = str # Type alias for commitment level strings
226
227
# Commitment levels (ordered from fastest to most secure)
228
Processed: Commitment = "processed" # Query the most recent block confirmed by cluster
229
Confirmed: Commitment = "confirmed" # Query the most recent block with at least 1 confirmation
230
Finalized: Commitment = "finalized" # Query the most recent block confirmed by supermajority
231
232
# Deprecated commitment levels (use modern equivalents above)
233
Max: Commitment = "max" # Deprecated, use "finalized"
234
Root: Commitment = "root" # Deprecated, use "finalized"
235
Single: Commitment = "single" # Deprecated, use "confirmed"
236
Recent: Commitment = "recent" # Deprecated, use "processed"
237
```
238
239
### Common Type Definitions
240
241
Frequently used type definitions and parameter structures for Solana operations.
242
243
```python { .api }
244
# RPC and networking types
245
URI = str # Type alias for endpoint URI strings
246
RPCMethod = str # Type alias for RPC method name strings
247
248
class RPCError(TypedDict):
249
code: int # Error code
250
message: str # Error message
251
data: Optional[Any] # Additional error data
252
253
# Query parameter types
254
class DataSliceOpts(NamedTuple):
255
offset: int # Starting byte offset
256
length: int # Number of bytes to return
257
258
class MemcmpOpts(NamedTuple):
259
offset: int # Byte offset for comparison
260
bytes_: str # Base58 encoded bytes to compare
261
262
class TokenAccountOpts(NamedTuple):
263
mint: Optional[Pubkey] = None # Filter by token mint
264
program_id: Optional[Pubkey] = None # Filter by token program
265
266
# Transaction options
267
class TxOpts(NamedTuple):
268
skip_preflight: bool = False # Skip transaction simulation
269
preflight_commitment: Optional[Commitment] = None # Commitment for simulation
270
encoding: str = "base64" # Transaction encoding
271
max_retries: Optional[int] = None # Maximum retry attempts
272
skip_confirmation: bool = False # Skip waiting for confirmation
273
```
274
275
## Usage Examples
276
277
### Basic Cluster Connection
278
279
```python
280
from solana.rpc.api import Client
281
from solana.utils.cluster import cluster_api_url
282
283
# Connect to different clusters
284
mainnet_client = Client(cluster_api_url("mainnet-beta"))
285
testnet_client = Client(cluster_api_url("testnet"))
286
devnet_client = Client(cluster_api_url("devnet"))
287
288
# Use custom endpoint
289
custom_client = Client("https://my-custom-rpc.com")
290
```
291
292
### Error Handling
293
294
```python
295
from solana.exceptions import SolanaRpcException, handle_exceptions
296
from solana.rpc.api import Client
297
298
@handle_exceptions
299
def safe_get_balance(client: Client, pubkey: Pubkey):
300
try:
301
return client.get_balance(pubkey)
302
except SolanaRpcException as e:
303
print(f"RPC Error {e.error_code}: {e}")
304
return None
305
```
306
307
### Validation
308
309
```python
310
from solana.utils.validate import validate_instruction_keys
311
from solders.instruction import Instruction
312
313
# Validate instruction has correct number of keys
314
def process_instruction(instruction: Instruction):
315
validate_instruction_keys(instruction, 3) # Expects exactly 3 keys
316
# Process instruction...
317
```
318
319
### Working with Constants
320
321
```python
322
from solana.constants import LAMPORTS_PER_SOL, SYSTEM_PROGRAM_ID
323
from spl.token.constants import TOKEN_PROGRAM_ID
324
325
# Convert SOL to lamports
326
sol_amount = 1.5
327
lamports = int(sol_amount * LAMPORTS_PER_SOL)
328
329
# Use program IDs in instructions
330
system_program_id = SYSTEM_PROGRAM_ID
331
token_program_id = TOKEN_PROGRAM_ID
332
```
333
334
## Types
335
336
```python { .api }
337
# Type aliases
338
Commitment = str
339
Cluster = Literal["mainnet-beta", "testnet", "devnet"]
340
URI = str
341
RPCMethod = str
342
343
# Structured types
344
class ClusterUrls(NamedTuple):
345
http: str
346
https: str
347
ws: str
348
wss: str
349
350
class Endpoint(NamedTuple):
351
http: str
352
https: str
353
354
class WithdrawFromVoteAccountParams(NamedTuple):
355
vote_account_pubkey: Pubkey
356
authorized_withdrawer_pubkey: Pubkey
357
to_pubkey: Pubkey
358
lamports: int
359
360
class SecurityTxt:
361
name: Optional[str]
362
project_url: Optional[str]
363
contacts: List[str]
364
policy: Optional[str]
365
preferred_languages: Optional[str]
366
source_code: Optional[str]
367
source_revision: Optional[str]
368
source_release: Optional[str]
369
auditors: List[str]
370
acknowledgments: Optional[str]
371
expiry: Optional[str]
372
373
class DataSliceOpts(NamedTuple):
374
offset: int
375
length: int
376
377
class MemcmpOpts(NamedTuple):
378
offset: int
379
bytes_: str
380
381
class TokenAccountOpts(NamedTuple):
382
mint: Optional[Pubkey] = None
383
program_id: Optional[Pubkey] = None
384
385
class TxOpts(NamedTuple):
386
skip_preflight: bool = False
387
preflight_commitment: Optional[Commitment] = None
388
encoding: str = "base64"
389
max_retries: Optional[int] = None
390
skip_confirmation: bool = False
391
392
class RPCError(TypedDict):
393
code: int
394
message: str
395
data: Optional[Any]
396
```