### Install PyTonConnect Source: https://context7.com/xabbl4/pytonconnect/llms.txt Install the pytonconnect package using pip. This command is used to add the library to your Python environment. ```bash pip install pytonconnect ``` -------------------------------- ### FileStorage Source: https://context7.com/xabbl4/pytonconnect/llms.txt A file-backed implementation of `IStorage` that serializes connection state to a JSON file, enabling session restoration across process restarts. Use `use_cache=False` to always read directly from disk, which is safe for multi-process setups. ```APIDOC ## `FileStorage` — Persistent Session Storage A file-backed implementation of `IStorage` that serialises connection state to a JSON file. Enables session restoration across process restarts. Use `use_cache=False` to always read directly from disk (safe for multi-process setups). ```python from pytonconnect import TonConnect from pytonconnect.storage import FileStorage # Default: in-process cache + write-through to file storage = FileStorage('ton_session.json') # No cache: every read goes to disk (use for multi-process / shared storage) storage_no_cache = FileStorage('ton_session.json', use_cache=False) connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) ``` ``` -------------------------------- ### Initialize Wallet Connection via Universal Link Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md Generates a universal link to initiate a wallet connection. This link should be presented to the user (e.g., as a QR code or deep link). Connection approval is signaled via the status change callback. ```python generated_url = await connector.connect(wallets_list[0]) print('generated_url:', generated_url) ``` -------------------------------- ### Custom Redis Storage Backend Source: https://context7.com/xabbl4/pytonconnect/llms.txt Implement `IStorage` to integrate custom backends like Redis for storing connection data. Ensure the Redis client is properly initialized and connected. ```python import json import redis.asyncio as aioredis from pytonconnect.storage import IStorage class RedisStorage(IStorage): def __init__(self, redis_client: aioredis.Redis, prefix: str = 'tonconnect'): self._redis = redis_client self._prefix = prefix def _key(self, key: str) -> str: return f'{self._prefix}:{key}' async def set_item(self, key: str, value: str): await self._redis.set(self._key(key), value) async def get_item(self, key: str, default_value: str = None) -> str: val = await self._redis.get(self._key(key)) return val.decode() if val is not None else default_value async def remove_item(self, key: str): await self._redis.delete(self._key(key)) # Usage async def main(): redis = await aioredis.from_url('redis://localhost') storage = RedisStorage(redis, prefix='user:42:tonconnect') connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) await connector.restore_connection() ``` -------------------------------- ### Initialize Connector and Restore Connection Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md Initializes the TonConnect connector and attempts to restore a previous connection if one exists. Requires the manifest URL. ```python import asyncio from pytonconnect import TonConnect async def main(): connector = TonConnect(manifest_url='https://raw.githubusercontent.com/XaBbl4/pytonconnect/main/pytonconnect-manifest.json') is_connected = await connector.restore_connection() print('is_connected:', is_connected) if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(main()) ``` -------------------------------- ### Fetch Supported Wallets List Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md Retrieves a list of all supported TON wallets. This can be done using an instance of the connector or statically. ```python wallets_list = connector.get_wallets() # wallets_list is # [ # { # name: str, # image: str, # about_url: str, # bridge_url: str, # universal_url: str, # }, # ] ``` ```python wallets_list = TonConnect.get_wallets() ``` -------------------------------- ### Fetch Supported Wallets Source: https://context7.com/xabbl4/pytonconnect/llms.txt Retrieve a list of TON-Connect-compatible wallets. This can be called statically or on an instance, respecting custom sources and cache settings. ```python # Static call — no connector instance needed wallets = TonConnect.get_wallets() # Instance call — honours custom wallets_list_source and cache_ttl wallets = connector.get_wallets() # Each wallet dict contains: # { # 'name': 'Tonkeeper', # 'image': 'https://...', # 'about_url': 'https://tonkeeper.com', # 'app_name': 'tonkeeper', # may be None # 'bridge_url': 'https://bridge.tonapi.io/bridge', # 'universal_url': 'https://app.tonkeeper.com/ton-connect', # } for w in wallets: print(w['name'], '->', w.get('universal_url')) ``` -------------------------------- ### Await Wallet Approval with TonConnect.wait_for_connection Source: https://context7.com/xabbl4/pytonconnect/llms.txt Awaits user approval for a wallet connection. Resolves with `WalletInfo` upon approval or `TonConnectError` on failure. Restores existing connections if available. ```python import asyncio from pytonconnect import TonConnect from pytonconnect.storage import FileStorage from pytonconnect.exceptions import TonConnectError async def main(): storage = FileStorage('session.json') connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) is_connected = await connector.restore_connection() if not is_connected: wallets = connector.get_wallets() url = await connector.connect(wallets[0]) print('Connect at:', url) result = await connector.wait_for_connection() if isinstance(result, TonConnectError): print('Connection failed:', result) else: print('Connected:', result.account.address) asyncio.run(main()) ``` -------------------------------- ### Initialize TonConnect Connector Source: https://context7.com/xabbl4/pytonconnect/llms.txt Initialize the TonConnect connector. The manifest_url is mandatory. Optional parameters include storage for session persistence and API tokens for bridge authentication. ```python import asyncio from pytonconnect import TonConnect from pytonconnect.storage import FileStorage # In-memory storage (default) — session lost on restart connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) # File-backed storage — session persists across restarts connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=FileStorage('session.json'), wallets_list_cache_ttl=86400, # cache wallet list for 24 h api_tokens={'https://bridge.tonapi.io/bridge': 'my-api-token'}, ) ``` -------------------------------- ### Custom IStorage Source: https://context7.com/xabbl4/pytonconnect/llms.txt Implement the three abstract async methods (`set_item`, `get_item`, `remove_item`) to store connection data in any backend, such as Redis or a database, enabling custom storage solutions. ```APIDOC ## Custom `IStorage` — Implement Your Own Storage Backend Implement the three abstract async methods to store connection data in any backend (Redis, database, etc.). ```python import json import redis.asyncio as aioredis from pytonconnect.storage import IStorage class RedisStorage(IStorage): def __init__(self, redis_client: aioredis.Redis, prefix: str = 'tonconnect'): self._redis = redis_client self._prefix = prefix def _key(self, key: str) -> str: return f'{self._prefix}:{key}' async def set_item(self, key: str, value: str): await self._redis.set(self._key(key), value) async def get_item(self, key: str, default_value: str = None) -> str: val = await self._redis.get(self._key(key)) return val.decode() if val is not None else default_value async def remove_item(self, key: str): await self._redis.delete(self._key(key)) # Usage async def main(): redis = await aioredis.from_url('redis://localhost') storage = RedisStorage(redis, prefix='user:42:tonconnect') connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) await connector.restore_connection() ``` ``` -------------------------------- ### TonConnect.__init__ Source: https://context7.com/xabbl4/pytonconnect/llms.txt Initializes a TonConnect instance. Manages the bridge provider connection to a user's wallet. Supports pluggable session storage and API tokens for bridge authentication. ```APIDOC ## TonConnect.__init__ Creates a `TonConnect` instance. `manifest_url` is required; all other parameters are optional. `storage` defaults to an in-memory store; supply a `FileStorage` instance to persist sessions across process restarts. `api_tokens` can pass bridge-specific auth tokens as `{"bridge_url": "token"}`. ```python import asyncio from pytonconnect import TonConnect from pytonconnect.storage import FileStorage # In-memory storage (default) — session lost on restart connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) # File-backed storage — session persists across restarts connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=FileStorage('session.json'), wallets_list_cache_ttl=86400, # cache wallet list for 24 h api_tokens={'https://bridge.tonapi.io/bridge': 'my-api-token'}, ) ``` ``` -------------------------------- ### Subscribe to Connection Status Changes Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md Sets up a callback function to be notified when the wallet connection status changes. Remember to call the returned unsubscribe function when no longer needed. ```python def status_changed(wallet_info): # update state/reactive variables to show updates in the ui print('wallet_info:', wallet_info) unsubscribe() unsubscribe = connector.on_status_change(status_changed) # call unsubscribe() later to save resources when you don't need to listen for updates anymore. ``` -------------------------------- ### Add tonconnect-manifest.json Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md The manifest file provides meta-information to the wallet. Ensure the manifest is accessible via its URL. ```json { "url": "", // required "name": "", // required "iconUrl": "", // required "termsOfUseUrl": "", // optional "privacyPolicyUrl": "" // optional } ``` -------------------------------- ### Generate Connection URL with TonConnect.connect Source: https://context7.com/xabbl4/pytonconnect/llms.txt Generates a universal link for QR codes or deep links to initiate wallet connection. Optionally includes `ton_proof` for ownership verification. ```python import asyncio from pytonconnect import TonConnect async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) wallets = connector.get_wallets() # Basic connection url = await connector.connect(wallets[0]) print('Show this QR code or deep link to the user:', url) # Connection with ton_proof ownership challenge proof_payload = 'my_random_challenge_payload_hex' url_with_proof = await connector.connect(wallets[0], { 'ton_proof': proof_payload }) print('Proof URL:', url_with_proof) asyncio.run(main()) ``` -------------------------------- ### Pause and Unpause SSE Connection Source: https://context7.com/xabbl4/pytonconnect/llms.txt Use `pause_connection` to release server resources when no wallet interaction is expected, and `unpause_connection` to resume it. ```python # Pause to save server resources (e.g., during idle periods) connector.pause_connection() # Resume when interaction is needed again await connector.unpause_connection() ``` -------------------------------- ### App Manifest Configuration Source: https://context7.com/xabbl4/pytonconnect/llms.txt A JSON manifest file is required for your application to be identified by TON wallets. This file should be publicly accessible. ```json { "url": "https://myapp.example.com", "name": "My TON App", "iconUrl": "https://myapp.example.com/icon.png", "termsOfUseUrl": "https://myapp.example.com/terms", "privacyPolicyUrl": "https://myapp.example.com/privacy" } ``` -------------------------------- ### TonConnect.wait_for_connection Source: https://context7.com/xabbl4/pytonconnect/llms.txt Awaits for the user to approve the connection in their wallet. It returns an `asyncio.Future` that resolves with `WalletInfo` upon approval or `TonConnectError` on failure. Resolves immediately if already connected. ```APIDOC ## `TonConnect.wait_for_connection` — Await Wallet Approval Returns an `asyncio.Future` that resolves with a `WalletInfo` object (or a `TonConnectError`) once the user approves the connection in their wallet. Resolves immediately if already connected. ```python import asyncio from pytonconnect import TonConnect from pytonconnect.storage import FileStorage from pytonconnect.exceptions import TonConnectError async def main(): storage = FileStorage('session.json') connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) is_connected = await connector.restore_connection() if not is_connected: wallets = connector.get_wallets() url = await connector.connect(wallets[0]) print('Connect at:', url) result = await connector.wait_for_connection() if isinstance(result, TonConnectError): print('Connection failed:', result) else: print('Connected:', result.account.address) asyncio.run(main()) ``` ``` -------------------------------- ### File Storage for Session Persistence Source: https://context7.com/xabbl4/pytonconnect/llms.txt Use `FileStorage` to serialize connection state to a JSON file, enabling session restoration across restarts. Set `use_cache=False` for multi-process safety. ```python from pytonconnect import TonConnect from pytonconnect.storage import FileStorage # Default: in-process cache + write-through to file storage = FileStorage('ton_session.json') # No cache: every read goes to disk (use for multi-process / shared storage) storage_no_cache = FileStorage('ton_session.json', use_cache=False) connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=storage, ) ``` -------------------------------- ### TonConnect.get_wallets Source: https://context7.com/xabbl4/pytonconnect/llms.txt Fetches the list of TON-Connect-compatible wallets from the official registry. This can be called as a static method or on an instance, respecting custom configurations like `wallets_list_source` and `cache_ttl`. ```APIDOC ## TonConnect.get_wallets Returns the list of TON-Connect-compatible wallets fetched from the official wallets registry (falls back to a built-in list on network error). Can be called as a static method or on an instance. ```python # Static call — no connector instance needed wallets = TonConnect.get_wallets() # Instance call — honours custom wallets_list_source and cache_ttl wallets = connector.get_wallets() # Each wallet dict contains: # { # 'name': 'Tonkeeper', # 'image': 'https://...', # 'about_url': 'https://tonkeeper.com', # 'app_name': 'tonkeeper', # may be None # 'bridge_url': 'https://bridge.tonapi.io/bridge', # 'universal_url': 'https://app.tonkeeper.com/ton-connect', # } for w in wallets: print(w['name'], '->', w.get('universal_url')) ``` ``` -------------------------------- ### TonConnect.connect Source: https://context7.com/xabbl4/pytonconnect/llms.txt Generates a connection URL for users to connect their wallets. This URL can be presented as a QR code or a deep link. It supports optional `ton_proof` for ownership verification. ```APIDOC ## `TonConnect.connect` — Generate a Connection URL Subscribes to the wallet's bridge and returns a universal link (used as a QR code or deep link) that the user opens in their wallet app. Raises `WalletAlreadyConnectedError` if already connected. Optionally accepts a `ton_proof` payload for ownership verification. ```python import asyncio from pytonconnect import TonConnect async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) wallets = connector.get_wallets() # Basic connection url = await connector.connect(wallets[0]) print('Show this QR code or deep link to the user:', url) # Connection with ton_proof ownership challenge proof_payload = 'my_random_challenge_payload_hex' url_with_proof = await connector.connect(wallets[0], { 'ton_proof': proof_payload }) print('Proof URL:', url_with_proof) asyncio.run(main()) ``` ``` -------------------------------- ### Restore Previous Wallet Session Source: https://context7.com/xabbl4/pytonconnect/llms.txt Attempt to restore a previous wallet connection using stored session data. This should be called on application startup to re-establish a connection if one exists. ```python async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=FileStorage('session.json'), ) is_connected = await connector.restore_connection() if is_connected: print('Restored session:', connector.account.address) # connector.connected == True # connector.account.chain == '-239' (CHAIN.MAINNET) else: print('No previous session found.') asyncio.run(main()) ``` -------------------------------- ### Inspect Connection State Source: https://context7.com/xabbl4/pytonconnect/llms.txt Access read-only properties on the connector to inspect the current connection state without needing callbacks. This includes checking if a wallet is connected, retrieving account details, wallet information, and the active universal URL. ```APIDOC ## `TonConnect` Properties — Inspect Connection State Access read-only properties on the connector to inspect current connection state without callbacks. ```python connector = TonConnect(manifest_url='...') await connector.restore_connection() print(connector.connected) # bool — True if wallet is connected print(connector.account) # Account | None print(connector.wallet) # WalletInfo | None print(connector.url) # str | None — the active universal_url if connector.connected: acc = connector.account print(acc.address) # "0:" workchain:hash format print(acc.chain) # "-239" (MAINNET) or "-3" (TESTNET) print(acc.public_key) # hex string (no 0x prefix) print(acc.wallet_state_init) # base64 state_init for key derivation dev = connector.wallet.device print(dev.platform) # "iphone" | "android" | "windows" | ... print(dev.app_name) # "Tonkeeper" print(dev.app_version) # "2.3.367" print(dev.max_protocol_version) # int ``` ``` -------------------------------- ### TonConnect.on_status_change Source: https://context7.com/xabbl4/pytonconnect/llms.txt Subscribes a callback function to listen for changes in the wallet connection status. It also accepts an optional error handler for connection failures. Returns an `unsubscribe` callable to stop listening. ```APIDOC ## TonConnect.on_status_change Registers a callback that fires whenever the wallet connection state changes. Returns an `unsubscribe` callable. An optional `errors_handler` callback receives `TonConnectError` instances on connect failures. ```python def on_connected(wallet_info): if wallet_info is None: print('Wallet disconnected') else: print('Connected wallet:', wallet_info.account.address) print('Platform:', wallet_info.device.platform) print('App:', wallet_info.device.app_name, wallet_info.device.app_version) def on_error(error): print('Connection error:', error) unsubscribe = connector.on_status_change(on_connected, on_error) # Later, to stop listening: unsubscribe() ``` ``` -------------------------------- ### TonConnect.restore_connection Source: https://context7.com/xabbl4/pytonconnect/llms.txt Attempts to reconnect to a previously connected wallet using stored session data. This method should be called on application startup to restore existing connections. ```APIDOC ## TonConnect.restore_connection Attempts to reconnect to a previously connected wallet using data stored in the configured storage. Should be called immediately on app startup. Returns `True` if a session was restored. ```python async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json', storage=FileStorage('session.json'), ) is_connected = await connector.restore_connection() if is_connected: print('Restored session:', connector.account.address) # connector.connected == True # connector.account.chain == '-239' (CHAIN.MAINNET) else: print('No previous session found.') asyncio.run(main()) ``` ``` -------------------------------- ### WalletInfo.check_proof Source: https://context7.com/xabbl4/pytonconnect/llms.txt Cryptographically verifies the `ton_proof` signature returned by the wallet during connection. This confirms the user controls the private key for the claimed address and should always be called server-side after receiving a `ton_proof` response. ```APIDOC ## `WalletInfo.check_proof` — Verify Wallet Ownership (ton_proof) Cryptographically verifies the `ton_proof` signature returned by the wallet during connection, confirming the user controls the private key for the claimed address. Should always be called server-side after receiving a `ton_proof` response. ```python import asyncio from datetime import datetime from nacl.utils import random from pytonconnect import TonConnect from pytonconnect.parsers import WalletInfo def generate_payload(ttl_seconds: int) -> str: """Generate a time-limited random challenge payload.""" payload = bytearray(random(8)) expire_ts = int(datetime.now().timestamp()) + ttl_seconds payload.extend(expire_ts.to_bytes(8, 'big')) return payload.hex() def verify_proof(payload: str, wallet_info: WalletInfo) -> bool: """Return True only if signature is valid and payload has not expired.""" if len(payload) < 32: return False if not wallet_info.check_proof(payload): return False expire_ts = int(payload[16:32], 16) return datetime.now().timestamp() <= expire_ts async def main(): proof_payload = generate_payload(ttl_seconds=600) # valid 10 minutes connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) def status_changed(wallet_info: WalletInfo): if wallet_info is not None: is_valid = verify_proof(proof_payload, wallet_info) print('Proof valid:', is_valid) print('Wallet address:', wallet_info.account.address) unsubscribe() unsubscribe = connector.on_status_change(status_changed) wallets = connector.get_wallets() url = await connector.connect(wallets[0], {'ton_proof': proof_payload}) print('Connect URL:', url) for _ in range(120): await asyncio.sleep(1) if connector.connected: break asyncio.run(main()) ``` ``` -------------------------------- ### Verify Wallet Ownership with ton_proof Source: https://context7.com/xabbl4/pytonconnect/llms.txt Cryptographically verifies the `ton_proof` signature server-side to confirm user control of the claimed address. Ensure the payload has not expired before verification. ```python import asyncio from datetime import datetime from nacl.utils import random from pytonconnect import TonConnect from pytonconnect.parsers import WalletInfo def generate_payload(ttl_seconds: int) -> str: """Generate a time-limited random challenge payload.""" payload = bytearray(random(8)) expire_ts = int(datetime.now().timestamp()) + ttl_seconds payload.extend(expire_ts.to_bytes(8, 'big')) return payload.hex() def verify_proof(payload: str, wallet_info: WalletInfo) -> bool: """Return True only if signature is valid and payload has not expired.""" if len(payload) < 32: return False if not wallet_info.check_proof(payload): return False expire_ts = int(payload[16:32], 16) return datetime.now().timestamp() <= expire_ts async def main(): proof_payload = generate_payload(ttl_seconds=600) # valid 10 minutes connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) def status_changed(wallet_info: WalletInfo): if wallet_info is not None: is_valid = verify_proof(proof_payload, wallet_info) print('Proof valid:', is_valid) print('Wallet address:', wallet_info.account.address) unsubscribe() unsubscribe = connector.on_status_change(status_changed) wallets = connector.get_wallets() url = await connector.connect(wallets[0], {'ton_proof': proof_payload}) print('Connect URL:', url) for _ in range(120): await asyncio.sleep(1) if connector.connected: break asyncio.run(main()) ``` -------------------------------- ### Exception Hierarchy Source: https://context7.com/xabbl4/pytonconnect/llms.txt All SDK exceptions inherit from `TonConnectError`. Catch specific subclasses for precise error handling, such as `UserRejectsError` when a user declines an action, or `WalletNotConnectedError` if attempting an action without a connected wallet. ```APIDOC ## Exception Hierarchy All SDK exceptions inherit from `TonConnectError`. Catch specific subclasses for precise error handling. ```python from pytonconnect.exceptions import ( TonConnectError, WalletAlreadyConnectedError, # connect() called while already connected WalletNotConnectedError, # send_transaction/disconnect with no wallet WalletNotSupportFeatureError, # wallet can't handle requested feature UserRejectsError, # user declined in wallet UI ManifestNotFoundError, # manifest URL returned 404 ManifestContentError, # manifest JSON is malformed FetchWalletsError, # wallets list fetch failed BadRequestError, # malformed RPC request UnknownAppError, # app not connected to injected wallet ) try: result = await connector.send_transaction(tx) except UserRejectsError: print('User cancelled.') except WalletNotConnectedError: print('Connect a wallet first.') except WalletNotSupportFeatureError as e: print('Wallet cannot process this transaction:', e) except TonConnectError as e: print('TON Connect error:', e) ``` ``` -------------------------------- ### TonConnect.pause_connection / unpause_connection Source: https://context7.com/xabbl4/pytonconnect/llms.txt Manages the underlying HTTP SSE bridge connection by pausing or resuming it. This is useful in server/backend contexts to release resources when no wallet interaction is expected. ```APIDOC ## `TonConnect.pause_connection` / `unpause_connection` — Manage Bridge SSE Connection Pauses or resumes the underlying HTTP SSE bridge connection. Useful in server/backend contexts to release resources when no wallet interaction is expected. ```python # Pause to save server resources (e.g., during idle periods) connector.pause_connection() # Resume when interaction is needed again await connector.unpause_connection() ``` ``` -------------------------------- ### Handle TonConnect SDK Exceptions Source: https://context7.com/xabbl4/pytonconnect/llms.txt All SDK exceptions inherit from TonConnectError. Catch specific subclasses for precise error handling, such as when a user rejects a transaction or a wallet is not connected. ```python from pytonconnect.exceptions import ( TonConnectError, WalletAlreadyConnectedError, # connect() called while already connected WalletNotConnectedError, # send_transaction/disconnect with no wallet WalletNotSupportFeatureError, # wallet can't handle requested feature UserRejectsError, # user declined in wallet UI ManifestNotFoundError, # manifest URL returned 404 ManifestContentError, # manifest JSON is malformed FetchWalletsError, # wallets list fetch failed BadRequestError, # malformed RPC request UnknownAppError, # app not connected to injected wallet ) try: result = await connector.send_transaction(tx) except UserRejectsError: print('User cancelled.') except WalletNotConnectedError: print('Connect a wallet first.') except WalletNotSupportFeatureError as e: print('Wallet cannot process this transaction:', e) except TonConnectError as e: print('TON Connect error:', e) ``` -------------------------------- ### TonConnect.disconnect Source: https://context7.com/xabbl4/pytonconnect/llms.txt Disconnects the wallet, clears the session, and updates the connection status. Raises `WalletNotConnectedError` if no wallet is connected. ```APIDOC ## `TonConnect.disconnect` — Disconnect the Wallet Sends a disconnect request to the wallet, clears the stored session, and triggers `on_status_change` callbacks with `None`. Raises `WalletNotConnectedError` if no wallet is currently connected. ```python async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) await connector.restore_connection() if connector.connected: await connector.disconnect() print('Disconnected. connector.connected =', connector.connected) # False print('connector.account =', connector.account) # None ``` ``` -------------------------------- ### Inspect TonConnect Connection State Source: https://context7.com/xabbl4/pytonconnect/llms.txt Access read-only properties on the connector to inspect the current connection state without needing callbacks. This is useful for checking connection status, account details, and wallet information. ```python connector = TonConnect(manifest_url='...') await connector.restore_connection() print(connector.connected) # bool — True if wallet is connected print(connector.account) # Account | None print(connector.wallet) # WalletInfo | None print(connector.url) # str | None — the active universal_url if connector.connected: acc = connector.account print(acc.address) # "0:" workchain:hash format print(acc.chain) # "-239" (MAINNET) or "-3" (TESTNET) print(acc.public_key) # hex string (no 0x prefix) print(acc.wallet_state_init) # base64 state_init for key derivation dev = connector.wallet.device print(dev.platform) # "iphone" | "android" | "windows" | ... print(dev.app_name) # "Tonkeeper" print(dev.app_version) # "2.3.367" print(dev.max_protocol_version) # int ``` -------------------------------- ### Disconnect Wallet with TonConnect.disconnect Source: https://context7.com/xabbl4/pytonconnect/llms.txt Sends a disconnect request to the wallet and clears the session. Triggers status change callbacks. Raises `WalletNotConnectedError` if no wallet is connected. ```python async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) await connector.restore_connection() if connector.connected: await connector.disconnect() print('Disconnected. connector.connected =', connector.connected) # False print('connector.account =', connector.account) # None ``` -------------------------------- ### Send Transaction Source: https://github.com/xabbl4/pytonconnect/blob/main/README.md Constructs and sends a transaction to the TON blockchain. Handles potential user rejection or other errors during the process. ```python transaction = { 'valid_until': 1681223913, 'messages': [ { 'address': '0:0000000000000000000000000000000000000000000000000000000000000000', 'amount': '1', # 'stateInit': 'base64_YOUR_STATE_INIT' # just for instance. Replace with your transaction state_init or remove }, { 'address': '0:0000000000000000000000000000000000000000000000000000000000000000', 'amount': '1', # 'payload': 'base64_YOUR_PAYLOAD' # just for instance. Replace with your transaction payload or remove } ] } try: result = await connector.send_transaction(transaction) print('Transaction was sent successfully') except Exception as e: if isintance(e, UserRejectsError): print('You rejected the transaction. Please confirm it to send to the blockchain') else: print('Unknown error:', e) ``` -------------------------------- ### Request Transaction with TonConnect.send_transaction Source: https://context7.com/xabbl4/pytonconnect/llms.txt Requests a connected wallet to sign and send a transaction. Handles potential errors like user rejection or unsupported features. Supports transactions defined as plain dicts or `TransactionMessage` objects. ```python import asyncio from datetime import datetime from pytonconnect import TonConnect from pytonconnect.exceptions import UserRejectsError, WalletNotConnectedError from pytonconnect.parsers import TransactionMessage async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) await connector.restore_connection() # Transaction using plain dicts transaction = { 'valid_until': int(datetime.now().timestamp()) + 900, # 15 min TTL 'messages': [ { 'address': '0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', 'amount': '50000000', # 0.05 TON in nanotons 'payload': 'base64_encoded_cell_payload', # optional 'stateInit': 'base64_encoded_state_init', # optional } ] } # Alternatively, use the TransactionMessage dataclass msg = TransactionMessage( address='0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', amount=50000000, payload='base64_encoded_cell_payload', ) transaction_typed = { 'valid_until': int(datetime.now().timestamp()) + 900, 'messages': [msg], } try: result = await connector.send_transaction(transaction) print('Transaction sent. BoC:', result['boc']) # Decode the BoC to get the message hash (requires pytoniq_core) # from pytoniq_core.boc import Cell # msg_hash = Cell.one_from_boc(result['boc']).hash.hex() # print('Explorer:', f'https://toncenter.com/api/v3/transactionsByMessage?direction=out&msg_hash={msg_hash}') except UserRejectsError: print('User rejected the transaction.') except WalletNotConnectedError: print('No wallet connected.') except Exception as e: print('Unexpected error:', e) asyncio.run(main()) ``` -------------------------------- ### TonConnect.send_transaction Source: https://context7.com/xabbl4/pytonconnect/llms.txt Requests the connected wallet to sign and send a transaction. It accepts a transaction object and returns the signed BoC. Handles errors like `WalletNotConnectedError`, `UserRejectsError`, and `WalletNotSupportFeatureError`. ```APIDOC ## `TonConnect.send_transaction` — Request a Transaction Asks the connected wallet to sign and send a transaction. Returns a dict containing the signed BoC (`boc`). Raises `WalletNotConnectedError` if no wallet is connected, `UserRejectsError` if the user declines, or `WalletNotSupportFeatureError` if the wallet cannot handle the number of messages. ```python import asyncio from datetime import datetime from pytonconnect import TonConnect from pytonconnect.exceptions import UserRejectsError, WalletNotConnectedError from pytonconnect.parsers import TransactionMessage async def main(): connector = TonConnect( manifest_url='https://myapp.example.com/tonconnect-manifest.json' ) await connector.restore_connection() # Transaction using plain dicts transaction = { 'valid_until': int(datetime.now().timestamp()) + 900, # 15 min TTL 'messages': [ { 'address': '0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', 'amount': '50000000', # 0.05 TON in nanotons 'payload': 'base64_encoded_cell_payload', # optional 'stateInit': 'base64_encoded_state_init', # optional } ] } # Alternatively, use the TransactionMessage dataclass msg = TransactionMessage( address='0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', amount=50000000, payload='base64_encoded_cell_payload', ) transaction_typed = { 'valid_until': int(datetime.now().timestamp()) + 900, 'messages': [msg], } try: result = await connector.send_transaction(transaction) print('Transaction sent. BoC:', result['boc']) # Decode the BoC to get the message hash (requires pytoniq_core) # from pytoniq_core.boc import Cell # msg_hash = Cell.one_from_boc(result['boc']).hash.hex() # print('Explorer:', f'https://toncenter.com/api/v3/transactionsByMessage?direction=out&msg_hash={msg_hash}') except UserRejectsError: print('User rejected the transaction.') except WalletNotConnectedError: print('No wallet connected.') except Exception as e: print('Unexpected error:', e) asyncio.run(main()) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.