OmniTipper Documentation

OmniTipper - Architectural Overview

Table of Contents

  1. System Overview
  2. Architecture Components
  3. Data Flow
  4. Database Schema
  5. Security Architecture
  6. External Integrations
  7. Deployment Architecture
  8. Key Design Decisions
  9. Technology Stack

System Overview

OmniTipper is a Discord-based cryptocurrency tipping bot that operates on the Base blockchain. The system enables users to tip, deposit, and withdraw various ERC20 tokens and native ETH through Discord commands, with off-chain transfers for tips and on-chain operations for deposits and withdrawals.

System Diagram

!System Architecture Diagram

Core Principles


Architecture Components

1. Bot Layer (src/bot.ts)

The main entry point that orchestrates all components: Key Responsibilities:

2. Command Handlers (src/commands/)

Modular command processors for user interactions:

User Commands

Admin Commands (admin.ts)

3. Service Layer (src/services/)

Core business logic services:

Web3Service (web3.ts)

Handles all blockchain interactions:

PriceService (price.ts)

Handles cryptocurrency price conversions:

MetricsService (metrics.ts)

Prometheus-compatible metrics collection:

MetricsServer (metrics-server.ts)

HTTP server exposing Prometheus metrics:

4. Database Layer (src/database/)

MongoDB-based data persistence:

Connection (connection.ts)

Models (models.ts)

Database schema and operations: Collections: Key Features:

5. Utility Layer (src/utils/)

Supporting utilities:

Encryption (encryption.ts)

Logger (logger.ts)

Environment (env.ts)


Data Flow

1. Tip Flow (Off-chain)

!Tip Flow Diagram No blockchain interaction - pure database operation

2. Deposit Flow (On-chain)

!Deposit Flow Diagram

3. Withdrawal Flow (On-chain)

!Withdrawal Flow Diagram

4. ERC20 Transfer from Deposit Address Flow

!ERC20 Transfer Flow Diagram

5. Price Conversion Flow

!Price Conversion Flow Diagram

Database Schema

!Database Schema Diagram

Users Collection

{
  _id: string;                    // Discord user ID
  username: string;                // Discord username
  balances: Record<string, string>; // coin symbol -> balance (string for precision)
  depositAddress: string | null;   // Single address for all tokens
  depositPrivateKey: string | null; // Encrypted private key
  createdAt: Date;
  updatedAt: Date;
}
Indexes:

Coins Collection

{
  _id: string;                     // Token symbol (e.g., "USDC", "ETH")
  contractAddress: string | null;  // ERC20 contract address (null for native ETH)
  decimals: number;                 // Token decimals
  name: string;                    // Token name
  enabled: boolean;                 // Whether token is enabled
  isNative: boolean;                // true for native ETH
  createdAt: Date;
}
Indexes:

BotBalances Collection

{
  coin: string;                    // Token symbol
  balance: string;                  // On-chain balance (string for precision)
  updatedAt: Date;
}
Indexes:

DepositTracking Collection

{
  _id: string;                     // "userId:coinSymbol"
  userId: string;                  // Discord user ID
  coin: string;                    // Token symbol
  lastCheckedBalance: string;      // Last checked balance
  botFundedAmount: string;         // ETH funded by bot (not user deposit)
  updatedAt: Date;
}
Indexes:

GasFeeTracking Collection

{
  _id: string;                     // Transaction hash or 'total'
  type: 'funding' 
'withdrawal'
'transfer'; amount: string; // Gas fee in ETH (string for precision) transactionHash?: string; // Transaction hash depositAddress?: string; // For funding operations userId?: string; // For withdrawal operations createdAt: Date; }
Indexes:

Security Architecture

1. Private Key Encryption

2. Access Control

3. Input Validation

4. Rate Limiting

5. Balance Precision

6. Transaction Safety


External Integrations

1. Discord API

2. Base Blockchain

3. CoinMarketCap API

4. MongoDB


Deployment Architecture

Container Architecture

!Container Architecture Diagram

Docker Compose Setup

┌─────────────────────────────────────┐
│         Docker Network              │
│                                     │
│  ┌──────────────┐  ┌─────────────┐ │
│  │   Bot        │  │  MongoDB    │ │
│  │  Container   │◄─┤  Container  │ │
│  │              │  │             │ │
│  │  - Bun       │  │  - MongoDB 7│ │
│  │  - Node.js   │  │  - Volume   │ │
│  │  - Source    │  │    Mounted  │ │
│  └──────┬───────┘  └─────────────┘ │
│         │                          │
└─────────┼──────────────────────────┘
          │
          ▼
    ┌──────────┐
    │ Discord  │
    │   API    │
    └──────────┘
          │
          ▼
    ┌──────────┐
    │  Base    │
    │  RPC     │
    └──────────┘
          │
          ▼
    ┌──────────┐
    │CoinMarket│
    │   Cap    │
    └──────────┘

Container Configuration

Bot Container: MongoDB Container:

Environment Variables

Required: Optional:

Key Design Decisions

1. Off-chain Tips

Decision: Tips are database-only operations (no blockchain transactions) Rationale: Trade-offs:

2. Single Deposit Address per User

Decision: One deposit address per user for all tokens Rationale: Trade-offs:

3. Automatic ETH Funding

Decision: Bot automatically funds deposit addresses with ETH for gas Rationale: Trade-offs:

4. ETH Sweeping

Decision: Automatically sweep excess ETH from deposit addresses Rationale: Trade-offs:

5. Batch Balance Checking

Decision: Use JSON-RPC batch requests for balance checks Rationale: Trade-offs:

6. String-based Balance Storage

Decision: Store all balances as strings in database Rationale: Trade-offs:

7. Gas Fee Tracking

Decision: Track all gas fees separately for accounting Rationale: Trade-offs:

8. Recursive Deposit Checking

Decision: Use recursive setTimeout instead of setInterval Rationale: Trade-offs:

Technology Stack

Runtime & Language

Core Dependencies

Infrastructure

External Services

Development Tools


Performance Considerations

1. RPC Optimization

2. Database Optimization

3. API Optimization

4. Memory Management


Monitoring & Observability

Logging

Metrics (Prometheus)

The bot exposes Prometheus-compatible metrics on an HTTP endpoint for integration with Grafana or other monitoring systems.

Metrics Endpoint

Available Metrics

Counters: Gauges: Summaries:

Grafana Integration

  1. Configure Prometheus to scrape the metrics endpoint:
scrape_configs:
  • job_name: 'omnitipper'
static_configs:
  • targets: ['bot-container:9090']
  1. Import Grafana Dashboard or create custom dashboards using the available metrics
  1. Set up Alerts for:

Key Metrics to Monitor

Health Checks


Future Enhancements

Potential Improvements

  1. Multi-chain support: Extend to other EVM chains
  2. Transaction history: Track all user transactions
  3. Analytics dashboard: Admin interface for metrics
  4. Webhook notifications: Alternative to DMs
  5. Rate limiting: Per-user command rate limits
  6. Multi-signature wallet: Enhanced security
  7. Automated testing: Comprehensive test suite
  8. API endpoint: REST API for external integrations

Conclusion

OmniTipper is designed as a scalable, secure, and efficient cryptocurrency tipping bot. The architecture prioritizes: The system is production-ready and can handle high-volume operations while maintaining accuracy and security.