Skip to content

Analyze API wrapper functionality#5

Merged
mayankjanmejay merged 1 commit into
mainfrom
claude/analyze-api-wrapper-011CV4vowFC73byanSEoLMnG
Nov 13, 2025
Merged

Analyze API wrapper functionality#5
mayankjanmejay merged 1 commit into
mainfrom
claude/analyze-api-wrapper-011CV4vowFC73byanSEoLMnG

Conversation

@mayankjanmejay
Copy link
Copy Markdown
Owner

@mayankjanmejay mayankjanmejay commented Nov 13, 2025

This commit implements 5 major improvements to make the babel_binance wrapper production-ready and enterprise-grade:

🎯 1. Custom Exception Classes

  • Added hierarchical exception system with specific error types
  • BinanceApiException, BinanceRateLimitException, BinanceAuthException
  • BinanceNetworkException, BinanceTimeoutException, BinanceParameterException
  • Smart error detection (isRetryable, isAuthError, isRateLimitError)
  • Better error handling with specific catch blocks

⚡ 2. Rate Limiting System

  • Implemented token bucket algorithm for rate limiting
  • Tracks REQUEST_WEIGHT, ORDERS, and RAW_REQUESTS limits
  • Automatic throttling to prevent API bans
  • Syncs with server-reported usage from response headers
  • Configurable: throw vs wait, safety margins
  • Prevents hitting Binance limits (1200 weight/min, 10 orders/sec)

⏱️ 3. Timeout Configuration

  • Added BinanceConfig for comprehensive configuration
  • Configurable request and connection timeouts
  • Server time synchronization for accurate signatures
  • Custom headers, user-agent, proxy support
  • Preset configs: default, slow network, high-frequency
  • Per-request timeout overrides

🔌 4. WebSocket Improvements

  • Complete WebSocket rewrite with auto-reconnection
  • Exponential backoff for reconnection attempts
  • Ping/pong heartbeat to detect dead connections
  • Connection state management (connecting, connected, reconnecting, etc.)
  • Support for ALL stream types (not just user data):
    • Aggregate trades, kline, ticker, depth
    • Combined streams support
    • Market data streams
  • Production-ready with proper error recovery

📊 5. Logging Mechanism

  • Pluggable logging interface (BinanceLogger)
  • ConsoleLogger with colored output
  • Logs: requests, responses, WebSocket events, rate limits
  • Custom logger support for monitoring integration
  • Sanitizes sensitive data (API keys, signatures)
  • Production observability and debugging

🏗️ Infrastructure Improvements:

  • HTTP client wrapper with proper timeout handling
  • Better error messages with context
  • Resource cleanup with dispose() methods
  • Backward compatible API
  • Zero breaking changes to existing code

📦 New Files (20 files):

  • lib/src/exceptions/* (4 files)
  • lib/src/config/* (1 file)
  • lib/src/http/* (1 file)
  • lib/src/rate_limiting/* (4 files)
  • lib/src/logging/* (3 files)
  • lib/src/websocket/* (4 files)

Updated Files:

  • lib/babel_binance.dart - Export new modules
  • lib/src/babel_binance_base.dart - Add config/logger support
  • lib/src/binance_base.dart - Integrate all improvements
  • lib/src/websockets.dart - Use new WebSocket client

Impact:
✅ Production-ready error handling
✅ Prevents API rate limit bans
✅ Configurable timeouts
✅ Reliable WebSocket connections
✅ Observable and debuggable
✅ Enterprise-grade quality

Breaking Changes: None (backward compatible)

Usage Example:

final binance = Binance(
  apiKey: 'YOUR_KEY',
  apiSecret: 'YOUR_SECRET',
  config: BinanceConfig(
    requestTimeout: Duration(seconds: 30),
    rateLimitConfig: RateLimitConfig.conservative,
  ),
  logger: ConsoleLogger(minLevel: LogLevel.debug),
);

try {
  final ticker = await binance.spot.market.get24HrTicker('BTCUSDT');
} on BinanceRateLimitException catch (e) {
  print('Rate limited! Retry after ${e.retryAfterSeconds}s');
} on BinanceAuthException catch (e) {
  print('Auth failed: ${e.message}');
}

Summary by CodeRabbit

  • New Features
    • Configuration system for customizing connection timeouts, failover behavior, and headers
    • Built-in logging with configurable debug and console output
    • Rate limiting protection with configurable limits to prevent API throttling
    • WebSocket streams with automatic reconnection and heartbeat monitoring
    • Enhanced error handling with specific exception types (rate limit, auth, network)
    • Expanded API surface with additional endpoints and modules now accessible

This commit implements 5 major improvements to make the babel_binance
wrapper production-ready and enterprise-grade:

🎯 1. Custom Exception Classes
- Added hierarchical exception system with specific error types
- BinanceApiException, BinanceRateLimitException, BinanceAuthException
- BinanceNetworkException, BinanceTimeoutException, BinanceParameterException
- Smart error detection (isRetryable, isAuthError, isRateLimitError)
- Better error handling with specific catch blocks

⚡ 2. Rate Limiting System
- Implemented token bucket algorithm for rate limiting
- Tracks REQUEST_WEIGHT, ORDERS, and RAW_REQUESTS limits
- Automatic throttling to prevent API bans
- Syncs with server-reported usage from response headers
- Configurable: throw vs wait, safety margins
- Prevents hitting Binance limits (1200 weight/min, 10 orders/sec)

⏱️ 3. Timeout Configuration
- Added BinanceConfig for comprehensive configuration
- Configurable request and connection timeouts
- Server time synchronization for accurate signatures
- Custom headers, user-agent, proxy support
- Preset configs: default, slow network, high-frequency
- Per-request timeout overrides

🔌 4. WebSocket Improvements
- Complete WebSocket rewrite with auto-reconnection
- Exponential backoff for reconnection attempts
- Ping/pong heartbeat to detect dead connections
- Connection state management (connecting, connected, reconnecting, etc.)
- Support for ALL stream types (not just user data):
  * Aggregate trades, kline, ticker, depth
  * Combined streams support
  * Market data streams
- Production-ready with proper error recovery

📊 5. Logging Mechanism
- Pluggable logging interface (BinanceLogger)
- ConsoleLogger with colored output
- Logs: requests, responses, WebSocket events, rate limits
- Custom logger support for monitoring integration
- Sanitizes sensitive data (API keys, signatures)
- Production observability and debugging

🏗️ Infrastructure Improvements:
- HTTP client wrapper with proper timeout handling
- Better error messages with context
- Resource cleanup with dispose() methods
- Backward compatible API
- Zero breaking changes to existing code

📦 New Files (20 files):
- lib/src/exceptions/* (4 files)
- lib/src/config/* (1 file)
- lib/src/http/* (1 file)
- lib/src/rate_limiting/* (4 files)
- lib/src/logging/* (3 files)
- lib/src/websocket/* (4 files)

Updated Files:
- lib/babel_binance.dart - Export new modules
- lib/src/babel_binance_base.dart - Add config/logger support
- lib/src/binance_base.dart - Integrate all improvements
- lib/src/websockets.dart - Use new WebSocket client

Impact:
✅ Production-ready error handling
✅ Prevents API rate limit bans
✅ Configurable timeouts
✅ Reliable WebSocket connections
✅ Observable and debuggable
✅ Enterprise-grade quality

Breaking Changes: None (backward compatible)

Usage Example:
```dart
final binance = Binance(
  apiKey: 'YOUR_KEY',
  apiSecret: 'YOUR_SECRET',
  config: BinanceConfig(
    requestTimeout: Duration(seconds: 30),
    rateLimitConfig: RateLimitConfig.conservative,
  ),
  logger: ConsoleLogger(minLevel: LogLevel.debug),
);

try {
  final ticker = await binance.spot.market.get24HrTicker('BTCUSDT');
} on BinanceRateLimitException catch (e) {
  print('Rate limited! Retry after ${e.retryAfterSeconds}s');
} on BinanceAuthException catch (e) {
  print('Auth failed: ${e.message}');
}
```
@mayankjanmejay mayankjanmejay merged commit ed01115 into main Nov 13, 2025
1 check was pending
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Nov 13, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The PR significantly expands babel_binance's public API infrastructure by introducing configuration management, comprehensive logging, structured exception handling, rate limiting, an HTTP wrapper, and refactored WebSocket support. The main Binance classes are enhanced to integrate these systems throughout the request lifecycle, including server-time synchronization and request signing. Multiple new modules are added and exported.

Changes

Cohort / File(s) Summary
Public API Reorganization
lib/babel_binance.dart
Comprehensive reorganization and expansion of exports. Removed auto_invest export, re-added it with others. Added grouped exports for configuration, exceptions (binance_exception, api_exception, network_exception, validation_exception), logging (logger, log_level, console_logger), rate limiting (rate_limiter, rate_limit_config), WebSocket (websocket_client, websocket_config, websocket_stream, stream_types), and API modules (spot, futures_usd, margin, testnet, websockets, simulated_convert, blvt, c2c, convert, copy_trading, fiat, futures_algo, futures_coin, gift_card, loan, mining, nft, pay, portfolio_margin, rebate, savings, simple_earn, staking, sub_account, vip_loan, wallet).
Main Entry Point Classes
lib/src/babel_binance_base.dart
Extended constructor to accept optional config and logger parameters with sensible defaults. Added public config and logger fields. Updated Binance.testnet factory to forward these parameters. Added dispose() method for resource cleanup.
Core Base Class
lib/src/binance_base.dart
Major enhancement: added public config, logger, and getRateLimitStatus() getter. Extended constructor to accept optional config and logger, with initialization of RateLimiter and BinanceHttpClient. Implemented server-time synchronization logic (private _initServerTimeSync, _getServerTimeInternal, _getSyncedTimestamp, _resyncServerTimeIfNeeded). Enhanced sendRequest signature to accept weight, isOrder, and timeout parameters. Implemented rate-limit checking, server-time resynchronization, request signing, failover logic, and exception mapping via _createExceptionFromResponse.
Configuration
lib/src/config/binance_config.dart
New class centralizing HTTP/API client configuration with fields: requestTimeout, connectTimeout, enableFailover, userAgent, customHeaders, proxyUrl, recvWindow, syncServerTime, rateLimitConfig. Provides const constructor with defaults and three predefined configurations: defaultConfig, slowNetwork, highFrequency. Includes copyWith method.
Exception Hierarchy
lib/src/exceptions/binance_exception.dart, api_exception.dart, network_exception.dart, validation_exception.dart
Introduced base abstract BinanceException with message, stackTrace, and timestamp fields. Added specialized exception classes: BinanceApiException (with statusCode, errorCode, errorMessage, responseBody; includes helpers isRateLimitError, isAuthError, isIpBan, isRetryable), BinanceRateLimitException (with retryAfterSeconds, rateLimitType), BinanceAuthException, BinanceIpBanException (with banUntil), BinanceParameterException (with parameterName); BinanceNetworkException (with originalError, url; includes isTimeout, isConnectionError), BinanceTimeoutException (with timeout). BinanceValidationException (with fieldName, invalidValue, constraint).
Logging Framework
lib/src/logging/log_level.dart, logger.dart, console_logger.dart
Introduced LogLevel enum (debug, info, warn, error, fatal, none) with severity codes and comparison operators. Added abstract BinanceLogger interface with methods: debug, info, warn, error, fatal, logRequest, logResponse, logWebSocket, logRateLimit, flush, close, and minLevel getter. Implemented NoOpLogger as default no-op implementation. Introduced ConsoleLogger with configurable minLevel, colorization, timestamps, JSON formatting, and body length truncation; includes specialized logging methods and internal formatting helpers.
Rate Limiting
lib/src/rate_limiting/rate_limit_config.dart, rate_limiter.dart, token_bucket.dart, weight_tracker.dart
Added RateLimitConfig with fields for request weight, orders per second/day, raw requests per minute, safety margin, and throwOnLimit behavior. Predefined configurations: spot, futuresUsd, conservative. Implemented RateLimiter orchestrating multiple TokenBucket instances (weight, raw requests, orders) and daily order counter; exposes checkLimit, processResponse, getStatus, reset. TokenBucket provides tryConsume, consume, availableTokens, usagePercent, reset with time-based refilling. WeightTracker monitors API weight usage from headers, tracks history, provides usagePercent and isApproachingLimit helpers. New RateLimitStatus data class reporting usage percentages and health status.
HTTP Client Wrapper
lib/src/http/binance_http_client.dart
New BinanceHttpClient wrapping http.Client with support for GET, POST, DELETE, PUT requests. Each method accepts optional per-call timeout (defaulting to config.requestTimeout). Translates timeouts to BinanceTimeoutException and socket errors to BinanceNetworkException. Private _buildHeaders method composes headers from config (including User-Agent and custom headers). Includes close() method for cleanup.
WebSocket Infrastructure
lib/src/websocket/stream_types.dart, websocket_config.dart, websocket_stream.dart, websocket_client.dart, lib/src/websockets.dart
Introduced StreamType enum and StreamConfig class with streamName getter and factory constructors (aggTrade, kline, ticker, depth) for building WebSocket stream identifiers. WebSocketConfig provides autoReconnect, maxReconnectAttempts, reconnect delay exponential backoff, ping interval, pong timeout, connection timeout, and debugMode fields; includes defaultConfig and aggressiveReconnect presets. New ConnectionState enum (disconnected, connecting, connected, reconnecting, disconnecting, failed). BinanceWebSocketStream manages a single WebSocketChannel with automatic reconnect, ping/pong heartbeat, message streaming, and lifecycle management. BinanceWebSocket client manages multiple streams, provides connectUserDataStream, connectMarketStream, connectCombinedStreams, with disconnectStream, disconnectAll, getStreamState, activeStreamUrls, activeStreamCount, and dispose. Refactored Websockets wrapper to use new BinanceWebSocket client and expose convenience stream methods (aggTradeStream, klineStream, tickerStream, depthStream).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Binance
    participant BinanceBase
    participant RateLimiter
    participant ServerTimeSync
    participant HttpClient
    participant BinanceException

    User->>Binance: new Binance(apiKey, apiSecret, config, logger)
    Binance->>BinanceBase: constructor with config & logger
    BinanceBase->>RateLimiter: initialize with config.rateLimitConfig
    BinanceBase->>ServerTimeSync: initServerTimeSync()
    ServerTimeSync-->>BinanceBase: serverTimeOffset established

    User->>Binance: sendRequest(method, path, params, weight, isOrder)
    Binance->>BinanceBase: delegate to sendRequest
    BinanceBase->>RateLimiter: checkLimit(weight, isOrder)
    alt Rate limit exceeded
        RateLimiter-->>BinanceException: throw BinanceRateLimitException
    else Within limits
        RateLimiter->>RateLimiter: consume tokens
    end
    BinanceBase->>ServerTimeSync: getSyncedTimestamp()
    alt Sync needed
        ServerTimeSync->>HttpClient: GET /api/v3/time
        HttpClient-->>ServerTimeSync: server time
        ServerTimeSync->>ServerTimeSync: update serverTimeOffset
    end
    BinanceBase->>BinanceBase: compute signature with synced timestamp
    BinanceBase->>HttpClient: get/post/delete/put with timeout
    HttpClient-->>BinanceBase: http.Response
    alt Error response
        BinanceBase->>BinanceException: _createExceptionFromResponse()
        BinanceException-->>BinanceBase: typed exception
    else Success
        BinanceBase->>RateLimiter: processResponse(headers)
        RateLimiter->>RateLimiter: update weight from X-MBX-USED-WEIGHT-1M
    end
    BinanceBase-->>Binance: Map<String, dynamic>
    Binance-->>User: response data

    User->>Binance: dispose()
    Binance->>BinanceBase: dispose()
    BinanceBase->>HttpClient: close()
Loading
sequenceDiagram
    participant User
    participant BinanceWebSocket
    participant BinanceWebSocketStream
    participant WebSocketChannel
    participant MessageLoop
    participant ReconnectLogic

    User->>BinanceWebSocket: connectMarketStream(streamConfig)
    BinanceWebSocket->>BinanceWebSocketStream: _connectToStream(url)
    alt Stream exists
        BinanceWebSocketStream-->>BinanceWebSocket: return existing stream
    else New stream
        BinanceWebSocketStream->>BinanceWebSocketStream: new BinanceWebSocketStream(url, config)
        BinanceWebSocket->>BinanceWebSocketStream: connect()
    end
    BinanceWebSocketStream->>WebSocketChannel: connect with timeout
    WebSocketChannel-->>BinanceWebSocketStream: connected
    BinanceWebSocketStream->>MessageLoop: start listening to messages
    BinanceWebSocketStream->>MessageLoop: start ping/pong heartbeat
    
    alt Message received
        WebSocketChannel-->>MessageLoop: message event
        MessageLoop->>MessageLoop: emit to _messageController
    else Connection lost
        MessageLoop->>ReconnectLogic: on error or close
        ReconnectLogic->>ReconnectLogic: exponential backoff delay
        ReconnectLogic->>BinanceWebSocketStream: auto-reconnect if enabled
    else Pong timeout
        ReconnectLogic->>BinanceWebSocketStream: trigger reconnect
    end
    
    User->>BinanceWebSocket: disconnectAll()
    BinanceWebSocket->>BinanceWebSocketStream: disconnect each stream
    BinanceWebSocketStream->>WebSocketChannel: close
    BinanceWebSocketStream->>MessageLoop: cancel subscription
    BinanceWebSocketStream->>ReconnectLogic: cancel timers
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Areas requiring extra attention:

  • Server time synchronization logic (binance_base.dart): The _initServerTimeSync, _getSyncedTimestamp, and _resyncServerTimeIfNeeded methods manage critical timestamp state for request signing. Edge cases include sync failures, race conditions during concurrent requests, and resync triggers.
  • Request signing with rate limiting integration (binance_base.dartsendRequest): Verify correct order of operations (rate limit check before signing, proper timestamp inclusion, signature calculation, and timeout handling).
  • Token bucket refill mechanics (token_bucket.dart): Ensure time-based token calculation is accurate; verify that consume() correctly waits for token availability and handles concurrent callers.
  • Rate limiter multi-bucket coordination (rate_limiter.dart): Confirm that weight, raw request, and order limits are enforced independently and that daily order counter resets work correctly across time boundaries.
  • WebSocket reconnection exponential backoff (websocket_stream.dart): Validate backoff calculation, max attempt handling, and state transitions during reconnection; check for resource leaks (timers, subscriptions).
  • Exception mapping from responses (binance_base.dart_createExceptionFromResponse): Ensure all API error codes map to correct exception types and that sensitive information is not leaked in exception messages.
  • Config and logger initialization defaults (binance_base.dart): Verify that BinanceConfig.defaultConfig and NoOpLogger() are applied correctly as fallbacks and that no null reference errors occur.

Poem

🐰 New configs bloom and rates are tamed,
WebSockets dance with reconnect aflame,
Exceptions flow through pipelines clean,
The finest Binance client ever seen!
With logs and limits, signatures signed—
A rabbit's code, so well-designed! 🎉

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/analyze-api-wrapper-011CV4vowFC73byanSEoLMnG

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bcb34c9 and 0945b38.

📒 Files selected for processing (21)
  • lib/babel_binance.dart (1 hunks)
  • lib/src/babel_binance_base.dart (2 hunks)
  • lib/src/binance_base.dart (2 hunks)
  • lib/src/config/binance_config.dart (1 hunks)
  • lib/src/exceptions/api_exception.dart (1 hunks)
  • lib/src/exceptions/binance_exception.dart (1 hunks)
  • lib/src/exceptions/network_exception.dart (1 hunks)
  • lib/src/exceptions/validation_exception.dart (1 hunks)
  • lib/src/http/binance_http_client.dart (1 hunks)
  • lib/src/logging/console_logger.dart (1 hunks)
  • lib/src/logging/log_level.dart (1 hunks)
  • lib/src/logging/logger.dart (1 hunks)
  • lib/src/rate_limiting/rate_limit_config.dart (1 hunks)
  • lib/src/rate_limiting/rate_limiter.dart (1 hunks)
  • lib/src/rate_limiting/token_bucket.dart (1 hunks)
  • lib/src/rate_limiting/weight_tracker.dart (1 hunks)
  • lib/src/websocket/stream_types.dart (1 hunks)
  • lib/src/websocket/websocket_client.dart (1 hunks)
  • lib/src/websocket/websocket_config.dart (1 hunks)
  • lib/src/websocket/websocket_stream.dart (1 hunks)
  • lib/src/websockets.dart (1 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@mayankjanmejay mayankjanmejay deleted the claude/analyze-api-wrapper-011CV4vowFC73byanSEoLMnG branch November 13, 2025 02:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants