Solana Python API

0.36.11 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to the Solana Devnet using `AsyncClient` and fetch the SOL balance of a specified public key. It highlights the use of `solders.pubkey.Pubkey` and the asynchronous nature of `solana-py` interactions. Remember to replace the example public key with a valid one and set `SOLANA_RPC_URL` if not using the default devnet endpoint.

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))

view raw JSON →