Python for Solana Best Practices
Rules for production-grade Python services talking to Agave 4.1.1 RPC: correct math, safe keys, resilient sends, and observable failures.
How to Use This List
- Apply to every bot, backend, and ETL job before mainnet enablement.
- Pair with code review focusing on signing, fees, and retry logic.
- Revisit when RPC provider, Anchor IDL, or fee market behavior changes.
A - Security & Keys
- Never commit keypairs or API keys. Use env vars, secret managers, or HSM-backed signers.
- Isolate hot wallets per strategy with spend caps. Limits blast radius on bug or key leak.
- Run bots under dedicated service accounts. Not developer laptops in production.
- Validate pubkeys before building instructions.
Pubkey.from_stringcatches malformed input early. - Redact secrets from logs. Strip key material and provider API keys from error traces.
B - RPC & Data
- Use private RPC with SLA for mainnet bots. Public endpoints rate-limit and lag.
- Set commitment explicitly per call.
confirmedfor trading;finalizedfor accounting. - Throttle and backoff on 429/5xx. Jitter prevents thundering herds across replicas.
- Avoid unfiltered
getProgramAccounts. Use memcmp filters or an indexer. - Cache immutable account data. Mint decimals and program IDs rarely change.
C - Transactions
- Simulate before every mainnet send. Read logs on failure - do not retry blindly.
- Refresh blockhash on each retry. Expired blockhashes guarantee failure.
- Set compute unit limit and price explicitly. Do not rely on defaults during congestion.
- Use integer lamports end-to-end. No floats in amount calculations.
- Confirm transactions with timeouts. Track stuck signatures and alert operators.
D - AnchorPy & IDL
- Pin IDL JSON to deployed program hash. Regenerate on Anchor 0.32.1 upgrades.
- Separate configs per cluster. Devnet and mainnet program IDs differ.
- Use AsyncClient throughout asyncio code. No blocking RPC in event loops.
E - Operations
- Structured logging with signature, slot, and fee. Enables incident correlation.
- Export metrics: send success rate, sim failure reasons, RPC latency. Dashboards beat grep.
- Version-pin dependencies in
requirements.txtor Poetry lock. Reproducible deploys. - Dry-run on devnet or Surfpool 0.12.0 fork before mainnet. Validate account metas cheaply.
FAQs
Minimum monitoring?
Send success rate, wallet balance, RPC error rate, confirmation latency p95.
How many RPC endpoints?
Primary + fallback; health-check and circuit-break between them.
Process manager?
systemd, Kubernetes, or supervisor with restart limits - not bare tmux on prod.
Testing strategy?
Unit-test pure functions; integration-test against local validator with funded keypair.
Dependency audit?
Run pip audit in CI; solders/solana-py updates may change serialization.
Multiprocessing?
Prefer asyncio; if multiprocessing, never fork after loading keypairs into memory.
Idempotency?
Track submitted signatures; dedupe triggers on webhook retries.
Compliance retention?
Define log retention for signatures and amounts per policy.
When to rewrite in Rust?
When profiling shows Python overhead dominates - not preemptively.
Align with TS clients?
Share IDL and env naming with @solana/kit 7.0.0 frontend for fewer drift bugs.
Related
- Python for Solana Basics - section intro
- Building Transactions in Python - tx patterns
- Trading & Bots - automation architecture
- Priority Fees Best Practices - landing txs
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.