hypercast-sdk
v2.0.1
Published
HyperCast SDK - Complete blockchain event processing and management solution
Maintainers
Readme
HyperCast SDK v2.0.0 🚀
Production-ready blockchain event processing SDK with advanced features for real-time streaming, rule management, and comprehensive analytics.
✨ Features
🔄 Enhanced Event Stream Management
- Connection pooling for multiple subscriptions
- Automatic reconnection with exponential backoff
- Event buffering during disconnections
- Connection health monitoring and heartbeat
- Multiple filter support with complex predicates
- Circuit breaker pattern for resilience
⚙️ Advanced Rule Management
- Rule validation before creation
- Rule templates for common use cases
- Bulk operations (create/update/delete multiple rules)
- Rule import/export (JSON format)
- Rule testing with sample events
- Complex filtering with AND/OR logic
📊 Comprehensive ABI Management
- ABI validation and processing
- External ABI import (Etherscan, Sourcify)
- Contract mapping and versioning
- Multiple export formats (JSON, TypeScript, Solidity)
- Event extraction and caching
🔍 Event Processing & Analytics
- Real-time event processing with filtering
- Advanced search with full-text and structured queries
- Event aggregation by various criteria
- Comprehensive statistics and metrics
- Performance optimization with indexing
🛠️ Testing & Development Tools
- Mock event generators for testing
- Performance benchmarking tools
- Integration test helpers
- Comprehensive test reporting
- Development utilities
🎯 Production-Ready Features
- HTTP client resilience with retry mechanisms
- Rate limiting and circuit breaker patterns
- Request/response interceptors
- Comprehensive error handling
- Performance monitoring and statistics
🚀 Quick Start
Installation
npm install @hypercast/sdk
# or
yarn add @hypercast/sdkBasic Usage
import { HyperCastSDK } from "@hypercast/sdk";
// Initialize SDK
const sdk = new HyperCastSDK({
baseUrl: "https://your-hypercast-server.com",
apiKey: "your-api-key",
debug: true,
eventStream: {
maxBufferSize: 1000,
enableHeartbeat: true,
heartbeatInterval: 30000,
},
});
// Subscribe to events
const subscription = sdk.subscribe(
{ name: "Transfer", source: "evm" },
(event) => {
console.log("Transfer event:", event);
}
);
// Create a rule
const rule = await sdk.createRule({
name: "Large Transfer Alert",
description: "Alert when transfers exceed 1000 tokens",
source: "evm",
eventName: "Transfer",
args: [{ key: "value", op: "gt", value: "1000000000000000000000" }],
actions: [
{
type: "webhook",
enabled: true,
url: "https://your-webhook.com/alert",
method: "POST",
},
],
});📚 Advanced Usage
Complex Event Filtering
import { ComplexEventFilter } from "@hypercast/sdk";
const complexFilter: ComplexEventFilter = {
predicates: [
{ field: "source", operator: "eq", value: "evm" },
{ field: "name", operator: "eq", value: "Transfer" },
{ field: "blockNumber", operator: "gt", value: 1000000 },
],
logic: "AND",
groups: [
{
predicates: [
{ field: "address", operator: "eq", value: "0x..." },
{
field: "args.value",
operator: "gt",
value: "1000000000000000000000",
},
],
logic: "OR",
},
],
};
const subscription = sdk.subscribe(complexFilter, (event) => {
console.log("Complex filtered event:", event);
});ABI Management
// Import ABI from Etherscan
const abiResult = await sdk.importAbi("etherscan", "0x...");
// Register custom ABI
const abiResult = await sdk.addAbi([
{
type: "event",
name: "CustomEvent",
inputs: [
{ name: "user", type: "address", indexed: true },
{ name: "amount", type: "uint256" },
],
},
]);
// Get ABI manager for advanced operations
const abiManager = sdk.getAbiManager();
const contractAbi = abiManager.getContractAbi("0x...");Event Processing & Analytics
// Get event processor
const processor = sdk.getEventProcessor();
// Process events with filtering
const result = processor.processEvents(
{ source: "evm", name: "Transfer" },
{ limit: 100, sortBy: "timestamp", sortOrder: "desc" }
);
// Aggregate events
const aggregation = processor.aggregateEvents("name");
// Search events
const searchResult = processor.searchEvents({
text: "large transfer",
filters: { source: "evm" },
timeRange: {
start: new Date(Date.now() - 24 * 60 * 60 * 1000),
end: new Date(),
},
});
// Get statistics
const stats = processor.getStatistics();Rule Validation & Testing
// Validate rule before creation
const validation = sdk.validateRule(ruleSpec);
if (!validation.isValid) {
console.log("Validation errors:", validation.errors);
console.log("Warnings:", validation.warnings);
}
// Test rule with sample events
const testEvents = TestingTools.generateMockEvents(100);
const testResult = sdk.testRule(rule, testEvents);
console.log("Test passed:", testResult.passed);
console.log("Accuracy:", testResult.accuracy);
// Use rule templates
const templates = sdk.getRuleTemplates();
const largeTransferTemplate = templates.find(
(t) => t.name === "Large Transfer Alert"
);
const customRule = sdk.createRuleFromTemplate(largeTransferTemplate, {
address: "0x...",
actions: [{ type: "telegram", botToken: "...", chatId: "..." }],
});Testing & Development
import { TestingTools } from "@hypercast/sdk";
// Generate test data
const testData = TestingTools.generateTestData(1000, 50);
// Create mock event stream
const mockStream = TestingTools.createMockEventStream(testData.events, 100);
mockStream.onEvent((event) => {
console.log("Mock event:", event);
});
mockStream.start();
// Run performance benchmarks
const benchmarks = await TestingTools.runPerformanceBenchmarks();
console.log("Performance results:", benchmarks);
// Generate test report
const report = TestingTools.generateTestReport(
testData,
testResults,
benchmarks
);
console.log(report);Utilities & Helpers
import { SDKUtils } from "@hypercast/sdk";
// Format events
const formatted = SDKUtils.formatEvents(events, {
format: "table",
timestampFormat: "relative",
includeArgs: true,
});
// Validate addresses
const addressValidation = SDKUtils.validateAddress("0x...", {
checksum: true,
normalize: true,
});
// Validate filters
const filterValidation = SDKUtils.validateEventFilter(complexFilter);
// Time utilities
const timeUtils = SDKUtils.getTimeUtils();
const now = timeUtils.now();
const isToday = timeUtils.isToday(timestamp);
// Utility functions
const debouncedFn = SDKUtils.debounce(myFunction, 1000);
const throttledFn = SDKUtils.throttle(myFunction, 100);
const clonedObj = SDKUtils.deepClone(originalObj);🔧 Configuration
SDK Configuration
const sdk = new HyperCastSDK({
baseUrl: "https://your-hypercast-server.com",
apiKey: "your-api-key",
timeout: 30000,
debug: true,
headers: {
"User-Agent": "MyApp/1.0.0",
},
eventStream: {
maxBufferSize: 1000,
healthCheckInterval: 30000,
connectionTimeout: 10000,
maxReconnectAttempts: 5,
baseReconnectDelay: 1000,
maxReconnectDelay: 30000,
enableHeartbeat: true,
heartbeatInterval: 30000,
debug: false,
},
});Event Stream Configuration
const eventStreamConfig = {
maxBufferSize: 1000, // Max events to buffer
healthCheckInterval: 30000, // Health check interval (ms)
connectionTimeout: 10000, // Connection timeout (ms)
maxReconnectAttempts: 5, // Max reconnection attempts
baseReconnectDelay: 1000, // Base reconnection delay (ms)
maxReconnectDelay: 30000, // Max reconnection delay (ms)
enableHeartbeat: true, // Enable heartbeat monitoring
heartbeatInterval: 30000, // Heartbeat interval (ms)
debug: false, // Enable debug logging
};📊 Monitoring & Statistics
Connection Health
// Get connection statistics
const stats = sdk.getConnectionStats();
console.log("Active connections:", stats.activeConnections);
console.log("Circuit breaker status:", stats.circuitBreakerStatus);
// Get connection health
const health = sdk.getConnectionHealth();
for (const [filterKey, status] of health) {
console.log(`${filterKey}: ${status.status}`);
}
// Get SDK health status
const sdkHealth = sdk.getHealthStatus();
console.log("SDK status:", sdkHealth.sdk);Comprehensive Statistics
// Get comprehensive SDK statistics
const comprehensiveStats = sdk.getComprehensiveStats();
console.log("SDK Health:", comprehensiveStats.sdk);
console.log("Connection Stats:", comprehensiveStats.connections);
console.log("Event Processor Stats:", comprehensiveStats.events);
console.log("ABI Manager Stats:", comprehensiveStats.abi);
console.log("HTTP Client Stats:", comprehensiveStats.http);🧪 Testing
Running Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Run linting
npm run lint
# Fix linting issues
npm run lint:fixTest Configuration
The SDK includes comprehensive testing tools:
- Mock Event Generators: Generate realistic test events
- Performance Benchmarks: Measure SDK performance
- Integration Test Helpers: Test against real servers
- Test Data Generation: Create test scenarios
- Result Validation: Validate test outcomes
📦 Building
Development Build
npm run devProduction Build
npm run buildClean Build
npm run clean
npm run build�� API Reference
Core Classes
HyperCastSDK: Main SDK classEventStreamClient: Enhanced event streamingRuleValidator: Rule validation and testingAbiManager: ABI management and importEventProcessor: Event processing and analyticsTestingTools: Testing and development utilitiesSDKUtils: Utility functions and helpers
Key Methods
- Event Subscription:
subscribe(),subscribeToAll(),subscribeToContract() - Rule Management:
createRule(),updateRule(),deleteRule(),toggleRule() - ABI Management:
addAbi(),importAbi(),getContractAbi() - Event Processing:
processEvents(),aggregateEvents(),searchEvents() - Validation:
validateRule(),testRule(),validateEventFilter() - Monitoring:
getConnectionStats(),getHealthStatus(),getComprehensiveStats()
🌟 Examples
Check out the examples/ directory for comprehensive usage examples:
- Basic Usage: Simple event subscription and rule creation
- Advanced Filtering: Complex event filtering with predicates
- ABI Management: ABI import and management workflows
- Event Processing: Analytics and processing examples
- Testing: Testing and benchmarking examples
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
git clone https://github.com/hypercast/sdk.git
cd sdk
npm install
npm run dev📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
- Documentation: https://docs.hypercast.com
- Issues: GitHub Issues
- Discord: Join our community
- Email: [email protected]
🔄 Changelog
v2.0.0 - Major Release
- ✨ Enhanced event stream management with connection pooling
- ⚙️ Advanced rule management with validation and testing
- 📊 Comprehensive ABI management with external import
- 🔍 Event processing and analytics engine
- 🛠️ Testing and development tools
- 🎯 Production-ready features with resilience patterns
- 📚 Comprehensive documentation and examples
v1.0.0 - Initial Release
- Basic event subscription
- Simple rule management
- Basic ABI registration
Built with ❤️ by the HyperCast Team
