npm package: @mraicodedev/bsc-token-detector
Description: 🚀 Real-time BSC token detector with advanced filtering, health monitoring, and comprehensive event system. Detect new tokens on Binance Smart Chain as they are created!
Author: mraicodedev
Latest version: 1.0.0

# 🚀 BSC Token Detector

[![npm version](https://badge.fury.io/js/bsc-token-detector.svg)](https://badge.fury.io/js/bsc-token-detector)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen)](https://nodejs.org/)
[![Downloads](https://img.shields.io/npm/dm/bsc-token-detector.svg)](https://www.npmjs.com/package/bsc-token-detector)

**Real-time BSC token detector with advanced filtering, health monitoring, and comprehensive event system.**

Detect new tokens on Binance Smart Chain as they are created! Perfect for DeFi applications, trading bots, and blockchain analytics.

## ✨ Features

- 🔍 **Real-time Detection** - Detect tokens from both blocks and mempool
- 🎯 **Advanced Filtering** - Configurable filters for supply, creator, name patterns
- 🏥 **Health Monitoring** - Built-in health checks and circuit breaker patterns
- 🔄 **Auto Recovery** - Automatic error recovery and RPC failover
- 📊 **Rich Events** - Comprehensive event system with detailed callbacks
- ⚙️ **Runtime Config** - Update configuration without restarting
- 🛡️ **Production Ready** - Battle-tested with proper error handling
- 📚 **Full Documentation** - Complete API docs and examples

## 🚀 Quick Start

### Installation

```bash
npm install bsc-token-detector
```

### Basic Usage

```javascript
import { BSCTokenDetector } from 'bsc-token-detector';

// Create detector
const detector = new BSCTokenDetector({
  rpcProviders: [{
    url: 'https://bsc-dataseed.binance.org/',
    weight: 1,
    timeout: 5000
  }]
});

// Register callback for new tokens
detector.onTokenDetected((token) => {
  console.log('🎉 New token detected!');
  console.log(`Name: ${token.name}`);
  console.log(`Symbol: ${token.symbol}`);
  console.log(`Contract: ${token.contractAddress}`);
  console.log(`Creator: ${token.creator}`);
  console.log(`Supply: ${token.totalSupply}`);
});

// Start detection
await detector.start();
```

### Continuous Detection

```bash
# Run continuous detection
npm start

# Or use the detector programmatically
node examples/continuous-detection.js
```

## 📖 Documentation

### Configuration

```javascript
const detector = new BSCTokenDetector({
  // RPC Providers (required)
  rpcProviders: [
    {
      url: 'https://bsc-dataseed.binance.org/',
      weight: 2,
      timeout: 5000,
      maxRetries: 3,
      priority: 100
    },
    {
      url: 'https://bsc-dataseed1.defibit.io/',
      weight: 1,
      timeout: 3000,
      priority: 80
    }
  ],
  
  // Token Filters (optional)
  filters: {
    minTotalSupply: '1000000000000000000000', // 1000 tokens minimum
    maxTotalSupply: '1000000000000000000000000000', // 1B tokens maximum
    creatorBlacklist: ['0x0000000000000000000000000000000000000000'],
    symbolPattern: '^[A-Z]{2,10}$', // 2-10 uppercase letters
    namePattern: '^[A-Za-z0-9\\s]{2,50}$' // 2-50 alphanumeric chars
  },
  
  // Monitoring Settings (optional)
  monitoring: {
    pollInterval: 1000, // Block polling interval (ms)
    enableMempool: true, // Monitor mempool for early detection
    mempoolPollInterval: 500, // Mempool polling interval (ms)
    enableHealthCheck: true,
    healthCheckInterval: 30000
  },
  
  // Performance Settings (optional)
  performance: {
    maxConcurrentRequests: 10,
    cacheSize: 1000,
    blockConfirmations: 1,
    requestTimeout: 5000
  }
});
```

### Event Handling

```javascript
// Method chaining for multiple callbacks
detector
  .onTokenDetected((token) => {
    console.log('New token:', token.symbol);
  })
  .onPendingToken((pending) => {
    console.log('Pending token:', pending.contractAddress);
  })
  .onError((error) => {
    console.error('Error:', error.message);
  })
  .onStatusChanged((status) => {
    console.log('Status:', status.isRunning ? 'Running' : 'Stopped');
  });

// Or register multiple callbacks at once
detector.registerCallbacks({
  tokenDetected: (token) => console.log('Token:', token.symbol),
  pendingToken: (pending) => console.log('Pending:', pending.contractAddress),
  error: (error) => console.error('Error:', error.message),
  healthAlert: (alert) => console.warn('Health Alert:', alert.message)
});
```

### Available Events

- `tokenDetected` - New confirmed token detected
- `pendingToken` - Potential token detected in mempool
- `error` - Error occurred
- `statusChanged` - Detector status changed
- `configurationChanged` - Configuration updated
- `healthStatusChanged` - System health status changed
- `healthAlert` - Health alert triggered
- `circuitBreakerActivated` - Circuit breaker activated
- `providerRecovered` - RPC provider recovered

### API Methods

```javascript
// Lifecycle
await detector.start();
await detector.stop();
await detector.destroy();

// Configuration
detector.configure({ filters: { minTotalSupply: '2000000000000000000000' } });
const config = detector.getConfig();
detector.resetConfig();

// Status & Results
const status = detector.getStatus();
const tokens = detector.getDetectedTokens();
const pending = detector.getPendingTokens();
const health = await detector.healthCheck();

// API Documentation
const docs = BSCTokenDetector.getAPIDocumentation();
const markdown = BSCTokenDetector.generateAPIDocumentation();
```

## 📋 Examples

### Simple Detection (30 seconds)
```bash
npm run example:simple
```

### Filtered Detection (2 minutes)
```bash
npm run example:filtered
```

### Comprehensive Demo (45 seconds)
```bash
npm run example:comprehensive
```

### Continuous Detection (until stopped)
```bash
npm start
# or
npm run detect
```

## 🔧 Advanced Usage

### With Filters

```javascript
const detector = new BSCTokenDetector({
  rpcProviders: [{ /* ... */ }],
  filters: {
    minTotalSupply: '1000000000000000000000', // 1K tokens minimum
    maxTotalSupply: '1000000000000000000000000000', // 1B tokens maximum
    creatorBlacklist: [
      '0x0000000000000000000000000000000000000000', // Null address
      '0x000000000000000000000000000000000000dead'  // Burn address
    ],
    symbolPattern: '^[A-Z]{2,10}$', // 2-10 uppercase letters only
    namePattern: '^[A-Za-z0-9\\s]{2,50}$' // Reasonable name pattern
  }
});
```

### Multiple RPC Providers

```javascript
const detector = new BSCTokenDetector({
  rpcProviders: [
    {
      url: 'https://bsc-dataseed.binance.org/',
      weight: 2, // Higher weight = more requests
      timeout: 5000,
      maxRetries: 3,
      priority: 100 // Higher priority = preferred
    },
    {
      url: 'https://bsc-dataseed1.defibit.io/',
      weight: 1,
      timeout: 3000,
      maxRetries: 2,
      priority: 80
    },
    {
      url: 'https://bsc-dataseed1.ninicoin.io/',
      weight: 1,
      timeout: 4000,
      maxRetries: 2,
      priority: 60
    }
  ]
});
```

### Production Deployment

```javascript
// Using PM2 for production
const pm2Config = {
  name: 'bsc-token-detector',
  script: 'examples/continuous-detection.js',
  instances: 1,
  autorestart: true,
  watch: false,
  max_memory_restart: '1G',
  env: {
    NODE_ENV: 'production'
  }
};

// pm2 start ecosystem.config.js
```

## 🛠️ Development

### Setup

```bash
git clone https://github.com/bsc-token-detector/bsc-token-detector.git
cd bsc-token-detector
npm install
```

### Scripts

```bash
npm run dev          # Development mode with watch
npm run build        # Build for production
npm run test         # Run tests
npm run test:watch   # Run tests in watch mode
npm run lint         # Lint code
npm run lint:fix     # Fix linting issues
```

### Testing

```bash
# Run all tests
npm test

# Run specific test
npm test -- --testNamePattern="BSCTokenDetector"

# Run tests with coverage
npm test -- --coverage
```

## 📊 Performance

- **Memory Usage**: ~50-100MB typical
- **CPU Usage**: Low (~1-5% on modern systems)
- **Network**: Optimized RPC calls with connection pooling
- **Latency**: Token detection within 1-3 seconds of creation
- **Throughput**: Handles 1000+ tokens/hour efficiently

## 🔒 Security

- No private keys or sensitive data required
- Read-only RPC operations
- Input validation and sanitization
- Circuit breaker patterns for resilience
- Configurable rate limiting

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Workflow

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📖 [Documentation](https://github.com/bsc-token-detector/bsc-token-detector/wiki)
- 🐛 [Issue Tracker](https://github.com/bsc-token-detector/bsc-token-detector/issues)
- 💬 [Discussions](https://github.com/bsc-token-detector/bsc-token-detector/discussions)
- 📧 [Email Support](mailto:support@bsc-token-detector.com)

## 🙏 Acknowledgments

- Binance Smart Chain team for the robust infrastructure
- The Web3 community for inspiration and feedback
- All contributors who helped make this project better

## 📈 Roadmap

- [ ] WebSocket support for real-time updates
- [ ] Token metadata enrichment
- [ ] Advanced analytics and metrics
- [ ] Multi-chain support (Ethereum, Polygon, etc.)
- [ ] GraphQL API
- [ ] Web dashboard
- [ ] Docker containerization
- [ ] Kubernetes deployment guides

---

**Made with ❤️ by the BSC Token Detector Team**

*Star ⭐ this repo if you find it useful!*