Python for Solana
Python is a first-class off-chain language for Solana. Teams use it for bots, backend services, research notebooks, ETL, and ops automation against Agave 4.1.1 RPC nodes.
It does not run inside the Sealevel runtime. On-chain programs stay Rust (often Anchor 0.32.1), built and deployed with Solana CLI 3.0.10. Python talks to those programs over JSON-RPC, websockets, and IDL clients.
This page is the section umbrella. Sibling articles cover the SDK pair, transaction construction, AnchorPy, reads, bots, analytics, and production habits.
Summary
- Use Python to read Solana state, build and sign transactions, call Anchor programs via IDL, and pipe chain data into analytics stacks - always as a client of the cluster, never as program bytecode.
- Insight: Many quant, data, and platform teams already ship Python. solders + solana-py + AnchorPy let them integrate Solana without rewriting services in TypeScript, while still pairing with @solana/kit 7.0.0 frontends when wallets and browsers are the product surface.
- Key Concepts: solders, solana-py (
solana), AnchorPy, VersionedTransaction, blockhash, simulation / preflight, AsyncClient, getProgramAccounts / filters, DAS API, pandas / Polars, Python vs Kit. - When to Use Python: Market-making and arb bots, custodial or relay backends, indexer-adjacent ETL, treasury and protocol metrics, research scripts, and ops that mirror CLI workflows.
- Limitations/Trade-offs: No on-chain execution; wallet-adapter and browser UX are weaker than the TS kit; public RPC rate limits punish naive bots; key management and blockhash expiry are production problems you own.
- Related Topics: Python for Solana Basics, solders & solana-py, Building Transactions in Python, AnchorPy, Reading Chain Data, Data Analysis.
Foundations
Solana program source is Rust 1.91.1 targeting sBPF. Python never enters that compile path. Your process is a normal host runtime that:
- Connects to RPC (HTTP and optional WebSocket).
- Deserializes accounts and transaction meta.
- Builds instructions and messages with solders types.
- Signs with keypairs you control (or returns unsigned txs for user wallets).
- Submits and confirms against cluster commitment levels.
That separation is the whole model. Durable app state lives in accounts. Programs mutate them. Python observes, schedules, and sometimes signs.
The default Python stack is:
| Package | Role |
|---|---|
| solders | Fast Rust-backed types: Pubkey, Keypair, Instruction, messages, versioned txs, system and compute-budget helpers |
solana (solana-py) | JSON-RPC client (Client / AsyncClient), TxOpts, subscriptions |
| anchorpy | Load Anchor IDL, typed program.rpc / account fetch, Provider + Wallet |
Pin RPC URLs and program IDs per environment. Dev scripts should not silently point at mainnet-beta. For local work, combine Solana CLI 3.0.10 (solana-test-validator or team Surfpool / LiteSVM workflows for programs) with a Python venv for client code.
Money is always integers: lamports and token base units. Never use floats for balances, fees, or PnL that must match the chain.
Mechanics & Interactions
solders and solana-py
solders is the type and serialization layer. It mirrors Solana primitives with Rust performance across the Python boundary. Prefer solders constructors for instructions, account metas, and message packing rather than hand-rolling wire formats.
solana-py (import path solana) is the network layer. Use it to:
get_latest_blockhash,get_balance,get_account_infosimulate_transactionandsend_transactionget_signatures_for_address,get_transaction- Async websockets for account and signature notifications
Modern solana-py expects solders types. Treat them as one stack, not competing SDKs. Details and copy-paste recipes live in solders & solana-py.
Building and sending transactions
The happy path for a Python-built transaction:
- Compose instructions (System Program transfer, SPL Token, Anchor program ix, compute budget).
- Fetch a recent blockhash from RPC.
- Build a message with fee payer and ix list (
Message.new_with_blockhashor versioned message APIs). - Sign into a
VersionedTransaction(or legacy only when a dependency forces it). - Simulate (preflight or explicit simulate) and inspect logs / CU.
- Send with commitment and retry policy; refresh blockhash on expiry.
Priority fees and compute limits are ordinary instructions (solders compute-budget helpers). Place them early in the message. Long-running bots must treat blockhash lifetime and duplicate-signature rules as core control-loop concerns, not edge cases.
Full composition patterns are in Building Transactions in Python.
AnchorPy and Anchor programs
If the on-chain program is Anchor 0.32.1, ship the IDL from anchor build and load it with AnchorPy. That gives you:
- Instruction builders with discriminators matching the program
- Account clients for
fetch/ decode Providerbinding of RPC client, wallet, and default options
Workflow:
- Build and deploy the program (Rust + Anchor + CLI).
- Version the IDL JSON with the program ID for each cluster.
- In Python:
Provider+Program.at(...)or explicitIdl.from_json. - Call
program.rpc["instruction_name"](...)or build instructions for custom batching.
Regenerate clients when the IDL changes. Mismatched discriminators or account order fail at simulation or runtime. AnchorPy sits on solders/solana-py; you still own blockhash, simulation, and confirmation. See AnchorPy.
Reading chain data
Reads dominate most production Python services.
Core RPC
- Account bytes and lamports:
get_account_info(raw or jsonParsed where supported) - Native balance:
get_balance - SPL holdings:
get_token_accounts_by_owner(and jsonParsed variants) - History:
get_signatures_for_addressthenget_transaction - Scans:
get_program_accountswith memcmp filters on discriminators or fixed fields
DAS (Digital Asset Standard)
NFT and cNFT portfolios often need a provider DAS endpoint (getAsset, search, proofs). Use httpx or similar HTTP clients when solana-py does not wrap the method; keep DAS URLs and API keys out of git.
Production read habits
- Prefer async clients under concurrent load
- Bound
get_program_accountswith filters; do not dump whole programs on public RPC - For heavy analytics, use indexers or warehouse exports instead of scraping mainnet live
- Decode account layouts with solders, Borsh helpers, or AnchorPy account types - not ad-hoc string splits
Deep dives: Reading Chain Data.
Analytics pipelines
Python's comparative advantage is the data stack: pandas, Polars, NumPy, notebooks, and ML tooling.
Typical flow:
- Collect signatures or account snapshots (RPC, websocket buffer, or indexer dump).
- Normalize rows: signature, slot, fee, success, program id, parsed fields.
- Load into Polars (large batches) or pandas (exploratory notebooks).
- Join off-chain tables (users, campaigns, risk scores).
- Publish metrics, alerts, or training features.
Treat chain time (slots, block times) carefully; join keys are usually pubkey, signature, or mint. Lamports stay integers until presentation. Patterns and framing: Data Analysis.
Ops alignment with CLI and validators
Python scripts should agree with how operators use Solana CLI 3.0.10: same RPC URL, same keypair JSON format (Keypair.from_bytes on the 64-byte secret array), same cluster (devnet / mainnet-beta / local). Agave 4.1.1 RPC semantics (commitment, simulation meta, compute unit reporting) are what your client must handle - not a separate "Python Solana."
Advanced Considerations & Applications
When Python vs TypeScript (@solana/kit 7.0.0)
| Need | Prefer | Why |
|---|---|---|
| Wallet connect, browser dApp, Action/Blink POST in Next.js | @solana/kit 7.0.0 | Wallet standards, web ecosystem, this site's default frontend stack |
| Bots, batch jobs, ML, pandas/Polars research | Python | Async services + data science libraries |
| Shared monorepo of TS services and web | Kit (or dual clients) | One language for product path |
| Existing Python FastAPI/Django estate | Python | Reuse auth, queues, and observability |
| Codama / Kit-first typed clients for many programs | Kit | Stronger codegen story in the TS world |
| Anchor IDL calls from a research laptop | AnchorPy | Fast path without a frontend |
Many orgs run both: Kit in the user-facing app; Python for market data, risk, rebalancing, and ops. The wire format is the same - versioned transactions and RPC JSON. Do not invent a second program interface per language; share program IDs, IDL versions, and account layout docs.
Architecture patterns that age well
- Hot wallet + policy: bots hold low balance keys; cold or multisig for treasury moves.
- Build unsigned, sign elsewhere: backends prepare messages; HSMs or user wallets sign.
- Simulate always on money paths: preflight catches missing accounts, CU overruns, and bad PDAs before fees.
- Confirm with purpose:
processedfor snappy UX is not settlement for accounting; pick commitment per risk. - Idempotent strategies: retries must not double-spend; use client-side order ids and on-chain uniqueness where programs allow.
- Observability: log slot, blockhash age, priority fee, simulation logs, and signature status on every failure class.
Bots and automation (scope preview)
Trading and automation glue RPC reads, transaction builders, and risk limits into a control loop. That sits on the same foundations as this overview; section pages for trading and best practices cover pacing, priority fees, and failure handling without turning Python into a strategy black box.
Hybrid with Anchor and native programs
Python does not care whether the program is Anchor, native solana-program, or Pinocchio. You need correct program id, account metas, and instruction bytes. AnchorPy reduces that cost for Anchor IDLs. For native programs, hand-build with solders or maintain small codecs shared with Rust tests.
Common Misconceptions
- "Python can run on-chain if I use the right library." No. Only sBPF programs execute in the SVM. Python is always a client.
- "solders and solana-py are alternatives." They are complementary: types vs RPC. Modern stacks use both.
- "If it works on web3.js examples, the Python port is one-to-one." Field names, transaction shapes, and async APIs differ. Follow solders message APIs end to end.
- "AnchorPy replaces understanding accounts and discriminators." It generates convenience over the same wire rules; bad IDLs still produce bad txs.
- "Public free RPC is fine for production bots." Rate limits and noisy neighbors break latency-sensitive loops. Budget a provider.
- "skip_preflight speeds me up safely." It can hide failures you would have caught for free. Use it only with eyes open.
- "Floats are OK for USDC amounts in pandas." Prefer integer base units through computation; format for display last.
- "getProgramAccounts is free analytics." Unfiltered scans are heavy; providers throttle or reject them. Prefer filters or indexers.
- "TypeScript is always better for Solana." Kit wins for wallets and web. Python wins for data and many backend estates. Choose by surface, not fashion.
- "One mainnet keypair in a notebook is fine for demos." Notebooks leak. Use env secrets and dedicated low-privilege keys.
FAQs
What is Python for on Solana if programs are Rust?
Off-chain work: reading accounts, building and sending transactions, calling programs via RPC/IDL, running bots, backends, and analytics. Programs stay Rust (or other sBPF toolchains).
What should I install first?
A venv, then solders and solana (solana-py). Add anchorpy when you call Anchor programs. Add httpx, pandas or polars for DAS and analytics.
Is solders required with solana-py?
Yes for modern solana-py: core types and serialization come from solders. Learn both packages as one stack.
When do I need AnchorPy?
When you invoke Anchor 0.32.1 programs and want IDL-driven instruction and account clients instead of manual discriminators and account metas.
How do I build a transfer or multi-instruction transaction?
Compose solders instructions, fetch a recent blockhash, build a message, sign a versioned transaction, simulate, then send via solana-py. See Building Transactions in Python.
How should I read token balances and NFT holdings?
Use RPC token account methods for SPL balances and a DAS-capable provider for NFT/cNFT metadata and compression-aware queries. See Reading Chain Data.
Can I use Python for a wallet-connected browser dApp?
Possible but awkward. Prefer @solana/kit 7.0.0 (and wallet adapters) in the browser; keep Python for servers and bots that do not need in-page wallet UX.
How do Python services relate to Agave 4.1.1?
They are RPC clients of Agave nodes (or compatible providers). Commitment levels, simulation results, and fee markets match cluster behavior - not a Python-specific chain.
What about key management?
Load Solana CLI-compatible keypair JSON only in secure environments. Prefer env vars or a secrets manager. Never commit key files. Use hot wallets with limited funds for bots.
Why do my transactions expire?
Blockhashes are short-lived. Long event loops must refresh blockhashes and resign. Retry policies should detect expiry and rebuild, not resubmit a stale signature forever.
How do I analyze protocol activity in notebooks?
Pull bounded signature or account samples (or indexer CSV/Parquet), normalize integer amounts, then aggregate in pandas/Polars. See Data Analysis.
Should bots use sync or async clients?
Prefer AsyncClient when you poll many accounts, fan out RPC, or mix websockets with sends. Sync Client is fine for short scripts.
Where should a new teammate start in this section?
This overview, then Python for Solana Basics, then solders/solana-py, transactions, AnchorPy, reads, and analytics as your role requires.
Do I need Solana CLI installed to use Python?
Not strictly for RPC-only scripts, but CLI 3.0.10 is invaluable for keygen, airdrops on devnet, config, and aligning cluster settings with your Python env.
Can Python deploy programs?
Deployment is a CLI / toolchain concern (solana program deploy, Anchor deploy). Python can wrap subprocess calls in ops automation; it does not replace cargo build-sbf.
Related
- Python for Solana Basics - short examples for fits, RPC, txs, AnchorPy, and data
- solders & solana-py - primitives, RPC client, and the default SDK pair
- Building Transactions in Python - instructions, signing, simulation, and send
- AnchorPy - IDL clients for Anchor 0.32.1 programs
- Reading Chain Data - accounts, tokens, signatures, and DAS
- Data Analysis - RPC and indexer data into pandas/Polars
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, Rust 1.91.1, and @solana/kit 7.0.0.