A sophisticated Node.js backend service for automated Arbitrum Stylus contract caching with ROI-based bidding logic, real-time blockchain monitoring, and intelligent contract discovery.
SmartCache Enhanced Backend automatically discovers new Stylus contracts on Arbitrum, detects SmartCache opt-ins, and places profitable bids for contract caching based on real-time ROI analysis. The system features comprehensive logging, error handling, and performance monitoring.
- WebSocket Event Monitoring: Live monitoring of
ProgramActivatedevents for new Stylus deployments - Automatic Opt-in Detection: Real-time detection via
isCacheable()function calls andAutoCacheOptInevents - Contract Classification: Automatic categorization (discovered, checked, opted-in, cached)
- Automatic Caching: When
isCacheable()returns true, automatically attempts to place profitable bids - Manual Contract Checking: API endpoint for manual opt-in verification and caching
- Dynamic market analysis using latest bid value data
- Configurable ROI thresholds (default: 10%)
- Intelligent bid placement with gas estimation and balance validation
- Comprehensive bid success/failure tracking
- Winston-based structured logging with multiple transport layers
- Request/response logging with unique request IDs
- Blockchain-specific event logging (contract deployment, bid placement, opt-ins)
- Database operation tracking and error monitoring
- Real-time Event Streaming: Live monitoring of blockchain events via WebSocket providers
- Environment Configuration: Uses
WS_ARBITRUM_SEPOLIA_URLenvironment variable for flexible network setup - Provider Management: Centralized WebSocket provider handling with automatic reconnection
- Event Topic Monitoring: Dedicated listeners for
ProgramActivatedandAutoCacheOptInevents - Graceful Shutdown: Proper WebSocket cleanup on application termination
- Contract Deployment: WebSocket detects
ProgramActivatedevent - Opt-in Check: Calls
isCacheable()on the new contract - ROI Analysis: If cacheable, analyzes profitability using current market data
- Bid Placement: If profitable (ROI > threshold), automatically places bid
- Result Tracking: Logs success/failure and updates contract categories
- Continuous Monitoring: Process repeats for all new contract deployments
- Custom error classes for different error types (Blockchain, Database, Validation)
- Comprehensive error middleware with consistent API responses
- Global error handlers for uncaught exceptions and unhandled rejections
- Development-friendly error responses with stack traces
- MongoDB integration for contract and bid data storage
- Automated contract metadata storage with eviction thresholds
- Performance-optimized caching with background updates
- Database health monitoring and connection management
- Arbitrum Sepolia (primary)
- Arbitrum One and Nova support
- Alchemy integration for deployer verification
- Network-specific configuration management
The backend now supports fully dynamic network selection for both Arbitrum Sepolia (testnet) and Arbitrum One (mainnet).
- Default Network: The default network is set via the
NETWORKenvironment variable. Supported values:arbitrum-sepolia,arbitrum-one. - Override Per Request: Most API endpoints (such as
/place-bid) accept anetworkparameter in the request body to override the default for that operation.
- Multiple Networks: You can monitor multiple networks simultaneously for WebSocket events using the
NETWORKSenvironment variable. - Configuration: Set
NETWORKS=arbitrum-sepolia,arbitrum-oneto monitor both testnet and mainnet. - Event Processing: Events from both networks are processed independently and tracked separately.
- Separate Documents: The
bid_valuescollection now stores separate documents for each network:{ type: "latest_bid_value", network: "arbitrum-sepolia", ... }{ type: "latest_bid_value", network: "arbitrum-one", ... }
- Background Updates: The background updater monitors both networks simultaneously and updates their respective cache documents.
- Network-Specific Contracts: Each network uses its own CacheManager contract:
- Arbitrum Sepolia:
0x0C9043D042aB52cFa8d0207459260040Cca54253 - Arbitrum One:
0x51dEDBD2f190E0696AFbEE5E60bFdE96d86464ec- Block Range Optimization: - Arbitrum Sepolia: Uses 5000-block ranges for efficient event querying - Arbitrum One: Uses 400-block ranges with pagination (up to 20 chunks = 8000 blocks) to respect Alchemy's 500-block limit foreth_getLogsand ensure older bids are found
- Arbitrum Sepolia:
# Single Network Mode
NETWORK=arbitrum-sepolia
# Multi-Network Mode (for WebSocket monitoring and bid value caching)
NETWORKS=arbitrum-sepolia,arbitrum-one
# Required API Keys
ARBISCAN_KEY=your_arbiscan_api_key
ALCHEMY_API_KEY=your_alchemy_api_key
# Database
MONGODB_URI=your_mongodb_connection_string
DATABASE_NAME=smartcache
# WebSocket URLs (optional - defaults provided)
WS_ARBITRUM_SEPOLIA_URL=wss://sepolia-rollup.arbitrum.io/wsSingle Network (Testnet):
NETWORK=arbitrum-sepoliaSingle Network (Mainnet):
NETWORK=arbitrum-oneMulti-Network (Both):
NETWORKS=arbitrum-sepolia,arbitrum-oneMulti-Network (Mainnet Only):
NETWORKS=arbitrum-onearbitrum-sepolia(testnet)arbitrum-one(mainnet)
# Monitor only Arbitrum Sepolia
NETWORK=arbitrum-sepolia
# Monitor only Arbitrum One
NETWORK=arbitrum-one# Monitor both testnet and mainnet simultaneously
NETWORKS=arbitrum-sepolia,arbitrum-one
# Monitor only mainnet
NETWORKS=arbitrum-one
# Monitor only testnet
NETWORKS=arbitrum-sepolia{
"contractAddress": "0x...",
"network": "arbitrum-one" // or omit for default
}- Parallel Monitoring: All specified networks are monitored simultaneously
- Network-Specific Events: Each network's events are tracked separately
- Independent Contract Processing: Contracts discovered on each network are processed independently
- Fault Tolerance: If one network fails to connect, others continue monitoring
- Network-Aware Logging: All logs include the source network information
src/
βββ server.js # Application entry point
βββ app.js # Main application logic & event listeners
βββ services/ # Business logic layer
β βββ bidding-logic.js # ROI-based bidding service
β βββ bid-value.js # Blockchain data fetching & caching
β βββ place-bid.js # Bid placement functionality
βββ routes/ # API endpoints
β βββ contracts.js # Contract management APIs
β βββ performance.js # Performance monitoring APIs
β βββ status.js # System status & analytics
βββ database/ # Database layer
β βββ connection.js # MongoDB connection management
βββ blockchain/ # Blockchain integration
β βββ providers.js # WebSocket providers & utilities
βββ middleware/ # Express middleware
β βββ errorHandler.js # Global error handling
β βββ requestLogger.js # Request/response logging
βββ utils/
βββ logger.js # Winston logging configuration
- Node.js 18+
- MongoDB database
- Arbitrum Sepolia RPC access
- Arbiscan API key
- Private key for bid transactions (optional for read-only mode)
# Clone repository
git clone <repository-url>
cd smart-cache-script
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Edit .env with your configurationCreate a .env file with the following variables:
# Blockchain Configuration
WS_ARBITRUM_SEPOLIA_URL=wss://sepolia-rollup.arbitrum.io/ws
ARBISCAN_KEY=your_arbiscan_api_key
PRIVATE_KEY=your_private_key_for_bidding
ALCHEMY_API_KEY=your_alchemy_api_key
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/smartcache
DATABASE_NAME=smartcache
COLLECTION_NAME=contracts
# Application Configuration
NODE_ENV=development
LOG_LEVEL=info
PORT=4000
NETWORK=arbitrum-sepolia # or arbitrum-one# Development mode (JavaScript)
npm run dev
# Development mode (TypeScript)
npm run dev:ts
# Production build
npm run build
npm run start:prod
# Standard start
npm start
# Testing WebSocket functionality
npm run test:websocket
# Testing bid cache system
npm run test:bid-cacheTest the real-time WebSocket monitoring functionality:
# Start the server (in a separate terminal)
npm run dev:ts
# Run WebSocket tests (in another terminal)
npm run test:websocketThis test will verify:
- WebSocket connection status
- Event listener activation
- Contract tracking functionality
- Real-time status endpoints
- Manual contract checking
- Automatic contract caching (checkAndCache functionality)
POST /contracts/store
Content-Type: application/json
{
"contractAddress": "0x...",
"deployedBy": "0x...",
"network": "arbitrum-sepolia"
}GET /contracts/list?network=arbitrum-sepoliaGET /contracts/cache-status/0x...POST /contracts/place-bid
Content-Type: application/json
{
"contractAddress": "0x...",
"network": "arbitrum-one" // or omit for default
}GET /api/tracked-contractsReturns all contract categories with real-time status:
{
"allContracts": ["0x123...", "0x456..."],
"optedInContracts": ["0x123..."],
"checkedContracts": ["0x123...", "0x456..."],
"successfullyCachedContracts": ["0x123..."],
"counts": {
"total": 2,
"optedIn": 1,
"checked": 2,
"cached": 1
},
"realtimeStatus": {
"websocketConnected": true,
"eventListenersActive": true,
"providerConnected": true
}
}GET /api/realtime-statusDetailed WebSocket and event monitoring status:
{
"websocket": {
"connected": true,
"provider": "initialized"
},
"eventListeners": {
"active": true,
"programActivatedTopic": "0x...",
"autoCacheOptInTopic": "0x..."
},
"contracts": {
"arbWasm": "connected",
"cacheManager": "connected",
"smartCacheDetection": "connected"
},
"discovery": {
"totalDiscovered": 5,
"totalChecked": 4,
"totalOptedIn": 2,
"checkRate": 50
}
}POST /api/check-contract-optin
Content-Type: application/json
{
"contractAddress": "0x..."
}Manually trigger opt-in verification for a specific contract:
{
"success": true,
"contractAddress": "0x...",
"message": "Contract opt-in check completed",
"isOptedIn": true,
"wasChecked": true
}POST /api/cache-contract
Content-Type: application/json
{
"contractAddress": "0x..."
}Manually trigger caching (bid placement) for a specific contract:
{
"success": true,
"contractAddress": "0x...",
"message": "Contract caching attempt completed",
"wasCached": true,
"isOptedIn": true,
"totalCached": 3
}GET /performance/bid-cacheGET /performance/database-healthPOST /performance/initialize-bid-cacheGET /statusPOST /status/analyze/0x...const biddingLogic = new BiddingLogic({
roiThreshold: 0.1, // 10% ROI threshold
defaultMarketBid: "0.005", // Default market bid in ETH
logger: logger, // Winston logger instance
});The application uses Winston for structured logging with multiple levels:
error: Error conditionswarn: Warning conditionsinfo: Informational messagesdebug: Debug-level messages
Logs are stored in:
logs/error.log- Error messages onlylogs/combined.log- All log levelslogs/exceptions.log- Uncaught exceptionslogs/rejections.log- Unhandled promise rejections
{
contractAddress: String,
deployedBy: String,
network: String,
minBidRequired: String,
gasSaved: String,
deployedAt: Date,
evictionThresholdDate: Date,
usingAutoCacheFlag: Boolean,
txHash: String,
roiAnalysis: Object
}# Run bid cache tests
node tests/bid-cache.test.js# Test specific contract
curl -X POST http://localhost:4000/status/analyze/0x...# View real-time logs
tail -f logs/combined.log
# Filter by module
grep "Blockchain" logs/combined.log
# View errors only
tail -f logs/error.log- Database:
GET /performance/database-health - WebSocket: Monitor connection status in logs
- Bidding:
GET /performance/bid-cache
- Create route file in
src/routes/ - Import and register in
src/app.js - Use error handling middleware with
asyncHandler
- Create service file in
src/services/ - Use structured logging with
createLogger - Implement proper error handling
const { BlockchainError } = require("./middleware/errorHandler");
throw new BlockchainError("Transaction failed", "bid_placement");- MongoDB-based bid value caching (5-minute TTL)
- Background cache updates every 5 minutes
- Reverse chronological event processing for latest data
- WebSocket reconnection with exponential backoff
- MongoDB connection pooling
- Request ID tracking for debugging
- Private keys stored in environment variables
- Database connection strings sanitized in logs
- Request/response size limiting
- Input validation on all endpoints
- WebSocket Connection Fails: Check WS_ARBITRUM_SEPOLIA_URL and network connectivity
- Database Connection Issues: Verify MONGODB_URI and database accessibility
- Bid Placement Fails: Check private key and account balance
- Fork the repository
- Create feature branch
- Add tests for new functionality
- Submit pull request with detailed description
[Your License Here]
Built with β€οΈ for the Arbitrum Stylus ecosystem