Skip to main content

High-performance JSON-RPC client — HTTP, WebSocket, provider pool with circuit breaker

Project description

ChainRPC

Production-grade, multi-provider RPC transport layer for EVM blockchains.

crates.io docs.rs npm PyPI License: MIT

Built-in retry, circuit breaker, rate limiting, tiered caching, request deduplication, auto-batching, multi-chain routing, MEV protection, and Prometheus metrics — all composable via a single Arc<dyn RpcTransport> trait.

DedupTransport(CacheTransport(BackpressureTransport(ProviderPool(HttpRpcClient))))

Every layer wraps Arc<dyn RpcTransport> and itself implements RpcTransport. Stack what you need, skip what you don't.


Quick Start

Rust

# Cargo.toml
[dependencies]
chainrpc-core = "0.1"
chainrpc-http = "0.1"
use chainrpc_http::HttpRpcClient;
use chainrpc_core::transport::RpcTransport;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let client = HttpRpcClient::default_for("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY");

    // Typed call — auto-deserializes the response
    let block: String = client.call(1, "eth_blockNumber", vec![]).await?;
    println!("Latest block: {block}");

    Ok(())
}

Multi-Provider Failover

use chainrpc_http::pool_from_urls;

let pool = pool_from_urls(&[
    "https://eth-mainnet.g.alchemy.com/v2/KEY1",
    "https://mainnet.infura.io/v3/KEY2",
    "https://rpc.ankr.com/eth",
])?;

// Round-robin with automatic failover when a provider's circuit breaker opens
let block = pool.send(JsonRpcRequest::auto("eth_blockNumber", vec![])).await?;
println!("Healthy: {}/{}", pool.healthy_count(), pool.len());

Tiered Caching + Dedup

use chainrpc_core::cache::{CacheTransport, CacheConfig, CacheTierResolver};
use chainrpc_core::dedup::DedupTransport;

// Cache with smart tier resolution:
//   eth_getTransactionReceipt → Immutable (1h TTL)
//   eth_blockNumber → Volatile (2s TTL)
//   eth_sendRawTransaction → NeverCache
let cached = CacheTransport::new(Arc::new(client), CacheConfig {
    tier_resolver: Some(CacheTierResolver::new()),
    max_entries: 4096,
    ..Default::default()
});

// Deduplicate concurrent identical requests
let dedup = DedupTransport::new(Arc::new(cached));

Features

Policy Engine

  • Rate Limiter — Token-bucket with CU-aware mode (knows eth_getLogs = 75 CU, eth_blockNumber = 10 CU)
  • Circuit Breaker — Three-state (Closed/Open/HalfOpen), configurable failure threshold and reset timeout
  • Retry Policy — Exponential backoff with jitter, respects method safety (never retries eth_sendTransaction)
  • Method Safety — Classifies 40+ EVM methods as Safe / Idempotent / Unsafe

Provider Pool

  • 5 selection strategies: RoundRobin, Priority, WeightedRoundRobin, LatencyBased, Sticky
  • Per-provider circuit breaker + automatic failover
  • Atomic metrics (success/failure counts, latency, rate-limit hits)
  • Background health checking

Caching & Dedup

  • 4-tier cache: Immutable (1h), SemiStable (5m), Volatile (2s), NeverCache
  • Smart tier resolution based on method + parameters
  • Reorg-aware invalidation (invalidate_for_reorg(block))
  • Request deduplication (N concurrent callers = 1 HTTP call)

Advanced

  • Auto-Batching — Collects individual calls into JSON-RPC batch requests within a time window
  • Multi-Chain Router — Route by chain ID, parallel cross-chain queries
  • Request Hedging — Race primary + backup, return first response
  • Backpressure — Concurrency limiting, fail-fast when overloaded
  • Archive Routing — Route historical queries to archive nodes
  • MEV Protection — Detect 12 MEV-susceptible selectors, route to private relays
  • Gas Estimation — EIP-1559 recommendations (Slow/Standard/Fast/Urgent)
  • Tx Lifecycle — Send, track, poll receipt, detect stuck, nonce management, gas bumping
  • CU Budget Tracking — Monitor compute unit consumption against monthly budgets
  • Solana Support — Commitment levels (Processed/Confirmed/Finalized), 50+ method safety classification, CU costs
  • Geo-Aware Routing — Route to geographically closest provider with automatic proximity-based fallback
  • Gas Bumping — Speed up or cancel stuck transactions with EIP-1559 compliant replacement (Percentage/Double/SpeedTier/Cancel)
  • Reorg Detection — Sliding block hash window, configurable safe depth, reorg callbacks for cache invalidation

Lifecycle & Observability

  • Graceful shutdown with signal handling and drain timeout
  • Cooperative cancellation tokens (parent/child hierarchy)
  • Per-provider Prometheus metrics export
  • Structured tracing integration

Crate Structure

chainrpc/
  crates/
    chainrpc-core/       # 31 modules — trait, types, all middleware
    chainrpc-http/       # HTTP transport (reqwest) with retry loop
    chainrpc-ws/         # WebSocket transport (tokio-tungstenite)
    chainrpc-providers/  # Pre-configured Alchemy, Infura, Ankr profiles
  bindings/
    node/                # TypeScript (napi-rs)
    python/              # Python (PyO3 + maturin)
    go/                  # Go (cgo)
    java/                # Java (JNI)
  cli/                   # CLI tool (call, pool, bench)
  examples/              # 26 runnable examples
  docs/                  # Architecture, modules, API reference

Examples

26 examples covering every module. See examples/README.md for the full index.

Category Examples
Basics Simple Client
Caching Tiered Cache
Cost Control Rate Limiting
Routing Multi-Chain
EVM Gas
Lifecycle Shutdown
New Modules Solana RPC

Documentation

Document Description
Architecture System diagram, crate structure, request flow, design principles
Modules Detailed reference for all 31 modules with public API
API Reference Quick-lookup tables for every type, trait, and function
Use Cases 20 real-world patterns with complete Rust code
Implementation Design decisions, concurrency patterns, internals

Language Bindings

Language Package Install
TypeScript @chainfoundry/chainrpc npm install @chainfoundry/chainrpc
Python chainrpc pip install chainrpc
Go chainrpc go get github.com/DarshanKumar89/chainfoundry/chainrpc
Java chainrpc Maven / Gradle

Test Coverage

262 tests, 0 failures

chainrpc-core:      250 tests (all 31 modules)
chainrpc-providers:   6 tests (URL construction)
chainrpc-ws:          3 tests (subscription management)
Doc-tests:            3 tests
cd chainrpc && cargo test --workspace

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

chainfoundry_chainrpc-0.2.1-cp311-cp311-win_amd64.whl (1.7 MB view details)

Uploaded CPython 3.11Windows x86-64

chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_11_0_arm64.whl (1.6 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_10_12_x86_64.whl (1.7 MB view details)

Uploaded CPython 3.11macOS 10.12+ x86-64

chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.7 MB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ x86-64

chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (1.7 MB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ ARM64

File details

Details for the file chainfoundry_chainrpc-0.2.1-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for chainfoundry_chainrpc-0.2.1-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 97d47a3f81578e539a6614facb58f7ad9c936e7b0d44e8fc1d46ad7a60f4a615
MD5 720d282db73b35fe6fb4b9d357dfff38
BLAKE2b-256 66b3f59b39e4e459ec0b9c6291001f5da250de72c2ba1abc485f1068f109a0cb

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainfoundry_chainrpc-0.2.1-cp311-cp311-win_amd64.whl:

Publisher: publish-chainrpc.yml on DarshanKumar89/chainfoundry

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 e9a4226df59aee209ca8b4ed397f6809eddf7d61b50ee40be3346c3517fc88a1
MD5 9eb197f189476052ce9a3e5796360f16
BLAKE2b-256 d54536f32c220cfbbbf5f6a1a94888c82245458d6171fc1fd72baaa6c142e014

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_11_0_arm64.whl:

Publisher: publish-chainrpc.yml on DarshanKumar89/chainfoundry

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 b5a3868723016631cacafd8b4d980535beb6c4a8ff779aca792c9a0426499e20
MD5 ba0fa591d472b5b4790b0e993108c787
BLAKE2b-256 f2b523c6f14552f4d9784afeffc815b8cd6435be73fd9ef7c1dd223d752ed03f

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainfoundry_chainrpc-0.2.1-cp311-cp311-macosx_10_12_x86_64.whl:

Publisher: publish-chainrpc.yml on DarshanKumar89/chainfoundry

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 e1ad0190c90a109dea6ca89cda2225bed25e880ad8abdc6cad84991202f2c1f8
MD5 60c003d463561680b5a4efa0ed047121
BLAKE2b-256 02769e9037c31d9eec1c82c276009027423a35e917fc0b317910e464fd7aa035

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: publish-chainrpc.yml on DarshanKumar89/chainfoundry

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 218ca4de576f9a9f58cff91abb67c5e8911cede9589aa605adf077cd55f76754
MD5 62d6d60c4185fc439ff1b5b0fcd8c3ab
BLAKE2b-256 1a30bf94502559aa4ec89afea31c3b95482975725680c6cfaf3d4f62c9b83d51

See more details on using hashes here.

Provenance

The following attestation bundles were made for chainfoundry_chainrpc-0.2.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: publish-chainrpc.yml on DarshanKumar89/chainfoundry

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page