Skip to main content

Client

Pass these parameters when creating ToncenterRestClient:
ParameterDefaultDescription
api_key""API key from @toncenter bot. Optional for REST; required for streaming.
networkRequiredNetwork.MAINNET or Network.TESTNET.
base_urlOptionalCustom base URL (overrides network).
timeout10 secondsRequest timeout.
sessionOptionalExternal aiohttp.ClientSession.
headersOptionalExtra HTTP headers sent with every request.
cookiesOptionalExtra cookies sent with every request.
rps_limit0 (off)Client-side rate limit (requests per second).
rps_period1.0Rate-limiter window in seconds.
retry_policyEnabledRetry policy, or None to disable.
The rps_limit parameter throttles requests locally on the client side. The server enforces its own rate limits independently — see API Key.

Sessions

The recommended approach — session is created and closed automatically:
from toncenter.rest import ToncenterRestClient
from toncenter.types import Network

async with ToncenterRestClient(network=Network.MAINNET) as client:
    balance = await client.v2.accounts.get_address_balance("EQDtFpEwcFAEcRe5mLVh2N6C0x-_hJEM7W61_JLnSF74p4q2")

Manual

from toncenter.rest import ToncenterRestClient
from toncenter.types import Network

client = ToncenterRestClient(network=Network.MAINNET)
await client.create_session()
try:
    balance = await client.v2.accounts.get_address_balance("EQDtFpEwcFAEcRe5mLVh2N6C0x-_hJEM7W61_JLnSF74p4q2")
finally:
    await client.close_session()

External

Bring your own aiohttp.ClientSession to share it across multiple clients:
import aiohttp

from toncenter.rest import ToncenterRestClient
from toncenter.types import Network

async with aiohttp.ClientSession() as session:
    async with ToncenterRestClient(
        network=Network.MAINNET,
        session=session,
    ) as client:
        balance = await client.v2.accounts.get_address_balance("EQDtFpEwcFAEcRe5mLVh2N6C0x-_hJEM7W61_JLnSF74p4q2")
The client does not close an external session — you manage its lifecycle yourself.

Retries

Rate-limited (429) and server-error (5xx) responses are retried automatically with exponential backoff.
Status codesMax retriesBase delayMax delayBackoff
42950.3 s3 s2x
5xx30.5 s5 s2x
Custom policy:
from toncenter.types import RetryPolicy, RetryRule

client = ToncenterRestClient(
    network=Network.MAINNET,
    retry_policy=RetryPolicy(rules=(
        RetryRule(
            statuses=frozenset({429}),
            max_retries=10,
            base_delay=0.5,
            max_delay=10.0,
            backoff_factor=2.0,
        ),
    )),
)
FieldDefaultDescription
statusesRequiredHTTP status codes that trigger retry.
max_retries3Maximum retry attempts.
base_delay1 secondInitial delay.
max_delay30 secondsUpper bound after backoff.
backoff_factor2.0Multiplier per attempt.
Pass retry_policy=None to disable retries entirely.

Utilities

from toncenter.utils import raw_to_userfriendly, userfriendly_to_raw, to_nano, to_amount

Address conversion

raw_to_userfriendly

Convert a raw address (workchain:hex) to user-friendly base64 format.
raw = "0:83ae019a23a8162beaa5cb0ebdc56668b2eac6c6ba51808812915b206a152dc5"

raw_to_userfriendly(raw)
# UQCDrgGaI6gWK-qlyw69xWZosurGxrpRgIgSkVsgahUtxZR0

raw_to_userfriendly(raw, is_bounceable=True)
# EQCDrgGaI6gWK-qlyw69xWZosurGxrpRgIgSkVsgahUtxcmx

raw_to_userfriendly(raw, is_test_only=True)
# 0QCDrgGaI6gWK-qlyw69xWZosurGxrpRgIgSkVsgahUtxS_-

raw_to_userfriendly(raw, is_test_only=True, is_bounceable=True)
# kQCDrgGaI6gWK-qlyw69xWZosurGxrpRgIgSkVsgahUtxXI7
ParameterDefaultDescription
addressRequiredRaw address in workchain:hex form.
is_bounceableFalseBounceable flag (tag 0x11 vs 0x51).
is_url_safeTrueUse URL-safe base64 encoding.
is_test_onlyFalseMark as test-only address.

userfriendly_to_raw

Convert a user-friendly base64 address back to raw format.
userfriendly_to_raw("EQCDrgGaI6gWK-qlyw69xWZosurGxrpRgIgSkVsgahUtxcmx")
# 0:83ae019a23a8162beaa5cb0ebdc56668b2eac6c6ba51808812915b206a152dc5
ParameterDefaultDescription
addressRequiredUser-friendly base64 address.
Accepts both standard and URL-safe base64. Raises ValueError on invalid input.

Amount conversion

to_nano

Convert a human-readable amount to the smallest unit (nanotons for TON).
to_nano(1.5)                # 1_500_000_000
to_nano("0.001")            # 1_000_000
to_nano(100, decimals=6)    # 100_000_000 (USDT)
ParameterDefaultDescription
valueRequiredAmount as int, float, str, or Decimal.
decimals9Decimal places (9 for TON).

to_amount

Convert the smallest unit back to a human-readable Decimal.
to_amount(1_500_000_000)               # Decimal("1.5")
to_amount(1_500_000_000, precision=2)  # Decimal("1.50")
to_amount(100_000_000, decimals=6)     # Decimal("100")
ParameterDefaultDescription
valueRequiredAmount in smallest units.
decimals9Decimal places (9 for TON).
precisionOptionalRound result to N decimal places.

Errors

All SDK exceptions inherit from ToncenterError. Catch it to handle any error from the library.
from toncenter.exceptions import ToncenterError

Client errors (4xx)

CodeExceptionDescription
400ToncenterBadRequestErrorCheck query parameters, request body, and path arguments.
401ToncenterUnauthorizedErrorInvalid API key. Obtain one via @toncenter bot.
403ToncenterForbiddenErrorAPI key was issued for a different network.
404ToncenterNotFoundErrorResource does not exist.
405ToncenterMethodNotAllowedErrorUse GET or POST.
409ToncenterConflictErrorResource does not match the expected type.
422ToncenterUnprocessableErrorParameters failed validation.
429ToncenterTooManyRequestsErrorRate limit exceeded. Back off and retry.

Server errors (5xx)

CodeExceptionDescription
500ToncenterInternalServerErrorInternal server error.
504ToncenterGatewayTimeoutErrorLiteserver timeout. Retry the request.
542ToncenterLiteServerErrorLiteserver error or unsupported TVM stack type.
V2 API may return all listed codes. V3 API typically returns 401, 404, 409, 422, and 500.

Other exceptions

ExceptionWhen
ToncenterConnectionErrorDNS failure, TCP timeout, or refused connection — before any HTTP response.
ToncenterValidationErrorResponse body did not match the expected Pydantic model.
ToncenterSessionErrorRequest made before client session was initialized.
ToncenterStreamingErrorTransport-level error during streaming.
ToncenterConnectionLostErrorReconnect limit exhausted during streaming.
ToncenterRetryErrorAll retry attempts exhausted.