Official TypeScript/JavaScript client for the EthPending API - Monitor and stream Ethereum pending transactions from the mempool before they are mined into blocks.
Stream Ethereum pending transactions, detect MEV opportunities, monitor DeFi protocols, track whale movements, and analyze gas prices in real-time.
Pending transactions (also known as the mempool) contain valuable information before blocks are mined:
- π MEV Opportunities - Detect arbitrage and front-running opportunities
- π Whale Watching - Track large transfers and significant movements
- π± DeFi Monitoring - Monitor DEX swaps, liquidity changes, and protocol interactions
- π¨ NFT Tracking - Detect NFT mints, sales, and transfers in real-time
- β½ Gas Analytics - Analyze gas prices and network congestion
- π Security - Detect suspicious transactions and potential exploits
- π Market Intelligence - Gain insights before transactions are confirmed
- π Real-time WebSocket streaming - Sub-second latency for pending transactions
- π HTTP REST API - Poll for pending transactions on-demand
- π Advanced filtering - Filter by contract addresses and method signatures
- π Built-in metrics - Track connection health, uptime, and performance
- π Automatic reconnection - Exponential backoff with jitter
- πͺ Full TypeScript support - Complete type definitions included
- π Universal compatibility - Works in Node.js and browsers
- β‘ Minimal dependencies - Only
wsfor Node.js WebSocket support - π‘οΈ Production-ready - Error handling, retry logic, and connection management
- Installation
- Quick Start
- Use Cases
- WebSocket Client
- HTTP Client
- Filtering
- Advanced Features
- TypeScript Support
- Error Handling
- Examples
- API Reference
- Best Practices
npm install ethpendingOr using yarn:
yarn add ethpendingGet your API key at ethpending.com
The fastest way to start monitoring Ethereum pending transactions:
const { WebSocketClient } = require('ethpending');
const client = new WebSocketClient('your-api-key');
client.on('transaction', (tx) => {
console.log('Pending tx:', tx.txHash);
console.log('From:', tx.from, 'β To:', tx.to);
console.log('Value:', tx.value, 'wei');
});
await client.connect();import { WebSocketClient } from 'ethpending';
const client = new WebSocketClient('your-api-key');
// Listen for transactions
client.on('transaction', (tx) => {
console.log('New transaction:', tx.txHash);
console.log('Success:', tx.success);
console.log('Events:', tx.logs.length);
});
// Connect to the stream
await client.connect();import { HTTPClient } from 'ethpending';
const client = new HTTPClient('your-api-key');
// Fetch pending transactions
const response = await client.fetchTransactions({
limit: 100,
});
console.log(`Found ${response.transactions.length} transactions`);
// Or start polling
const stopPolling = client.startPolling(5000, (response) => {
response.transactions.forEach(tx => {
console.log('Transaction:', tx.txHash);
});
});const client = new WebSocketClient('your-api-key', {
wsUrl: 'wss://api.ethpending.com/ws', // WebSocket URL
autoReconnect: true, // Auto-reconnect on disconnect
maxReconnectAttempts: Infinity, // Max reconnection attempts
reconnectDelay: 1000, // Initial reconnection delay (ms)
maxReconnectDelay: 60000, // Max reconnection delay (ms)
heartbeatInterval: 30000, // Heartbeat interval (ms)
connectionTimeout: 10000, // Connection timeout (ms)
});// Connection events
client.on('connected', () => {
console.log('Connected to WebSocket');
});
client.on('disconnected', (code, reason) => {
console.log(`Disconnected: ${code} - ${reason}`);
});
client.on('reconnecting', (attempt) => {
console.log(`Reconnecting... (attempt ${attempt})`);
});
// Transaction events
client.on('transaction', (tx) => {
console.log('New transaction:', tx);
});
// Filter subscription
client.on('subscribed', (filters) => {
console.log('Subscribed with filters:', filters);
});
// Error events
client.on('error', (error) => {
console.error('Error:', error);
});
// State change events
client.on('stateChange', (oldState, newState) => {
console.log(`State: ${oldState} β ${newState}`);
});// Connect to the WebSocket server
await client.connect();
// Disconnect from the server
client.disconnect();
// Set transaction filters
client.setFilters({
addresses: ['0x...', '0x...'], // Filter by contract addresses
methods: ['0xabcd...'], // Filter by method signatures
});
// Get connection metrics
const metrics = client.getMetrics();
console.log('Messages received:', metrics.messagesReceived);
console.log('Uptime:', metrics.uptime);
console.log('Connection state:', metrics.connectionState);
// Check connection state
const isConnected = client.isConnected();
const state = client.getConnectionState();const client = new HTTPClient('your-api-key', 'https://api.ethpending.com');// Fetch transactions with filters
const response = await client.fetchTransactions({
addresses: ['0x...'], // Optional: filter by addresses
methods: ['0xabcd...'], // Optional: filter by methods
limit: 100, // Optional: limit results
});
// Set default filters
client.setFilters({
addresses: ['0x...'],
methods: ['0xabcd...'],
});
// Get current filters
const filters = client.getFilters();
// Start polling
const stopPolling = client.startPolling(
5000, // Poll interval (ms)
(response) => { // Callback
console.log('Transactions:', response.transactions);
},
{ // Optional filters
limit: 50,
}
);
// Stop polling
stopPolling();
// Get metrics
const metrics = client.getMetrics();
console.log('Average latency:', metrics.averageLatency);// Rate limit events
client.on('rateLimit', (retryAfter) => {
console.log(`Rate limited. Retry after ${retryAfter}ms`);
});
// Error events
client.on('error', (error) => {
console.error('Error:', error);
});Filter transactions by contract addresses and method signatures:
// Monitor Uniswap V3 Router swaps
const UNISWAP_V3_ROUTER = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
const SWAP_EXACT_INPUT = '0xc04b8d59';
const SWAP_EXACT_OUTPUT = '0xf28c0498';
client.setFilters({
addresses: [UNISWAP_V3_ROUTER],
methods: [SWAP_EXACT_INPUT, SWAP_EXACT_OUTPUT],
});
// Monitor USDC and USDT transfers
client.setFilters({
addresses: [
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
'0xdAC17F958D2ee523a2206206994597C13D831ec7', // USDT
],
});
// Clear filters
client.setFilters({});import { FilterManager } from 'ethpending';
const filterManager = new FilterManager();
// Set filters
filterManager.setFilters({
addresses: ['0x...'],
methods: ['0xabcd...'],
});
// Add more addresses
filterManager.addAddresses(['0x...']);
// Remove addresses
filterManager.removeAddresses(['0x...']);
// Add methods
filterManager.addMethods(['0xabcd...']);
// Check if filters are set
const hasFilters = filterManager.hasFilters();
// Get current filters
const filters = filterManager.getFilters();
// Convert to URL query parameters
const params = filterManager.toQueryParams();
// Clear all filters
filterManager.clearFilters();import { MetricsCollector } from 'ethpending';
const metrics = new MetricsCollector();
// Record events
metrics.recordMessageReceived();
metrics.recordMessageSent();
metrics.recordConnectionStart();
metrics.recordConnectionEnd();
metrics.recordReconnectAttempt();
metrics.recordError('ConnectionError');
metrics.recordLatency(123.45);
// Get metrics
const stats = metrics.getMetrics();
console.log('Messages received:', stats.messagesReceived);
console.log('Uptime:', stats.uptime);
console.log('Errors:', stats.errorsByType);
// Reset metrics
metrics.reset();import { retryWithBackoff, createRetryStrategy } from 'ethpending';
// Retry a function with exponential backoff
const result = await retryWithBackoff(
async () => {
// Your async operation
return await someAsyncOperation();
},
{
initialDelay: 1000, // Start with 1s
maxDelay: 60000, // Max 60s
maxAttempts: 5, // Try up to 5 times
multiplier: 2, // Double delay each time
jitter: true, // Add random jitter
}
);
// Create a reusable retry strategy
const retry = createRetryStrategy({
initialDelay: 2000,
maxAttempts: 3,
});
const result = await retry(async () => {
return await someAsyncOperation();
});import { ConnectionManager, ConnectionState } from 'ethpending';
const manager = new ConnectionManager();
// Listen for state changes
manager.on('stateChange', ({ oldState, newState }) => {
console.log(`State changed: ${oldState} β ${newState}`);
});
// Transition states
manager.connecting();
manager.connected();
manager.reconnecting();
manager.disconnecting();
manager.disconnected();
// Check state
const state = manager.getState();
const isConnected = manager.isConnected();
const isReconnecting = manager.isReconnecting();
// Reset to disconnected
manager.reset();Full TypeScript support with comprehensive type definitions:
import {
WebSocketClient,
HTTPClient,
PendingTransaction,
TransactionLog,
FilterOptions,
ClientConfig,
Metrics,
ConnectionState,
} from 'ethpending';
// All types are exported and availableimport {
EthPendingError,
ConnectionError,
ApiError,
RateLimitError,
AuthenticationError,
} from 'ethpending';
try {
await client.connect();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof ConnectionError) {
console.error('Connection failed:', error.message);
} else if (error instanceof RateLimitError) {
console.error('Rate limited. Retry after:', error.retryAfter);
} else if (error instanceof ApiError) {
console.error('API error:', error.statusCode, error.message);
}
}Monitor pending DEX swaps to detect arbitrage opportunities:
client.setFilters({
addresses: [
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', // Uniswap V2
'0xE592427A0AEce92De3Edee1F18E0157C05861564', // Uniswap V3
],
});
client.on('transaction', (tx) => {
// Analyze swap for arbitrage opportunities
if (tx.logs.length > 0) {
console.log('DEX swap detected:', tx.txHash);
}
});π See the complete example: get-pending-uniswap-swaps.ts
Track large transfers from known whale addresses:
const WHALES = ['0x...', '0x...'];
client.setFilters({ addresses: WHALES });
client.on('transaction', (tx) => {
const value = parseInt(tx.value || '0') / 1e18;
if (value > 100) { // More than 100 ETH
console.log(`π Large transfer: ${value} ETH`);
}
});Track NFT marketplace activity:
client.setFilters({
addresses: [
'0x00000000006c3852cbEf3e08E8dF289169EdE581', // OpenSea Seaport
'0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b', // OpenSea Legacy
],
});Monitor gas prices across pending transactions:
client.on('transaction', (tx) => {
if (tx.gasPrice) {
const gwei = parseInt(tx.gasPrice) / 1e9;
console.log(`Gas price: ${gwei} Gwei`);
}
});We provide 6 comprehensive, production-ready examples with detailed developer comments. Each example is designed to teach specific concepts and can be used as a starting point for your project.
| Example | Description | Use Case | Difficulty |
|---|---|---|---|
| get-pending-ethereum-transactions.js | π― Get Started - Stream all pending Ethereum transactions | General monitoring, analytics dashboards | β Beginner |
| get-pending-uniswap-swaps.ts | π¦ Uniswap DEX Monitor - Track Uniswap V2 & V3 swaps with event parsing | MEV, arbitrage, DeFi analytics | ββ Intermediate |
| websocket-basic.ts | π‘ WebSocket Basics - Real-time streaming fundamentals | Real-time monitoring, learning | β Beginner |
| websocket-filtered.ts | π Filtered Streaming - Monitor specific contracts and methods | Protocol monitoring, targeted tracking | ββ Intermediate |
| http-polling.ts | π HTTP Polling - Periodic transaction fetching | Serverless, batch processing | β Beginner |
| advanced-usage.ts | π Advanced Patterns - Fallback, caching, multi-client | Production deployments | βββ Advanced |
Each example includes:
- β Comprehensive inline comments explaining every concept
- β Developer tips for production deployments
- β Common patterns and best practices
- β Error handling strategies
- β Performance tips and optimization techniques
- β Real-world use cases and integration examples
Perfect for beginners - stream all pending transactions with detailed logging:
# JavaScript - runs directly with Node.js
export ETHPENDING_API_KEY=your-key
node examples/get-pending-ethereum-transactions.jsWhat it demonstrates:
- Basic WebSocket connection
- Transaction event handling
- Statistics tracking
- Graceful shutdown
Track DEX swaps on Uniswap V2 and V3 with automatic event parsing:
# TypeScript - comprehensive DEX monitoring
export ETHPENDING_API_KEY=your-key
npx tsx examples/get-pending-uniswap-swaps.tsWhat it demonstrates:
- Multiple contract filtering
- Method signature filtering
- Event log parsing
- Token extraction
- Real-time analytics
Learn how to efficiently filter transactions server-side:
export ETHPENDING_API_KEY=your-key
npx tsx examples/websocket-filtered.tsWhat it demonstrates:
- Server-side filtering
- Dynamic filter updates
- Bandwidth optimization
- Production-ready error handling
Use REST API for periodic checks - perfect for Lambda/serverless:
export ETHPENDING_API_KEY=your-key
npx tsx examples/http-polling.tsWhat it demonstrates:
- REST API usage
- Polling strategies
- Rate limit handling
- Deduplication logic
π― get-pending-ethereum-transactions.js - Best for beginners
File: examples/get-pending-ethereum-transactions.js
Lines: 180
Language: JavaScript (ES6)
This example is the perfect starting point for developers new to the library. It demonstrates:
- Basic WebSocket client setup
- Event listener registration
- Transaction data structure
- Real-time statistics tracking
- Clean shutdown handling
Key Features:
- No TypeScript required - runs with plain Node.js
- Detailed console output for learning
- Statistics dashboard (updates every 30s)
- Comprehensive error handling
Perfect for:
- Learning the API structure
- Quick prototyping
- Integration testing
- Monitoring dashboards
π¦ get-pending-uniswap-swaps.ts - Production-ready DEX monitor
File: examples/get-pending-uniswap-swaps.ts
Lines: 376
Language: TypeScript
A complete, production-ready example for monitoring Uniswap activity:
- Monitors Uniswap V2 + V3 routers
- Tracks 11 different swap methods
- Parses Swap and Transfer events
- Identifies common tokens (WETH, USDC, USDT, DAI)
- Real-time analytics and statistics
- Method distribution tracking
Key Features:
- Multi-version DEX support
- Event signature detection
- Token extraction from logs
- Gas price monitoring
- Comprehensive statistics
Perfect for:
- MEV bot development
- DEX analytics platforms
- Arbitrage opportunity detection
- Market making strategies
- DeFi research
Sample Output:
π Uniswap V3 Swap #42
Hash: 0xabc123...
Success: β
Method: exactInputSingle
Gas Price: 25.50 Gwei
Swap Events: 1
Token Transfers: 2
Tokens Involved:
β’ WETH
β’ USDC
π‘ websocket-basic.ts - Learn WebSocket fundamentals
File: examples/websocket-basic.ts
Lines: 178
Language: TypeScript
Educational example with extensive comments explaining every concept:
- Type-safe event handling
- Connection lifecycle management
- Automatic reconnection behavior
- Metrics monitoring
- Production deployment tips
Key Features:
- 100+ lines of inline documentation
- Explains every event type
- Shows transaction object structure
- Metrics dashboard implementation
- Production monitoring patterns
Perfect for:
- Learning WebSocket patterns
- Understanding event-driven architecture
- Building custom monitors
- Integration with existing systems
π websocket-filtered.ts - Optimize with filters
File: examples/websocket-filtered.ts
Lines: 177
Language: TypeScript
Learn how to drastically reduce bandwidth using server-side filters:
- Filter by contract addresses
- Filter by method signatures
- Dynamic filter updates
- Multiple filter strategies
Key Features:
- Server-side filtering (saves bandwidth)
- Shows multiple filter patterns
- Dynamic filter updates at runtime
- Method signature calculation tips
- Production optimization strategies
Perfect for:
- Protocol-specific monitoring
- Reducing costs/bandwidth
- Focused MEV strategies
- Smart contract analytics
Filter Examples Included:
// Example 1: Specific contracts + methods
client.setFilters({
addresses: [UNISWAP_V3],
methods: [SWAP_METHOD]
});
// Example 2: All methods on specific contracts
client.setFilters({
addresses: [CONTRACT_A, CONTRACT_B],
methods: []
});
// Example 3: Specific method across all contracts
client.setFilters({
addresses: [],
methods: [TRANSFER_METHOD]
});π http-polling.ts - REST API alternative
File: examples/http-polling.ts
Lines: 216
Language: TypeScript
Use HTTP polling instead of WebSocket for specific use cases:
- Serverless/Lambda compatible
- No persistent connections
- Simple integration
- Automatic retry on failures
Key Features:
- Two polling strategies (automatic & manual)
- Rate limit handling
- Deduplication logic
- Latency monitoring
- Serverless deployment tips
Perfect for:
- AWS Lambda / Google Cloud Functions
- Periodic batch processing
- Simple integrations
- Fallback/redundancy
When to Use:
- β Serverless environments
- β Polling intervals > 5 seconds
- β Simple cron-based workflows
- β Sub-second latency requirements
π advanced-usage.ts - Production patterns
File: examples/advanced-usage.ts
Lines: 194
Language: TypeScript
Advanced patterns for production deployments:
- WebSocket + HTTP fallback
- Transaction caching
- Multi-client architecture
- State management
- Production monitoring
Key Features:
- Automatic fallback to HTTP on disconnect
- Transaction deduplication cache
- Metrics aggregation
- Health checks
- Production error handling
Perfect for:
- Production deployments
- High-availability systems
- Enterprise applications
- Complex workflows
Architecture:
WebSocket (primary) β HTTP (fallback)
β
Transaction Cache (1 min TTL)
β
Processing Pipeline
All Examples Include:
-
Environment Variable Configuration
export ETHPENDING_API_KEY=your-key-here -
TypeScript Support
- Full type definitions
- Inline type hints
- Compilation not required (use
tsx)
-
Error Handling
- Network errors
- API errors
- Rate limits
- Validation errors
-
Production Patterns
- Graceful shutdown (SIGINT handling)
- Metrics monitoring
- Logging strategies
- Resource cleanup
-
Integration Examples
- Database storage patterns
- Webhook forwarding
- Message queue integration
- Monitoring service integration
All examples are designed to be easily customizable:
// Change filters
client.setFilters({
addresses: ['YOUR_CONTRACT'],
methods: ['YOUR_METHOD_SIG']
});
// Adjust polling interval
const POLL_INTERVAL = 10000; // 10 seconds
// Add custom processing
client.on('transaction', (tx) => {
// Your custom logic here
processTransaction(tx);
saveToDatabase(tx);
sendWebhook(tx);
});# Clone all examples
git clone https://github.com/ethpending/ethpending-library.git
cd ethpending-library/examples
# Install dependencies
npm install
# Run any example
export ETHPENDING_API_KEY=your-key
npx tsx websocket-basic.tsThe library works in both Node.js and browsers. For browsers, the native WebSocket API is used automatically:
<script type="module">
import { WebSocketClient } from 'https://unpkg.com/ethpending/dist/index.mjs';
const client = new WebSocketClient('your-api-key');
client.on('transaction', (tx) => {
console.log('Transaction:', tx.txHash);
});
await client.connect();
</script>interface PendingTransaction {
txHash: string; // Transaction hash
success: boolean; // Transaction success status
logs: TransactionLog[]; // Transaction event logs
timestamp: string; // ISO 8601 timestamp
network: string; // Network identifier
error?: string; // Error message if failed
from?: string; // Sender address
to?: string; // Recipient address
value?: string; // Transaction value in wei
gasPrice?: string; // Gas price in wei
gas?: string; // Gas limit
input?: string; // Transaction input data
nonce?: number; // Transaction nonce
}interface TransactionLog {
address: string; // Contract address
topics: string[]; // Indexed log arguments
data: string; // Non-indexed data
blockNumber: number | null; // Block number
transactionHash: string; // Transaction hash
transactionIndex: number | null;
blockHash: string | null;
logIndex: number | null;
removed: boolean; // Chain reorg flag
}interface FilterOptions {
addresses?: string[]; // Contract addresses to filter
methods?: string[]; // Method signatures to filter
}interface Metrics {
messagesReceived: number; // Messages received
messagesSent: number; // Messages sent
uptime: number; // Connection uptime (ms)
reconnectAttempts: number; // Reconnection attempts
errors: number; // Total errors
errorsByType: Record<string, number>;
connectionState: ConnectionState;
lastConnectedAt?: number; // Last connection timestamp
averageLatency?: number; // Avg latency (HTTP only)
}client.on('error', (error) => {
console.error('Error occurred:', error);
// Log to your error tracking service
});process.on('SIGINT', () => {
console.log('Shutting down...');
client.disconnect();
process.exit(0);
});setInterval(() => {
const metrics = client.getMetrics();
console.log('Connection health:', metrics);
}, 30000);Only subscribe to transactions you need to reduce bandwidth and processing:
client.setFilters({
addresses: ['0x...'], // Only specific contracts
methods: ['0xabcd...'], // Only specific methods
});Use HTTP polling as a fallback when WebSocket disconnects:
client.on('disconnected', () => {
console.log('WebSocket down, switching to HTTP polling');
const stopPolling = httpClient.startPolling(5000, handleTransactions);
client.once('connected', () => {
console.log('WebSocket reconnected, stopping HTTP polling');
stopPolling();
});
});- WebSocket: Real-time streaming with minimal latency (<100ms)
- HTTP: Polling with configurable intervals (recommended: 3-10 seconds)
- Memory: Efficient event handling with automatic cleanup
- CPU: Minimal overhead with native WebSocket implementation
The API has rate limits to ensure fair usage:
- WebSocket: 1 connection per API key
- HTTP: Varies by plan (check your dashboard)
Rate limit errors are automatically handled with retry logic.
Visit ethpending.com to sign up and get your API key instantly.
Currently supports Ethereum mainnet. More networks coming soon.
- WebSocket: Real-time streaming with sub-second latency. Best for continuous monitoring.
- HTTP: Polling-based with configurable intervals. Best for periodic checks or fallback.
Depends on your plan. Check ethpending.com/pricing for details.
Yes! The library includes automatic reconnection, error handling, and has been tested in production environments.
Yes! The library works in both Node.js and modern browsers.
Ethereum, pending transactions, mempool, MEV, front-running, arbitrage, DeFi, DEX, Uniswap, blockchain monitoring, real-time transactions, WebSocket, Ethereum API, transaction monitoring, whale watching, gas analysis, NFT tracking, blockchain analytics, Web3, Ethereum mempool API
- π Documentation
- π¬ Discord Community
- π§ Email Support
- π Report Issues
Contributions are welcome! Please read our Contributing Guide for details.
See also:
MIT License - see LICENSE file for details.
Made with β€οΈ by Skelpo GmbH