### GET /get_config_param Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves a specific blockchain configuration parameter by ID. ```APIDOC ## GET /get_config_param ### Description Retrieves a specific blockchain configuration parameter by its ID, optionally at a specific block seqno. ### Method GET ### Parameters #### Query Parameters - **config_id** (integer) - Required - The configuration parameter ID. - **seqno** (integer) - Optional - The block seqno for historical data. ``` -------------------------------- ### Initialize TonlibClient Source: https://context7.com/toncenter/pytonlib/llms.txt Demonstrates how to instantiate and initialize the TonlibClient using a network configuration and keystore directory. This setup is required before performing any blockchain operations. ```python import requests import asyncio from pathlib import Path from pytonlib import TonlibClient async def main(): ton_config = requests.get('https://ton.org/global.config.json').json() keystore_dir = '/tmp/ton_keystore' Path(keystore_dir).mkdir(parents=True, exist_ok=True) client = TonlibClient( ls_index=0, config=ton_config, keystore=keystore_dir, verbosity_level=0, tonlib_timeout=10 ) await client.init() masterchain_info = await client.get_masterchain_info() print(f"Latest block seqno: {masterchain_info['last']['seqno']}") await client.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### GET /get_masterchain_info Source: https://github.com/toncenter/pytonlib/blob/main/README.md Retrieves the current state and sequence number of the masterchain. ```APIDOC ## GET /get_masterchain_info ### Description Fetches the latest information about the masterchain, including the last block details. ### Method GET ### Endpoint client.get_masterchain_info() ### Response #### Success Response (200) - **last** (object) - Contains the seqno and root hash of the last masterchain block. #### Response Example { "last": { "workchain": -1, "shard": -9223372036854775808, "seqno": 34567890 } } ``` -------------------------------- ### Execute Async Script Source: https://github.com/toncenter/pytonlib/blob/main/README.md Provides a complete template for running an asynchronous script using the TonlibClient, including setup and graceful shutdown. ```python import asyncio from pytonlib import TonlibClient async def main(): client = TonlibClient(ls_index=0, config=ton_config, keystore=keystore_dir) await client.init() masterchain_info = await client.get_masterchain_info() await client.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Retrieve Raw Transactions for an Account Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves historical raw transactions for a specific account address starting from a known transaction ID. It requires the account address and the logical time (lt) and hash of the starting transaction. ```python from pytonlib.utils.common import b64str_to_hex address = 'EQBvW8Z5huBkMJYdnfAEM5JqTNkuWX3diqYENkWsIL0XggGG' # First get the account state to find last transaction account_state = await client.raw_get_account_state(address) last_tx = account_state['last_transaction_id'] # Get raw transactions (hash must be in hex format) raw_txs = await client.raw_get_transactions( account_address=address, from_transaction_lt=last_tx['lt'], from_transaction_hash=b64str_to_hex(last_tx['hash']) ) print(f"Found {len(raw_txs['transactions'])} transactions") print(f"Previous TX ID: {raw_txs.get('previous_transaction_id')}") ``` -------------------------------- ### Detect and Prepare TON Addresses with PyTONLib Source: https://context7.com/toncenter/pytonlib/llms.txt Demonstrates how to use detect_address to get various formats of a TON address and prepare_address to format it for API calls. It handles both raw and friendly address inputs. ```python from pytonlib.utils.common import detect_address, prepare_address # Assuming raw_address and friendly_address are defined elsewhere # Example usage: # raw_address = "0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef12345678" # friendly_address = "EQCDabcdef1234567890abcdef1234567890abcdef1234567890abcdef12345678" addr_info = detect_address(raw_address) print(f"Raw form: {addr_info['raw_form']}") print(f"Bounceable: {addr_info['bounceable']['b64']}") print(f"Bounceable URL-safe: {addr_info['bounceable']['b64url']}") print(f"Non-bounceable: {addr_info['non_bounceable']['b64']}") print(f"Non-bounceable URL-safe: {addr_info['non_bounceable']['b64url']}") print(f"Test only: {addr_info['test_only']}") addr_info = detect_address(friendly_address) prepared = prepare_address(raw_address) print(f"Prepared for API: {prepared}") ``` -------------------------------- ### Get Block Header Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves the header for a specific masterchain block. ```APIDOC ## Get Block Header ### Description Fetches the block header for a given masterchain block, identified by its sequence number and hash. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Assuming masterchain_info is already fetched and contains 'last' block_header = await client.get_block_header(**masterchain_info['last']) block_header ``` ### Response #### Success Response (200) - **block_header** (dict) - Dictionary containing the block header information. #### Response Example ```json { "global_id": 1, "shard": 0, "seqno": 1234567, "root_hash": "...", "file_hash": "...", "слей_hash": "...", "gen_utime": 1678886400, "gen_lt": 1234567890, "ப்படுத்த_hash": "..." } ``` ``` -------------------------------- ### GET /try_locate_tx_by_incoming_message Source: https://context7.com/toncenter/pytonlib/llms.txt Locates a transaction by searching for an incoming message. ```APIDOC ## GET /try_locate_tx_by_incoming_message ### Description Locates a transaction by searching for an incoming message based on source, destination, and creation logical time. ### Method GET ### Parameters #### Query Parameters - **source** (string) - Required - Source address. - **destination** (string) - Required - Destination address. - **creation_lt** (integer) - Required - Creation logical time. ``` -------------------------------- ### Raw Get Account State Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves the raw state of an account given its address. ```APIDOC ## Raw Get Account State ### Description Fetches the raw state of a TON account directly from the blockchain using its address. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python address = '0:C4CAC12F5BC7EEF4CF5EC84EE68CCF860921A06CA0395EC558E53E37B13C3B08' account_state = await client.raw_get_account_state(address) account_state ``` ### Response #### Success Response (200) - **account_state** (dict) - Dictionary containing the raw state of the account. #### Response Example ```json { "balance": 1000000000, "code": "...", "data": "...", "last_transaction_id": { "lt": "...", "hash": "..." }, "frozen_hash": "..." } ``` ``` -------------------------------- ### GET /get_jetton_wallet_address Source: https://context7.com/toncenter/pytonlib/llms.txt Calculates the Jetton wallet address for a given owner address from a Jetton master contract. ```APIDOC ## GET /get_jetton_wallet_address ### Description Calculates the specific Jetton wallet address for a given owner address based on a Jetton master contract address. ### Method GET ### Parameters #### Query Parameters - **owner_address** (string) - Required - The owner's wallet address. - **jetton_address** (string) - Required - The Jetton master contract address. ### Response #### Success Response (200) - **wallet_address** (string) - The calculated Jetton wallet address. ``` -------------------------------- ### GET /raw_get_account_state Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the raw state of an account, including balance, code, and last transaction details. ```APIDOC ## GET /raw_get_account_state ### Description Fetches the current or historical state of a specific account address. ### Method GET ### Endpoint /raw_get_account_state ### Parameters #### Query Parameters - **address** (string) - Required - Account address - **seqno** (integer) - Optional - Historical masterchain seqno ### Response #### Success Response (200) - **balance** (integer) - Account balance in nanoTON - **last_transaction_id** (object) - Last transaction metadata - **sync_utime** (integer) - Synchronization time ### Response Example { "balance": 1000000000, "last_transaction_id": {"lt": 123, "hash": "abc"}, "sync_utime": 1699900000 } ``` -------------------------------- ### Get Masterchain Info Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Fetches the latest masterchain information, including the last block sequence number. ```APIDOC ## Get Masterchain Info ### Description Retrieves the current masterchain information, which includes details about the latest block. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python masterchain_info = await client.get_masterchain_info() masterchain_info ``` ### Response #### Success Response (200) - **masterchain_info** (dict) - Dictionary containing masterchain details, including 'last' block information. #### Response Example ```json { "last": { "seqno": 1234567, "root_hash": "...", "file_hash": "..." }, "last_uts": 1678886400 } ``` ``` -------------------------------- ### Get Transactions Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves detailed transaction information based on transaction ID and other parameters. ```APIDOC ## Get Transactions ### Description Fetches detailed information for a specific transaction using its ID and other relevant block details, with a limit on the number of results. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Assuming 'tx' is a transaction dictionary obtained from get_block_transactions # Example: await client.get_transactions(**tx, limit=1) ``` ### Response #### Success Response (200) - **transactions** (list) - A list containing detailed transaction information. #### Response Example ```json [ { "id": "...", "utime": 1678886400, "data": "...", "action": null, "compute": null, "storage": null, "bounce": false, "split_info": null, "aborted": false, "destroyed": false, "credit": null, "destroy": null } ] ``` ``` -------------------------------- ### GET /get_block_transactions Source: https://github.com/toncenter/pytonlib/blob/main/README.md Retrieves a list of transactions for a specific block in the masterchain. ```APIDOC ## GET /get_block_transactions ### Description Retrieves transactions associated with a specific block identified by workchain, shard, and seqno. ### Method GET ### Endpoint client.get_block_transactions(workchain, shard, seqno, count) ### Parameters #### Query Parameters - **workchain** (int) - Required - The workchain ID. - **shard** (int) - Required - The shard ID. - **seqno** (int) - Required - The block sequence number. - **count** (int) - Optional - Number of transactions to retrieve. ### Response #### Success Response (200) - **transactions** (array) - List of transaction objects. #### Response Example { "transactions": [ { "hash": "...", "lt": 123456789 } ] } ``` -------------------------------- ### Get Account State Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Fetches the current state of a TON account given its address. This includes information like the account's balance, code, and data. ```python address = '0:C4CAC12F5BC7EEF4CF5EC84EE68CCF860921A06CA0395EC558E53E37B13C3B08' await client.raw_get_account_state(address) ``` -------------------------------- ### Get Shards Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves the shards associated with a specific masterchain block sequence number. ```APIDOC ## Get Shards ### Description Fetches the list of shards for a given masterchain block sequence number. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Assuming masterchain_info is already fetched and contains 'last' shards = await client.get_shards(master_seqno=masterchain_info['last']['seqno']) shards ``` ### Response #### Success Response (200) - **shards** (list) - A list of shard information dictionaries. #### Response Example ```json [ { "workchain_id": 0, "shard_id": "...", "seqno": 1234567, "root_hash": "...", "file_hash": "..." } ] ``` ``` -------------------------------- ### GET /get_nft_item_address Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the NFT item address by index from an NFT collection contract. ```APIDOC ## GET /get_nft_item_address ### Description Gets the unique NFT item address by its index from an NFT collection contract. ### Method GET ### Parameters #### Query Parameters - **collection_address** (string) - Required - The NFT collection contract address. - **item_index** (integer) - Required - The index of the NFT item. ### Response #### Success Response (200) - **nft_address** (string) - The address of the NFT item. ``` -------------------------------- ### raw_get_transactions Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves raw transaction history for a specific account starting from a given transaction ID. ```APIDOC ## GET /raw_get_transactions ### Description Retrieves raw transactions for an account starting from a specific transaction ID (logical time and hash). ### Method GET ### Parameters #### Query Parameters - **account_address** (string) - Required - The TON address of the account. - **from_transaction_lt** (integer) - Required - The logical time of the starting transaction. - **from_transaction_hash** (string) - Required - The hex-encoded hash of the starting transaction. ### Response #### Success Response (200) - **transactions** (array) - List of transaction objects. - **previous_transaction_id** (object) - ID of the previous transaction for pagination. ``` -------------------------------- ### GET /get_block_header Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the header information for a specific block, including timestamps and validator metadata. ```APIDOC ## GET /get_block_header ### Description Retrieves the header information for a specific block including timestamps, validator info, and block metadata. ### Method GET ### Endpoint /get_block_header ### Parameters #### Query Parameters - **workchain** (integer) - Required - The workchain ID - **shard** (integer) - Required - The shard ID - **seqno** (integer) - Required - The block sequence number - **root_hash** (string) - Required - The root hash of the block - **file_hash** (string) - Required - The file hash of the block ### Request Example await client.get_block_header(workchain=-1, shard=..., seqno=12345678, root_hash="...", file_hash="...") ### Response #### Success Response (200) - **gen_utime** (integer) - Block generation time - **start_lt** (integer) - Start logical time - **end_lt** (integer) - End logical time #### Response Example { "gen_utime": 1672531200, "start_lt": 1000, "end_lt": 2000 } ``` -------------------------------- ### GET /get_shards Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves shard information for a specific masterchain sequence number, logical time, or unix timestamp. ```APIDOC ## GET /get_shards ### Description Retrieves the shard configuration for a given block context. ### Method GET ### Endpoint /get_shards ### Parameters #### Query Parameters - **master_seqno** (integer) - Optional - Masterchain sequence number - **lt** (integer) - Optional - Logical time - **unixtime** (integer) - Optional - Unix timestamp ### Response #### Success Response (200) - **shards** (array) - List of shard objects containing workchain, shard, and seqno. ### Response Example { "shards": [{"workchain": 0, "shard": -9223372036854775808, "seqno": 12345}] } ``` -------------------------------- ### GET /lookup_block Source: https://context7.com/toncenter/pytonlib/llms.txt Looks up a specific block identifier using workchain, shard, and one of: sequence number, logical time, or unix time. ```APIDOC ## GET /lookup_block ### Description Resolves a block identifier based on provided temporal or sequence parameters. ### Method GET ### Endpoint /lookup_block ### Parameters #### Query Parameters - **workchain** (integer) - Required - Workchain ID - **shard** (integer) - Required - Shard ID - **seqno** (integer) - Optional - Sequence number - **lt** (integer) - Optional - Logical time - **unixtime** (integer) - Optional - Unix timestamp ### Response #### Success Response (200) - **seqno** (integer) - Block sequence number - **root_hash** (string) - Block root hash ### Response Example { "seqno": 12345678, "root_hash": "abc123..." } ``` -------------------------------- ### Get Block Transactions Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves transactions from a specific shard block, with an option to limit the number of transactions. ```APIDOC ## Get Block Transactions ### Description Retrieves a list of transactions from a specified block, with an option to limit the number of results and check for completeness. ### Method N/A (Client method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Assuming masterchain_info is already fetched and contains 'last' txs = await client.get_block_transactions(**masterchain_info['last'], count=10) print('Is incomplete:', txs['incomplete']) print('Num txs:', len(txs['transactions'])) tx = txs['transactions'][0] # Example: get the first transaction tx ``` ### Response #### Success Response (200) - **txs** (dict) - Dictionary containing transaction details, including 'incomplete' status and a list of 'transactions'. #### Response Example ```json { "incomplete": false, "transactions": [ { "id": "...", "utime": 1678886400, "data": "...", "action": null, "compute": null, "storage": null, "bounce": false, "split_info": null, "aborted": false, "destroyed": false, "credit": null, "destroy": null } ] } ``` ``` -------------------------------- ### Get Masterchain Information Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves the latest masterchain information, including the last block's sequence number and state. This is a fundamental step for querying subsequent blockchain data. ```python masterchain_info = await client.get_masterchain_info() masterchain_info ``` -------------------------------- ### Get Masterchain Block Header Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Fetches the block header for a specific masterchain block, identified by its sequence number. This provides metadata about the block. ```python block_header = await client.get_block_header(**masterchain_info['last']) block_header ``` -------------------------------- ### Get Masterchain Shards Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves a list of shards associated with a given masterchain block sequence number. This is crucial for understanding the TON network's sharded architecture. ```python shards = await client.get_shards(master_seqno=masterchain_info['last']['seqno']) shards ``` -------------------------------- ### Get Specific Transaction Details Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Retrieves detailed information for a specific transaction, identified by its unique hash and other relevant block identifiers. Useful for inspecting individual transaction data. ```python tx = txs['transactions'][0] await client.get_transactions(**tx, limit=1) ``` -------------------------------- ### Initialize TonlibClient Source: https://github.com/toncenter/pytonlib/blob/main/README.md Demonstrates how to download the global TON configuration, set up a local keystore, and initialize the TonlibClient instance. ```python import requests import asyncio from pathlib import Path from pytonlib import TonlibClient ton_config = requests.get('https://ton.org/global.config.json').json() keystore_dir = '/tmp/ton_keystore' Path(keystore_dir).mkdir(parents=True, exist_ok=True) client = TonlibClient(ls_index=0, config=ton_config, keystore=keystore_dir) await client.init() ``` -------------------------------- ### Initialize TonlibClient Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb This snippet shows how to set up the TonlibClient by configuring connection parameters and initializing the client. ```APIDOC ## Initialize TonlibClient ### Description Initializes the TonlibClient with a specific LiteServer configuration and keystore path. ### Method N/A (Initialization) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import sys import os os.makedirs('/tmp/ton_keystore', exist_ok=True) sys.path.insert(0, '/app') import logging import requests import asyncio from pytonlib import TonlibClient logging.basicConfig(format='%(asctime)s %(module)-15s %(message)s', level=logging.INFO) ton_config_url = 'https://ton.org/global.config.json' ton_config = requests.get(ton_config_url).json() loop = asyncio.get_running_loop() client = TonlibClient(ls_index=1, # choose LiteServer to connect config=ton_config, keystore='/tmp/ton_keystore', loop=loop) await client.init() ``` ### Response #### Success Response (200) N/A (Initialization) #### Response Example N/A ``` -------------------------------- ### Initialize Pytonlib TonlibClient Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Sets up the TonlibClient for interacting with the TON network. It configures logging, fetches network configuration, and initializes the client with a specific LiteServer. Requires the 'requests' and 'asyncio' libraries. ```python import sys import os os.makedirs('/tmp/ton_keystore', exist_ok=True) sys.path.insert(0, '/app') import logging import requests import asyncio from pytonlib import TonlibClient logging.basicConfig(format='%(asctime)s %(module)-15s %(message)s', level=logging.INFO) ton_config_url = 'https://ton.org/global.config.json' ton_config = requests.get(ton_config_url).json() loop = asyncio.get_running_loop() client = TonlibClient(ls_index=1, # choose LiteServer to connect config=ton_config, keystore='/tmp/ton_keystore', loop=loop) await client.init() ``` -------------------------------- ### Deploy Service with Docker Source: https://github.com/toncenter/pytonlib/blob/main/README.md Commands to build and run the service using Docker Compose for development environments. ```bash docker-compose -f docker-compose.jupyter.yaml build docker-compose -f docker-compose.jupyter.yaml up -d ``` -------------------------------- ### Manage TonlibClient with Context Manager Source: https://context7.com/toncenter/pytonlib/llms.txt Shows the usage of the async context manager to handle TonlibClient initialization and cleanup automatically. This approach is recommended to ensure connections are closed properly. ```python import requests import asyncio from pathlib import Path from pytonlib import TonlibClient async def main(): ton_config = requests.get('https://ton.org/global.config.json').json() keystore_dir = '/tmp/ton_keystore' Path(keystore_dir).mkdir(parents=True, exist_ok=True) async with TonlibClient( ls_index=0, config=ton_config, keystore=keystore_dir ) as client: masterchain_info = await client.get_masterchain_info() print(f"Block seqno: {masterchain_info['last']['seqno']}") asyncio.run(main()) ``` -------------------------------- ### Create and Send Queries Source: https://context7.com/toncenter/pytonlib/llms.txt Combines the creation of a query and its submission to the network into a single operation. Supports both standard interactions and contract deployment. ```python destination = 'EQBvW8Z5huBkMJYdnfAEM5JqTNkuWX3diqYENkWsIL0XggGG' body = b'...' # Serialized message body # For sending to an existing contract result = await client.raw_create_and_send_query( destination=destination, body=body ) # For deploying a new contract result = await client.raw_create_and_send_query( destination=destination, body=body, init_code=b'...', # Contract code init_data=b'...' # Initial contract data ) ``` -------------------------------- ### Retrieve Blockchain Data Source: https://github.com/toncenter/pytonlib/blob/main/README.md Shows how to fetch masterchain information, block headers, and shard data using an initialized client. ```python masterchain_info = await client.get_masterchain_info() block_header = await client.get_block_header(**masterchain_info['last']) shards = await client.get_shards(master_seqno=masterchain_info['last']['seqno']) ``` -------------------------------- ### raw_run_method Source: https://context7.com/toncenter/pytonlib/llms.txt Executes a get-method on a smart contract to read its state without modifying the blockchain. ```APIDOC ## POST /raw_run_method ### Description Executes a get-method on a smart contract and returns the TVM stack result. ### Method POST ### Parameters #### Request Body - **address** (string) - Required - Smart contract address. - **method** (string/integer) - Required - Method name or ID number. - **stack_data** (array) - Optional - Arguments for the method. - **seqno** (integer) - Optional - Historical masterchain seqno. ### Response #### Success Response (200) - **exit_code** (integer) - 0 for success. - **gas_used** (integer) - Gas consumed. - **stack** (array) - Resulting stack data. ``` -------------------------------- ### TON Exception Handling with PyTONLib Source: https://context7.com/toncenter/pytonlib/llms.txt Illustrates how to handle various TON-specific exceptions using PyTONLib, including network errors, timeouts, and specific block-related issues, ensuring robust error management in blockchain applications. ```python from pytonlib import ( TonlibClient, TonlibException, TonlibNoResponse, TonlibError, LiteServerTimeout, BlockNotFound, BlockDeleted, ExternalMessageNotAccepted ) # Assuming 'client' is an initialized TonlibClient instance # async def safe_query(): # try: # result = await client.get_block_header(workchain=-1, shard=-9223372036854775808, seqno=99999999) # except BlockNotFound as e: # print(f"Block not found: {e}") # except BlockDeleted as e: # print(f"Block was deleted (GC'd): {e}") # except LiteServerTimeout as e: # print(f"LiteServer timeout: {e}") # except ExternalMessageNotAccepted as e: # print(f"Message rejected: {e}") # except TonlibNoResponse: # print("No response from tonlib") # except TonlibError as e: # print(f"Tonlib error (code {e.code}): {e}") # except TonlibException as e: # print(f"General tonlib exception: {e}") ``` -------------------------------- ### Retrieve Smart Contract Libraries Source: https://context7.com/toncenter/pytonlib/llms.txt Fetches library data by their hashes, which is required for smart contracts that depend on external library code. ```python library_hashes = ['base64_encoded_hash_1', 'base64_encoded_hash_2'] libraries = await client.get_libraries(library_list=library_hashes) for lib in libraries.get('result', []): print(f"Library hash: {lib['hash']}") ``` -------------------------------- ### Execute Smart Contract Get-Methods Source: https://context7.com/toncenter/pytonlib/llms.txt Executes a read-only get-method on a smart contract to retrieve state information without modifying the blockchain. Supports passing stack arguments and querying historical states. ```python # Execute a simple get method (e.g., seqno on a wallet) wallet_address = 'EQBvW8Z5huBkMJYdnfAEM5JqTNkuWX3diqYENkWsIL0XggGG' result = await client.raw_run_method( address=wallet_address, method='seqno', stack_data=[] # No arguments needed ) print(f"Exit code: {result['exit_code']}") # 0 = success print(f"Gas used: {result['gas_used']}") print(f"Stack result: {result['stack']}") # Execute a method with arguments (e.g., get_wallet_address on Jetton master) jetton_master = 'EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE' owner_address_cell = 'base64_encoded_slice...' result = await client.raw_run_method( address=jetton_master, method='get_wallet_address', stack_data=[['tvm.Slice', owner_address_cell]] ) # Method can be specified by name or number result = await client.raw_run_method( address=wallet_address, method=85143, # Method ID number stack_data=[] ) # Get historical state at specific seqno result = await client.raw_run_method( address=wallet_address, method='seqno', stack_data=[], seqno=12345678 # Masterchain seqno for historical query ) ``` -------------------------------- ### Fetch Blockchain Configuration Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves specific or all blockchain configuration parameters. Supports historical lookups by providing a sequence number. ```python config = await client.get_config_param(config_id=34) print(f"Validators config: {config}") historical_config = await client.get_config_param(config_id=34, seqno=12345678) all_config = await client.get_config_all() ``` -------------------------------- ### Retrieve Block Signatures and Proofs Source: https://context7.com/toncenter/pytonlib/llms.txt Fetches validator signatures for masterchain blocks and cryptographic proofs for shard blocks to ensure data integrity. ```python seqno = 12345678 signatures = await client.get_masterchain_block_signatures(seqno=seqno) proof = await client.get_shard_block_proof( workchain=0, shard=-9223372036854775808, seqno=23456789 ) ``` -------------------------------- ### Fetch Block Header Data Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves metadata for a specific block, such as timestamps and logical time (LT) values. It demonstrates how to pass block identifiers directly or via dictionary unpacking. ```python masterchain_info = await client.get_masterchain_info() block_header = await client.get_block_header(**masterchain_info['last']) print(f"Block time: {block_header['gen_utime']}") print(f"Start LT: {block_header['start_lt']}") print(f"End LT: {block_header['end_lt']}") ``` -------------------------------- ### get_token_data Source: https://context7.com/toncenter/pytonlib/llms.txt Detects and parses metadata for Jetton or NFT tokens. ```APIDOC ## GET /get_token_data ### Description Automatically detects token type and returns parsed metadata. ### Method GET ### Parameters #### Query Parameters - **address** (string) - Required - Token contract address. - **skip_verification** (boolean) - Optional - Skip master contract verification. ### Response #### Success Response (200) - **contract_type** (string) - Type of token (e.g., 'jetton_master', 'nft_item'). - **content** (object) - Parsed token metadata. ``` -------------------------------- ### Convert TON Address Formats Source: https://context7.com/toncenter/pytonlib/llms.txt Utility functions to detect and convert TON addresses between raw, bounceable, and non-bounceable formats. ```python from pytonlib.utils.address import detect_address, prepare_address raw_address = '0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef12345678' friendly_address = 'EQCrze8TEQSC8gFvHDJwLN1nOVNdM_H4yz7JHQngDc5fZfTx' ``` -------------------------------- ### Parse Token Metadata Source: https://context7.com/toncenter/pytonlib/llms.txt Automatically detects the type of token (Jetton or NFT) and parses its metadata. Provides a simplified interface for retrieving contract-specific information. ```python # Get Jetton master data jetton_master = 'EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE' token_data = await client.get_token_data(jetton_master) print(f"Contract type: {token_data['contract_type']}") # 'jetton_master' print(f"Total supply: {token_data['total_supply']}") print(f"Mintable: {token_data['mintable']}") print(f"Admin: {token_data['admin_address']}") print(f"Content: {token_data['jetton_content']}") # Get NFT item data nft_address = 'EQExample...' nft_data = await client.get_token_data(nft_address) print(f"Contract type: {nft_data['contract_type']}") # 'nft_item' print(f"Collection: {nft_data['collection_address']}") print(f"Owner: {nft_data['owner_address']}") print(f"Index: {nft_data['index']}") print(f"Content: {nft_data['content']}") # Skip verification with master contract (faster but less secure) token_data = await client.get_token_data(address, skip_verification=True) ``` -------------------------------- ### Retrieve Shard Information Source: https://context7.com/toncenter/pytonlib/llms.txt Fetches shard information for a given masterchain sequence number. This allows developers to map out the network structure at a specific point in time. ```python shards = await client.get_shards(master_seqno=masterchain_info['last']['seqno']) for shard in shards['shards']: print(f"Workchain: {shard['workchain']}, Shard: {shard['shard']}, Seqno: {shard['seqno']}") ``` -------------------------------- ### TON Blockchain Common Utilities with PyTONLib Source: https://context7.com/toncenter/pytonlib/llms.txt Provides essential utility functions for encoding and decoding TON data, including base64 to hex conversion, hex to base64, hash format detection, and raw to user-friendly address conversions. ```python from pytonlib.utils.common import ( b64str_to_hex, hex_to_b64str, hash_to_hex, raw_to_userfriendly, userfriendly_to_raw ) b64_hash = 'SGVsbG8gV29ybGQ=' hex_hash = b64str_to_hex(b64_hash) print(f"Hex: {hex_hash}") back_to_b64 = hex_to_b64str(hex_hash) print(f"Base64: {back_to_b64}") tx_hash = 'SGVsbG8gV29ybGQhISEhISEhISEhISEhISEhISEhISE=' hex_result = hash_to_hex(tx_hash) raw = '0:abcdef1234567890abcdef1234567890abcdef1234567890abcdef12345678' friendly = raw_to_userfriendly(raw, tag=0x11) # 0x11 = bounceable print(f"User-friendly: {friendly}") raw_back = userfriendly_to_raw(friendly) print(f"Raw: {raw_back}") ``` -------------------------------- ### Calculate Jetton Wallet Address Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the specific Jetton wallet address for a given owner from a Jetton master contract. This is a prerequisite for querying token balances. ```python owner_address = 'EQBvW8Z5huBkMJYdnfAEM5JqTNkuWX3diqYENkWsIL0XggGG' jetton_master = 'EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE' wallet_address = await client.get_jetton_wallet_address( owner_address=owner_address, jetton_address=jetton_master ) print(f"Jetton wallet: {wallet_address}") wallet_data = await client.get_token_data(wallet_address) print(f"Balance: {wallet_data['balance']}") ``` -------------------------------- ### Query Raw Account State Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the current or historical raw state of an account, including balance, code, data, and last transaction metadata. ```python account_state = await client.raw_get_account_state(address) historical_state = await client.raw_get_account_state(address, seqno=12345678) ``` -------------------------------- ### Trace Transactions by Message Source: https://context7.com/toncenter/pytonlib/llms.txt Locates a transaction by searching for incoming or outgoing messages using source, destination, and logical time (LT). ```python source = 'EQSourceAddress...' destination = 'EQDestinationAddress...' creation_lt = 28596838000001 try: tx = await client.try_locate_tx_by_incoming_message( source=source, destination=destination, creation_lt=creation_lt ) print(f"Found transaction: {tx['transaction_id']}") except Exception as e: print(f"Transaction not found: {e}") ``` -------------------------------- ### Estimate Transaction Fees Source: https://context7.com/toncenter/pytonlib/llms.txt Calculates the expected fees for a transaction without executing it. Useful for pre-flight checks on gas, storage, and forwarding costs. ```python destination = 'EQBvW8Z5huBkMJYdnfAEM5JqTNkuWX3diqYENkWsIL0XggGG' body = b'...' # Message body as bytes fees = await client.raw_estimate_fees( destination=destination, body=body, init_code=b'', # Contract init code (for deployment) init_data=b'', # Contract init data (for deployment) ignore_chksig=True # Ignore signature check ) print(f"Source fees: {fees['source_fees']}") print(f"Destination fees: {fees['destination_fees']}") ``` -------------------------------- ### Retrieve Block Transactions Source: https://context7.com/toncenter/pytonlib/llms.txt Fetches a list of transactions from a specific block, supporting pagination via logical time and transaction hashes. Useful for auditing block contents. ```python txs = await client.get_block_transactions(workchain=masterchain_info['last']['workchain'], shard=masterchain_info['last']['shard'], seqno=masterchain_info['last']['seqno'], count=100) if txs['incomplete']: last_tx = txs['transactions'][-1] more_txs = await client.get_block_transactions(**masterchain_info['last'], count=100, after_lt=last_tx['lt'], after_hash=last_tx['account']) ``` -------------------------------- ### Fetch Account Transaction History Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves an account's transaction history in reverse chronological order with support for automatic pagination and message decoding. ```python transactions = await client.get_transactions(account=address, limit=10, decode_messages=True) transactions = await client.get_transactions(account=address, from_transaction_lt='28596838000001', limit=50) ``` -------------------------------- ### Retrieve Masterchain Information Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves the current state of the masterchain, including the latest block sequence number and hashes. This is typically the first step in querying blockchain data. ```python masterchain_info = await client.get_masterchain_info() print(f"Latest seqno: {masterchain_info['last']['seqno']}") print(f"Workchain: {masterchain_info['last']['workchain']}") ``` -------------------------------- ### raw_estimate_fees Source: https://context7.com/toncenter/pytonlib/llms.txt Estimates the transaction fees for a message without executing it. ```APIDOC ## POST /raw_estimate_fees ### Description Calculates the estimated fees for sending a message. ### Method POST ### Parameters #### Request Body - **destination** (string) - Required - Target address. - **body** (bytes) - Required - Message body. - **init_code** (bytes) - Optional - Contract code for deployment. - **init_data** (bytes) - Optional - Initial data for deployment. ### Response #### Success Response (200) - **source_fees** (integer) - Fees charged to source. - **destination_fees** (integer) - Fees charged to destination. ``` -------------------------------- ### Retrieve NFT Item Address Source: https://context7.com/toncenter/pytonlib/llms.txt Fetches the address of an NFT item based on its index within an NFT collection contract. Useful for inspecting specific NFT metadata or ownership. ```python collection_address = 'EQExample...' item_index = 42 nft_address = await client.get_nft_item_address( collection_address=collection_address, item_index=item_index ) print(f"NFT item address: {nft_address}") nft_data = await client.get_token_data(nft_address) print(f"Owner: {nft_data['owner_address']}") ``` -------------------------------- ### Lookup Block Identifier Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves a full block identifier using various criteria such as sequence number, logical time, or unix timestamp. This is essential for navigating the blockchain history. ```python block_id = await client.lookup_block(workchain=-1, shard=-9223372036854775808, seqno=12345678) block_id = await client.lookup_block(workchain=0, shard=-9223372036854775808, lt=28596838000001) block_id = await client.lookup_block(workchain=-1, shard=-9223372036854775808, unixtime=1699900000) ``` -------------------------------- ### Read Transactions from Shard Block Source: https://github.com/toncenter/pytonlib/blob/main/examples/pytonlib-example.ipynb Reads a specified number of transactions from a given shard block. It indicates whether the result is complete or truncated and returns the count of transactions found. ```python txs = await client.get_block_transactions(**masterchain_info['last'], count=10) print('Is incomplete:', txs['incomplete']) print('Num txs:', len(txs['transactions'])) ``` -------------------------------- ### raw_send_message Source: https://context7.com/toncenter/pytonlib/llms.txt Submits a serialized external message (bag of cells) to the blockchain. ```APIDOC ## POST /raw_send_message ### Description Sends a serialized external message (bag of cells) to the blockchain. ### Method POST ### Parameters #### Request Body - **serialized_boc** (bytes) - Required - The signed message as a bag of cells. ### Response #### Success Response (200) - **@type** (string) - Status indicator (e.g., 'ok'). ``` -------------------------------- ### Send Messages to Blockchain Source: https://context7.com/toncenter/pytonlib/llms.txt Submits a serialized external message (bag of cells) to the network. Provides options to simply send the message or return the resulting transaction hash. ```python # serialized_boc should be a bytes object containing the signed message serialized_boc = b'...' # Your serialized bag of cells result = await client.raw_send_message(serialized_boc) # Returns {'@type': 'ok'} on success print(f"Message sent: {result}") # Alternative: send message and get the hash result = await client.raw_send_message_return_hash(serialized_boc) print(f"Message hash: {result['hash']}") ``` -------------------------------- ### Retrieve Extended Transaction Data Source: https://context7.com/toncenter/pytonlib/llms.txt Retrieves detailed transaction information including full message payloads and state changes for a specific block. ```python txs_ext = await client.get_block_transactions_ext(workchain=masterchain_info['last']['workchain'], shard=masterchain_info['last']['shard'], seqno=masterchain_info['last']['seqno'], count=10) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.