or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-solana

Comprehensive Python SDK for interacting with the Solana blockchain network including RPC clients, SPL Token support, and WebSocket subscriptions.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/solana@0.36.x

To install, run

npx @tessl/cli install tessl/pypi-solana@0.36.0

0

# Solana Python SDK

1

2

A comprehensive Python SDK for interacting with the Solana blockchain network. This library enables developers to build transactions, interact with the Solana JSON RPC API, and work with SPL Token programs. The SDK offers both synchronous and asynchronous client interfaces for HTTP and WebSocket connections, making it suitable for various blockchain application development scenarios.

3

4

## Package Information

5

6

- **Package Name**: solana

7

- **Language**: Python

8

- **Installation**: `pip install solana`

9

10

## Core Imports

11

12

```python

13

import solana

14

```

15

16

For RPC client operations:

17

18

```python

19

from solana.rpc.api import Client

20

from solana.rpc.async_api import AsyncClient

21

```

22

23

For SPL Token operations:

24

25

```python

26

from spl.token.client import Token

27

from spl.token.async_client import AsyncToken

28

```

29

30

For WebSocket connections and subscriptions:

31

32

```python

33

from solana.rpc.websocket_api import connect, SolanaWsClientProtocol

34

```

35

36

For common types and constants:

37

38

```python

39

from solana.constants import LAMPORTS_PER_SOL, SYSTEM_PROGRAM_ID

40

from spl.token.constants import TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID

41

```

42

43

## Basic Usage

44

45

```python

46

from solana.rpc.api import Client

47

from solana.rpc.commitment import Confirmed

48

from solders.pubkey import Pubkey

49

50

# Initialize RPC client

51

client = Client("https://api.mainnet-beta.solana.com")

52

53

# Get account balance

54

pubkey = Pubkey.from_string("11111111111111111111111111111112")

55

balance = client.get_balance(pubkey, commitment=Confirmed)

56

print(f"Balance: {balance.value} lamports")

57

58

# Get latest blockhash

59

blockhash = client.get_latest_blockhash()

60

print(f"Latest blockhash: {blockhash.value.blockhash}")

61

62

# SPL Token operations

63

from spl.token.client import Token

64

from spl.token.constants import TOKEN_PROGRAM_ID

65

66

# Create a token instance

67

token = Token(

68

conn=client,

69

pubkey=Pubkey.from_string("your-mint-address"),

70

program_id=TOKEN_PROGRAM_ID,

71

payer=your_keypair # solders.keypair.Keypair instance

72

)

73

74

# Get token balance

75

token_balance = token.get_balance(token_account_pubkey)

76

print(f"Token balance: {token_balance.value.amount}")

77

```

78

79

## Architecture

80

81

The Solana Python SDK is organized into several key components:

82

83

- **RPC Layer**: Comprehensive JSON-RPC client with sync/async support and WebSocket subscriptions

84

- **SPL Integration**: Complete SPL Token program support with high-level convenience methods

85

- **Type System**: Extensive use of the `solders` library for core Solana types (Pubkey, Keypair, Transaction, etc.)

86

- **Error Handling**: Structured exception handling with RPC-specific error types

87

- **Utilities**: Cluster configuration, validation helpers, and development tools

88

89

This design provides both high-level convenience methods for common operations and low-level instruction building capabilities for advanced use cases, with full support for async/await patterns throughout.

90

91

## Capabilities

92

93

### RPC Client Operations

94

95

Complete Solana JSON-RPC API client with synchronous and asynchronous interfaces. Supports account queries, transaction operations, network information, and real-time WebSocket subscriptions.

96

97

```python { .api }

98

class Client:

99

def __init__(self, endpoint: str, commitment: Optional[Commitment] = None, timeout: float = 30, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[str] = None): ...

100

101

def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetBalanceResp: ...

102

def get_account_info(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: str = "base64", data_slice: Optional[DataSliceOpts] = None) -> GetAccountInfoResp: ...

103

def send_transaction(self, txn: Transaction, opts: Optional[TxOpts] = None) -> SendTransactionResp: ...

104

def get_latest_blockhash(self, commitment: Optional[Commitment] = None) -> GetLatestBlockhashResp: ...

105

106

class AsyncClient:

107

def __init__(self, endpoint: str, commitment: Optional[Commitment] = None, timeout: float = 30, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[str] = None): ...

108

109

async def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetBalanceResp: ...

110

async def get_account_info(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: str = "base64", data_slice: Optional[DataSliceOpts] = None) -> GetAccountInfoResp: ...

111

async def send_transaction(self, txn: Transaction, opts: Optional[TxOpts] = None) -> SendTransactionResp: ...

112

async def get_latest_blockhash(self, commitment: Optional[Commitment] = None) -> GetLatestBlockhashResp: ...

113

```

114

115

[RPC Client Operations](./rpc-client.md)

116

117

### SPL Token Operations

118

119

Comprehensive SPL Token program interface for token creation, account management, transfers, and advanced token operations. Supports both standard Token program and Token-2022.

120

121

```python { .api }

122

class Token:

123

def __init__(self, conn: Client, pubkey: Pubkey, program_id: Pubkey, payer: Keypair): ...

124

125

@staticmethod

126

def create_mint(conn: Client, payer: Keypair, mint_authority: Pubkey, decimals: int, program_id: Pubkey, freeze_authority: Optional[Pubkey] = None, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> "Token": ...

127

128

def create_account(self, owner: Pubkey, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> Pubkey: ...

129

def transfer(self, source: Pubkey, dest: Pubkey, owner: Keypair, amount: int, multi_signers: Optional[List[Keypair]] = None, opts: Optional[TxOpts] = None, recent_blockhash: Optional[Blockhash] = None) -> SendTransactionResp: ...

130

def mint_to(self, dest: Pubkey, mint_authority: Keypair, amount: int, multi_signers: Optional[List[Keypair]] = None, opts: Optional[TxOpts] = None, recent_blockhash: Optional[Blockhash] = None) -> SendTransactionResp: ...

131

def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetTokenAccountBalanceResp: ...

132

133

class AsyncToken:

134

def __init__(self, conn: AsyncClient, pubkey: Pubkey, program_id: Pubkey, payer: Keypair): ...

135

136

@staticmethod

137

async def create_mint(conn: AsyncClient, payer: Keypair, mint_authority: Pubkey, decimals: int, program_id: Pubkey, freeze_authority: Optional[Pubkey] = None, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> "AsyncToken": ...

138

139

async def create_account(self, owner: Pubkey, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> Pubkey: ...

140

async def transfer(self, source: Pubkey, dest: Pubkey, owner: Keypair, amount: int, multi_signers: Optional[List[Keypair]] = None, opts: Optional[TxOpts] = None, recent_blockhash: Optional[Blockhash] = None) -> SendTransactionResp: ...

141

async def mint_to(self, dest: Pubkey, mint_authority: Keypair, amount: int, multi_signers: Optional[List[Keypair]] = None, opts: Optional[TxOpts] = None, recent_blockhash: Optional[Blockhash] = None) -> SendTransactionResp: ...

142

async def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetTokenAccountBalanceResp: ...

143

```

144

145

[SPL Token Operations](./token-operations.md)

146

147

### Utilities and Helpers

148

149

Essential utilities for Solana development including cluster configuration, validation helpers, constants, and error handling.

150

151

```python { .api }

152

# Constants

153

LAMPORTS_PER_SOL: int = 1_000_000_000

154

SYSTEM_PROGRAM_ID: Pubkey

155

TOKEN_PROGRAM_ID: Pubkey

156

ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey

157

158

# Cluster utilities

159

def cluster_api_url(cluster: Optional[Cluster] = None, tls: bool = True) -> str: ...

160

161

# Validation utilities

162

def validate_instruction_keys(instruction: Instruction, expected: int) -> None: ...

163

def validate_instruction_type(parsed_data: Any, expected_type: Any) -> None: ...

164

165

# Exception handling

166

class SolanaExceptionBase(Exception): ...

167

class SolanaRpcException(SolanaExceptionBase): ...

168

169

def handle_exceptions(func: Callable) -> Callable: ...

170

def handle_async_exceptions(func: Callable) -> Callable: ...

171

```

172

173

[Utilities and Helpers](./utilities.md)

174

175

### WebSocket Subscriptions

176

177

Real-time WebSocket API for subscribing to account changes, transaction logs, block updates, program account changes, and other live network events with comprehensive subscription management.

178

179

```python { .api }

180

class SolanaWsClientProtocol:

181

def __init__(self): ...

182

183

async def account_subscribe(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: Optional[str] = None) -> None: ...

184

async def account_unsubscribe(self, subscription: int) -> None: ...

185

186

async def logs_subscribe(self, filter_: Union[RpcTransactionLogsFilter, RpcTransactionLogsFilterMentions] = RpcTransactionLogsFilter.All, commitment: Optional[Commitment] = None) -> None: ...

187

async def logs_unsubscribe(self, subscription: int) -> None: ...

188

189

async def block_subscribe(self, filter_: Union[RpcBlockSubscribeFilter, RpcBlockSubscribeFilterMentions] = RpcBlockSubscribeFilter.All, commitment: Optional[Commitment] = None, encoding: Optional[str] = None, transaction_details: Optional[TransactionDetails] = None, show_rewards: Optional[bool] = None, max_supported_transaction_version: Optional[int] = None) -> None: ...

190

async def block_unsubscribe(self, subscription: int) -> None: ...

191

192

async def program_subscribe(self, program_id: Pubkey, commitment: Optional[Commitment] = None, encoding: Optional[str] = None, data_slice: Optional[DataSliceOpts] = None, filters: Optional[Sequence[Union[int, MemcmpOpts]]] = None) -> None: ...

193

async def program_unsubscribe(self, subscription: int) -> None: ...

194

195

async def signature_subscribe(self, signature: Signature, commitment: Optional[Commitment] = None) -> None: ...

196

async def signature_unsubscribe(self, subscription: int) -> None: ...

197

198

async def slot_subscribe(self) -> None: ...

199

async def slot_unsubscribe(self, subscription: int) -> None: ...

200

201

async def recv(self) -> List[Union[Notification, SubscriptionResult]]: ...

202

203

async def connect(uri: str = "ws://localhost:8900") -> SolanaWsClientProtocol: ...

204

```

205

206

[WebSocket Subscriptions](./websocket-subscriptions.md)

207

208

## Core Types

209

210

These types are imported from the `solders` library and are fundamental to using the Solana SDK:

211

212

```python { .api }

213

# From solders.pubkey

214

class Pubkey:

215

@classmethod

216

def from_string(cls, s: str) -> "Pubkey": ...

217

def __str__(self) -> str: ...

218

219

# From solders.keypair

220

class Keypair:

221

@classmethod

222

def generate(cls) -> "Keypair": ...

223

@classmethod

224

def from_bytes(cls, data: bytes) -> "Keypair": ...

225

def pubkey(self) -> Pubkey: ...

226

227

# From solders.transaction

228

class Transaction:

229

def __init__(self, instructions: List[Instruction], payer: Pubkey, recent_blockhash: Optional[Hash] = None): ...

230

231

# From solders.instruction

232

class Instruction:

233

def __init__(self, program_id: Pubkey, data: bytes, accounts: List[AccountMeta]): ...

234

235

# RPC Response types

236

class GetBalanceResp:

237

value: int

238

239

class GetAccountInfoResp:

240

value: Optional[Account]

241

242

class SendTransactionResp:

243

value: str

244

245

class GetLatestBlockhashResp:

246

value: RpcBlockhash

247

248

# Common parameter types

249

class DataSliceOpts(NamedTuple):

250

offset: int

251

length: int

252

253

class TxOpts(NamedTuple):

254

skip_preflight: bool = False

255

preflight_commitment: Optional[Commitment] = None

256

encoding: str = "base64"

257

max_retries: Optional[int] = None

258

skip_confirmation: bool = False

259

260

# Commitment levels

261

Commitment = str

262

Finalized: Commitment = "finalized"

263

Confirmed: Commitment = "confirmed"

264

Processed: Commitment = "processed"

265

```