Comprehensive Python SDK for interacting with the Solana blockchain network including RPC clients, SPL Token support, and WebSocket subscriptions.
npx @tessl/cli install tessl/pypi-solana@0.36.0A 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.
pip install solanaimport solanaFor RPC client operations:
from solana.rpc.api import Client
from solana.rpc.async_api import AsyncClientFor SPL Token operations:
from spl.token.client import Token
from spl.token.async_client import AsyncTokenFor WebSocket connections and subscriptions:
from solana.rpc.websocket_api import connect, SolanaWsClientProtocolFor common types and constants:
from solana.constants import LAMPORTS_PER_SOL, SYSTEM_PROGRAM_ID
from spl.token.constants import TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_IDfrom solana.rpc.api import Client
from solana.rpc.commitment import Confirmed
from solders.pubkey import Pubkey
# Initialize RPC client
client = Client("https://api.mainnet-beta.solana.com")
# Get account balance
pubkey = Pubkey.from_string("11111111111111111111111111111112")
balance = client.get_balance(pubkey, commitment=Confirmed)
print(f"Balance: {balance.value} lamports")
# Get latest blockhash
blockhash = client.get_latest_blockhash()
print(f"Latest blockhash: {blockhash.value.blockhash}")
# SPL Token operations
from spl.token.client import Token
from spl.token.constants import TOKEN_PROGRAM_ID
# Create a token instance
token = Token(
conn=client,
pubkey=Pubkey.from_string("your-mint-address"),
program_id=TOKEN_PROGRAM_ID,
payer=your_keypair # solders.keypair.Keypair instance
)
# Get token balance
token_balance = token.get_balance(token_account_pubkey)
print(f"Token balance: {token_balance.value.amount}")The Solana Python SDK is organized into several key components:
solders library for core Solana types (Pubkey, Keypair, Transaction, etc.)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.
Complete Solana JSON-RPC API client with synchronous and asynchronous interfaces. Supports account queries, transaction operations, network information, and real-time WebSocket subscriptions.
class Client:
def __init__(self, endpoint: str, commitment: Optional[Commitment] = None, timeout: float = 30, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[str] = None): ...
def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetBalanceResp: ...
def get_account_info(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: str = "base64", data_slice: Optional[DataSliceOpts] = None) -> GetAccountInfoResp: ...
def send_transaction(self, txn: Transaction, opts: Optional[TxOpts] = None) -> SendTransactionResp: ...
def get_latest_blockhash(self, commitment: Optional[Commitment] = None) -> GetLatestBlockhashResp: ...
class AsyncClient:
def __init__(self, endpoint: str, commitment: Optional[Commitment] = None, timeout: float = 30, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[str] = None): ...
async def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetBalanceResp: ...
async def get_account_info(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: str = "base64", data_slice: Optional[DataSliceOpts] = None) -> GetAccountInfoResp: ...
async def send_transaction(self, txn: Transaction, opts: Optional[TxOpts] = None) -> SendTransactionResp: ...
async def get_latest_blockhash(self, commitment: Optional[Commitment] = None) -> GetLatestBlockhashResp: ...Comprehensive SPL Token program interface for token creation, account management, transfers, and advanced token operations. Supports both standard Token program and Token-2022.
class Token:
def __init__(self, conn: Client, pubkey: Pubkey, program_id: Pubkey, payer: Keypair): ...
@staticmethod
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": ...
def create_account(self, owner: Pubkey, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> Pubkey: ...
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: ...
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: ...
def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetTokenAccountBalanceResp: ...
class AsyncToken:
def __init__(self, conn: AsyncClient, pubkey: Pubkey, program_id: Pubkey, payer: Keypair): ...
@staticmethod
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": ...
async def create_account(self, owner: Pubkey, skip_confirmation: bool = False, recent_blockhash: Optional[Blockhash] = None) -> Pubkey: ...
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: ...
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: ...
async def get_balance(self, pubkey: Pubkey, commitment: Optional[Commitment] = None) -> GetTokenAccountBalanceResp: ...Essential utilities for Solana development including cluster configuration, validation helpers, constants, and error handling.
# Constants
LAMPORTS_PER_SOL: int = 1_000_000_000
SYSTEM_PROGRAM_ID: Pubkey
TOKEN_PROGRAM_ID: Pubkey
ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey
# Cluster utilities
def cluster_api_url(cluster: Optional[Cluster] = None, tls: bool = True) -> str: ...
# Validation utilities
def validate_instruction_keys(instruction: Instruction, expected: int) -> None: ...
def validate_instruction_type(parsed_data: Any, expected_type: Any) -> None: ...
# Exception handling
class SolanaExceptionBase(Exception): ...
class SolanaRpcException(SolanaExceptionBase): ...
def handle_exceptions(func: Callable) -> Callable: ...
def handle_async_exceptions(func: Callable) -> Callable: ...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.
class SolanaWsClientProtocol:
def __init__(self): ...
async def account_subscribe(self, pubkey: Pubkey, commitment: Optional[Commitment] = None, encoding: Optional[str] = None) -> None: ...
async def account_unsubscribe(self, subscription: int) -> None: ...
async def logs_subscribe(self, filter_: Union[RpcTransactionLogsFilter, RpcTransactionLogsFilterMentions] = RpcTransactionLogsFilter.All, commitment: Optional[Commitment] = None) -> None: ...
async def logs_unsubscribe(self, subscription: int) -> None: ...
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: ...
async def block_unsubscribe(self, subscription: int) -> None: ...
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: ...
async def program_unsubscribe(self, subscription: int) -> None: ...
async def signature_subscribe(self, signature: Signature, commitment: Optional[Commitment] = None) -> None: ...
async def signature_unsubscribe(self, subscription: int) -> None: ...
async def slot_subscribe(self) -> None: ...
async def slot_unsubscribe(self, subscription: int) -> None: ...
async def recv(self) -> List[Union[Notification, SubscriptionResult]]: ...
async def connect(uri: str = "ws://localhost:8900") -> SolanaWsClientProtocol: ...These types are imported from the solders library and are fundamental to using the Solana SDK:
# From solders.pubkey
class Pubkey:
@classmethod
def from_string(cls, s: str) -> "Pubkey": ...
def __str__(self) -> str: ...
# From solders.keypair
class Keypair:
@classmethod
def generate(cls) -> "Keypair": ...
@classmethod
def from_bytes(cls, data: bytes) -> "Keypair": ...
def pubkey(self) -> Pubkey: ...
# From solders.transaction
class Transaction:
def __init__(self, instructions: List[Instruction], payer: Pubkey, recent_blockhash: Optional[Hash] = None): ...
# From solders.instruction
class Instruction:
def __init__(self, program_id: Pubkey, data: bytes, accounts: List[AccountMeta]): ...
# RPC Response types
class GetBalanceResp:
value: int
class GetAccountInfoResp:
value: Optional[Account]
class SendTransactionResp:
value: str
class GetLatestBlockhashResp:
value: RpcBlockhash
# Common parameter types
class DataSliceOpts(NamedTuple):
offset: int
length: int
class TxOpts(NamedTuple):
skip_preflight: bool = False
preflight_commitment: Optional[Commitment] = None
encoding: str = "base64"
max_retries: Optional[int] = None
skip_confirmation: bool = False
# Commitment levels
Commitment = str
Finalized: Commitment = "finalized"
Confirmed: Commitment = "confirmed"
Processed: Commitment = "processed"