boltAsync Patterns

Best practices for async usage - concurrent operations, error handling, connection pooling

This example demonstrates best practices for using the async Seismic client including concurrent operations, proper resource management, error handling, and WebSocket connections.

Prerequisites

# Install the SDK with async support
pip install seismic-web3

# Set environment variables
export PRIVATE_KEY="your_64_char_hex_private_key"
export RPC_URL="https://gcp-1.seismictest.net/rpc"
export WS_URL="wss://gcp-1.seismictest.net/ws"
export CONTRACT_ADDRESS="0x..."

Basic Async Client Setup

import asyncio
import os
from seismic_web3 import create_async_wallet_client, PrivateKey


async def main():
    private_key = PrivateKey.from_hex_str(os.environ["PRIVATE_KEY"])

    # Create async client
    w3 = await create_async_wallet_client(
        os.environ["RPC_URL"],
        private_key=private_key,
    )

    try:
        # All operations must be awaited
        chain_id = await w3.eth.chain_id
        block_number = await w3.eth.block_number
        print(f"Connected to chain {chain_id}, block {block_number}")

    finally:
        # Always disconnect to clean up resources
        await w3.provider.disconnect()


if __name__ == "__main__":
    asyncio.run(main())

Concurrent Operations

Execute multiple independent operations in parallel for better performance:

Concurrent Writes with Progress Tracking

Error Handling with Retries

Context Manager Pattern

WebSocket Connection for Events

Connection Pooling Pattern

Timeout Handling

Rate Limiting

Complete Production-Ready Pattern

Expected Output

Best Practices

  1. Always disconnect - Use finally blocks or context managers

  2. Concurrent operations - Use asyncio.gather() for independent operations

  3. Error handling - Implement retries with exponential backoff

  4. Timeouts - Set reasonable timeouts for all operations

  5. Rate limiting - Respect RPC provider rate limits

  6. Connection pooling - For high-throughput applications

  7. WebSocket for events - Use WebSocket connections for event streaming

  8. Logging - Add comprehensive logging for production

Next Steps

See Also

Last updated