Pyth Lazer Rust Client
A high-performance Rust client for connecting to Pyth Lazer real-time data streams. This client provides reliable, low-latency access to Pyth's oracle price feeds with built-in redundancy and automatic failover.
Features
- Multiple redundant WebSocket connections - Maintains 4 concurrent connections by default for high availability
- Automatic message deduplication - Uses TTL-based caching to eliminate duplicate messages across connections
- Exponential backoff reconnection - Automatically handles connection failures with configurable retry logic
- Flexible subscription options - Support for multiple data formats (EVM, Solana, etc.) and delivery channels
- History API client - Fetch symbol metadata and historical price information
- Type-safe API - Strongly-typed Rust interface with comprehensive error handling
Installation
Add the following to your Cargo.toml:
[]
= "8.2.2"
= "0.16.0"
= { = "1", = ["full"] }
Authentication
To use the Pyth Lazer client, you need an access token. Set your access token via the LAZER_ACCESS_TOKEN environment variable:
Or provide it directly in your code:
use PythLazerStreamClientBuilder;
let access_token = var
.expect;
let client = new
.build?;
Quick Start
Here's a minimal example to get started with streaming price feeds:
use PythLazerStreamClientBuilder;
use ;
use ;
use FixedRate;
async
Configuration
The PythLazerStreamClientBuilder provides several configuration options:
Custom Endpoints
Override the default production endpoints:
let client = new
.with_endpoints
.build?;
Number of Connections
Set the number of concurrent WebSocket connections (default: 4):
let client = new
.with_num_connections
.build?;
Connection Timeout
Configure the timeout for WebSocket operations (default: 5 seconds):
use Duration;
let client = new
.with_timeout
.build?;
Exponential Backoff
Customize the reconnection backoff strategy:
use PythLazerExponentialBackoffBuilder;
let backoff = default
.build;
let client = new
.with_backoff
.build?;
Channel Capacity
Set the internal message buffer size (default: 1000):
let client = new
.with_channel_capacity
.build?;
Subscription Options
Channels
Choose the update frequency for your price feeds:
Channel::RealTime- Receive updates as soon as they're availableChannel::FixedRate(FixedRate::RATE_50_MS)- Updates every 50msChannel::FixedRate(FixedRate::RATE_200_MS)- Updates every 200ms (recommended for most use cases)Channel::FixedRate(FixedRate::RATE_1000_MS)- Updates every 1000ms
use Channel;
use FixedRate;
// Real-time updates
let channel = RealTime;
// Fixed rate updates
let channel = FixedRate;
Formats
Specify the signature format for the price data:
Format::Evm- EVM-compatible format with secp256k1 signaturesFormat::Solana- Solana-compatible format with Ed25519 signaturesFormat::LeEcdsa- Little-endian ECDSA formatFormat::LeUnsigned- Little-endian unsigned format
use Format;
let formats = vec!;
Delivery Format
Choose how messages are delivered:
DeliveryFormat::Json- Receive updates as JSON text messages (default)DeliveryFormat::Binary- Receive updates as binary messages (more efficient)
use DeliveryFormat;
let delivery_format = Binary;
Properties
Select which price feed properties to receive:
PriceFeedProperty::Price- Current pricePriceFeedProperty::BestBidPrice- Best bid pricePriceFeedProperty::BestAskPrice- Best ask pricePriceFeedProperty::PublisherCount- Number of contributing publishersPriceFeedProperty::Exponent- Price exponentPriceFeedProperty::Confidence- Confidence intervalPriceFeedProperty::FundingRate- Funding rate (for perpetual markets)PriceFeedProperty::FundingTimestamp- Funding rate timestampPriceFeedProperty::FundingRateInterval- Funding rate update interval
use PriceFeedProperty;
let properties = vec!;
Identifying Price Feeds
Subscribe to feeds using either price feed IDs or symbols:
// By price feed ID
let params = SubscriptionParamsRepr ;
// By symbol
let params = SubscriptionParamsRepr ;
Examples
Comprehensive Streaming Example
See examples/subscribe_price_feeds.rs for a complete example demonstrating:
- Client configuration with multiple connections
- Subscribing to price feeds with different formats
- Processing JSON and binary updates
- Verifying message signatures
- Unsubscribing from feeds
Run the example:
Symbol Metadata
Fetch symbol metadata using the history client:
use ;
let client = new;
// Get all symbol metadata
let symbols = client.all_symbols_metadata.await?;
// Or get an auto-updating handle
let handle = client.all_symbols_metadata_handle.await?;
let symbols = handle.symbols;
See examples/symbols.rs and examples/symbols_stream.rs for complete examples.
History Client
The PythLazerHistoryClient provides access to symbol metadata and historical price information:
use ;
use Duration;
let config = PythLazerHistoryClientConfig ;
let client = new;
// Fetch symbol metadata once
let symbols = client.all_symbols_metadata.await?;
// Or get an auto-updating handle that refreshes in the background
let handle = client.all_symbols_metadata_handle.await?;
// Or get a stream of updates
let mut stream = client.all_symbols_metadata_stream.await?;
while let Some = stream.recv.await
The history client supports:
- One-time fetches - Get current data with
all_symbols_metadata() - Auto-updating handles - Background updates with
all_symbols_metadata_handle() - Streaming updates - Receive updates via channels with
all_symbols_metadata_stream() - Local caching - Optional disk cache for offline access
- Fault tolerance - Graceful fallback to cached data on network failures
API Reference
Main Types
PythLazerStreamClient- The main client for streaming price updatesPythLazerStreamClientBuilder- Builder for configuring the stream clientPythLazerHistoryClient- Client for fetching symbol metadataSubscribeRequest- Subscription configurationSubscriptionParams- Subscription parameters wrapperAnyResponse- Enum for JSON or binary responses
Core Methods
PythLazerStreamClient
start() -> Result<Receiver<AnyResponse>>- Start the client and return message receiversubscribe(request: SubscribeRequest) -> Result<()>- Subscribe to price feedsunsubscribe(id: SubscriptionId) -> Result<()>- Unsubscribe from a feed
PythLazerHistoryClient
all_symbols_metadata() -> Result<Vec<SymbolMetadata>>- Fetch all symbols onceall_symbols_metadata_handle() -> Result<SymbolMetadataHandle>- Get auto-updating handleall_symbols_metadata_stream() -> Result<Receiver<Vec<SymbolMetadata>>>- Get update stream
For complete API documentation, visit docs.rs/pyth-lazer-client.
License
This project is licensed under the Apache-2.0 License. See the LICENSE file for details.