Solana Python API
Solana.py is the official Python SDK for interacting with the Solana blockchain. It provides a robust API for building transactions, interacting with the Solana JSON RPC API, and working with the SPL Token Program. The library is actively maintained with frequent releases, often incorporating core types and high-performance components from the `solders` library.
Warnings
- breaking Starting with v0.36.0, support for legacy transaction formats has been removed. Users should migrate to `VersionedTransaction` and `MessageV0` from `solders.transaction` and `solders.message` respectively.
- breaking Many core data types (e.g., `Keypair`, `Pubkey`, `Message`, `Transaction`) were migrated from `solana-py`'s internal modules to the `solders` library. Direct imports from `solana.keypair`, `solana.publickey`, or `solana.transaction` for these types are deprecated or will result in errors.
- deprecated The entire `solana.transaction` module and its classes (e.g., `Transaction`, `Message`) are deprecated. Additionally, methods like `get_stake_activation` have been deprecated.
- gotcha The `BlockhashCache`, an experimental feature, was removed in v0.33.0 due to it being 'experimental and flawed' and a 'footgun because it broke a lot'.
- gotcha When constructing transactions using `solders.transaction.Transaction` (especially older patterns) or `VersionedTransaction`, incorrect argument types or missing required arguments for the constructor are common, leading to `TypeError` or runtime errors like `argument 'payer': 'Hash' object cannot be converted to 'Pubkey'`.
Install
-
pip install solana solders
Imports
- AsyncClient
from solana.rpc.async_api import AsyncClient
- Keypair
from solders.keypair import Keypair
- Pubkey
from solders.pubkey import Pubkey
- VersionedTransaction
from solders.transaction import VersionedTransaction
- MessageV0
from solders.message import MessageV0
Quickstart
import asyncio
import os
from solders.pubkey import Pubkey
from solana.rpc.async_api import AsyncClient
async def get_sol_balance(public_key_str: str):
"""Fetches the SOL balance of a given public key."""
# Use a devnet RPC endpoint. For production, consider using a dedicated provider.
rpc_url = os.environ.get("SOLANA_RPC_URL", "https://api.devnet.solana.com")
async with AsyncClient(rpc_url) as client:
pubkey = Pubkey.from_string(public_key_str)
try:
response = await client.get_balance(pubkey)
balance_lamports = response.value
balance_sol = balance_lamports / 1_000_000_000 # 1 SOL = 1,000,000,000 lamports
print(f"Account: {public_key_str}")
print(f"Balance: {balance_sol} SOL ({balance_lamports} lamports)")
except Exception as e:
print(f"Error fetching balance: {e}")
if __name__ == "__main__":
# Replace with a real Solana public key (e.g., from a test wallet)
example_public_key = "5Q544fFztbO2Drj9yQ9C7M2f8L2rW3e3H5D2n6H6f8f8" # Example devnet address
asyncio.run(get_sol_balance(example_public_key))