Skip to content

Conversation

@lorenjphillips
Copy link

Problem

The binance.us staking endpoints use assert statements for region validation:

assert self.tld == "us", "Endpoint only available on binance.us"

This is problematic because assert statements are completely disabled when running Python with the -O (optimize) flag, which is common in production deployments. When this happens the validation silently disappears and users get confusing API errors from Binance instead of a clear client-side error.

Solution

Added BinanceRegionException - a proper exception class that:

  • Can't be disabled by interpreter flags
  • Gives callers a specific exception type to catch
  • Includes structured info (required_tld, actual_tld, endpoint_name)
# Now users can handle this properly
try:
    client.get_staking_asset_us()
except BinanceRegionException as e:
    print(f"Wrong region: need {e.required_tld}, got {e.actual_tld}")

Changes

  • Added BinanceRegionException to exceptions.py
  • Added _require_tld() helper to BaseClient
  • Replaced 6 asserts in client.py and 6 in async_client.py
  • Added tests covering all affected endpoints

Testing

All 15 new tests pass. Ran linting with ruff, no issues.

tests/test_region_exception.py - 15 passed

assert statements get disabled when running python with -O flag which
means the region check silently dissapears in production. Replaced with
BinanceRegionException that gives callers a proper catchable error type.

Affects get_staking_asset_us, stake_asset_us, unstake_asset_us,
get_staking_balance_us, get_staking_history_us, get_staking_rewards_history_us
Copy link
Collaborator

@pcriadoperez pcriadoperez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks for the contribution!

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