Ton Python SDK

Haftkhan BotHaftkhan Bot
10 min read

You're right to ask! The TON (The Open Network) blockchain is still relatively young, so the ecosystem of SDKs isn't as mature as, say, Ethereum. However, there are some solid options available for Python developers looking to interact with the TON blockchain. Here's a breakdown:

Primary and Most Popular Options:

  1. ton-py (by Disintar Team):

    • Status: This is generally considered the most complete and widely adopted Python SDK for TON. It's actively maintained and has broad functionality.

    • Features:

      • High-Level API: Provides an easy-to-use interface for common operations like sending transactions, reading contract data, deploying contracts, interacting with wallets, etc.

      • Support for Pyton3.7+: Compatible with Python 3.7 and above.

      • BOC (Bag of Cells) Manipulation: Allows you to work with the raw data structures on the TON blockchain.

      • Fift and FunC Support: Can be used with Fift and FunC for smart contract development.

      • Local Node Interaction: Includes capabilities to interact with a local TON node.

      • TON API Interaction: Functions to interact with the TON API if you're using a remote access method to the blockchain.

    • Installation: pip install ton-py

    • Example (Simple Transaction):

        from tonpy import TonClient, TonWallet
      
        # Assuming you have a private key stored in "private_key.txt"
        with open("private_key.txt", "r") as f:
            private_key = f.read().strip()
      
        # Create a wallet instance
        wallet = TonWallet.from_private_key(private_key)
      
        # Create a TON client
        client = TonClient()  # You might need to specify a node URL
      
        # Recipient address
        to_address = "EQCjV0H0F82H8jB_..."
      
        # Send some tokens
        tx_hash = wallet.send_ton(client, to_address, 1.0, "This is a test transfer")
      
        print(f"Transaction Hash: {tx_hash}")
      
    • Documentation: https://github.com/Disintar/ton-py (Check the README)

  2. pytonlib (by tonlib):

    • Status: This is a more low-level library focused on providing access to the TON client core.

    • Features:

      • Direct Access to TON Client Core: Wraps the C++ TON client for very direct and performant access.

      • Low-Level Operations: Suitable for tasks that require very fine-grained control over the TON blockchain.

      • RPC Interaction: Useful for interacting with nodes via the TON RPC.

      • Less Abstraction: Provides less high-level abstraction compared to ton-py, requiring a deeper understanding of TON specifics.

    • Installation: pip install pytonlib

    • Use Cases: Typically suited for projects requiring advanced control or building other SDKs.

    • Documentation: https://github.com/tonlib/pytonlib (Check the README)

Other Related Libraries (Less Direct, but Can Be Helpful):

  • Libraries for Specific Use Cases: There might be smaller Python libraries that cater to specific use cases within the TON ecosystem (e.g., libraries to interact with a specific DEX on TON). You'll need to search and check the documentation for their specific functionality.

  • Libraries with Third-Party Integrations: Some third-party services might offer Python libraries as part of their offering. For example, some node providers might have a python package to interact with their node. You'd need to check the individual service's documentation for those.

Key Considerations When Choosing:

  • Your Needs:

    • High-Level vs. Low-Level: Do you need a simple, high-level approach for common tasks (ton-py), or do you need direct access for advanced operations (pytonlib)?

    • Specific Use Cases: Does your project involve a specific aspect of TON, like smart contract development, or node interaction?

    • Learning Curve: Are you looking for an easy-to-learn SDK or willing to dive deeper into the technical aspects of TON?

  • Maturity and Maintenance: ton-py is often the safest bet due to its stability and strong community. pytonlib is also well maintained, though it's for more advanced use.

  • Documentation: Check the documentation for clarity and completeness.

  • Community: Look for active communities on GitHub and Telegram that can provide help and support.

Getting Started:

  1. Install your chosen SDK: pip install ...

  2. Set up your environment: You will probably need to have access to a TON node (you can run one yourself or use a service) and a TON wallet.

  3. Explore the documentation: Refer to the library's official documentation for examples and best practices.

  4. Experiment with simple actions: Start with basic operations like sending transactions or checking wallet balances.

Recommendation:

For most use cases, start with ton-py. It offers a great balance of ease-of-use and functionality. If you need more direct control, or are doing some work around the core of ton, pytonlib might be a better choice.

Okay, let's dive deeper into the capabilities of ton-py and pytonlib, providing module overviews, use cases, and code examples to help you understand their features.

1. ton-py (Disintar Team)

  • Core Principle: Aims to provide a user-friendly, high-level interface for interacting with the TON blockchain. It handles a lot of the complexity under the hood, allowing developers to focus on their application logic.

  • High-Level Module Overview:

    • tonpy (Main Module):

      • TonClient: Handles connections to the TON network (usually an RPC endpoint of a node).

        • Submodules (or Key Methods):

          • __init__(url, api_key=None, ...): Constructor, setting the URL for the node and optional API key

          • get_masterchain_seqno(): Fetches the latest masterchain sequence number.

          • get_account_state(address): Retrieves the state of an account.

          • send_boc(boc): Sends a BOC (Bag of Cells, serialized data) to the network.

          • run_get_method(address, method, stack): Executes a contract get method with given stack.

      • TonWallet: Represents a TON wallet and handles signing transactions.

        • Submodules (or Key Methods):

          • __init__(private_key): Constructor using a private key.

          • from_mnemonic(mnemonic): Creates a wallet from a mnemonic.

          • get_address(): Returns the wallet's address.

          • send_ton(ton_client, to_address, amount, comment): Sends TON tokens to another address.

          • create_transfer_message(to_address, amount, comment): Creates raw transfer message.

          • deploy_contract(ton_client, contract_code, contract_data, initial_storage): Deploys a smart contract.

      • Contract: Represents a TON contract (a smart contract deployed to the blockchain).

        • Submodules (or Key Methods):

          • __init__(address, ton_client): Constructor using the address and a ton client

          • get_method(method_name, stack): Runs contract's get method.

          • send_message(ton_client,function_name, stack, value): Executes a contract's function with a given stack.

      • Boc: For working with Bag of Cells (BOC) encoded data.

        • Submodules (or Key Methods):

          • from_base64(base64_string): Creates BOC instance from a base64 string.

          • serialize(): Serializes BOC instance to base64 string.

      • lite_client: For interacting with a Ton Lite Client.

        • Submodules (or Key Methods):

          • __init__(config, api_key): Creates the lite client instance.

          • send_boc(boc): Send boc data.

          • get_account_state(address): Get an account state.

          • run_get_method(address, method_name, stack): Get method of a contract.

      • utils

        • Submodules (or Key Methods):

          • address_from_raw(raw_address): Get formatted address from raw address.
    • types: Various data type definitions and enums specific to the TON blockchain.

      • Example: Address, Message, InternalMessage, ExternalMessage.
    • fift & func: Modules for interacting with Fift and FunC (TON's low-level contract languages).

  • Basic Use Cases and Code Examples:

    1. Checking Account Balance:

      ```python from tonpy import TonClient, TonWallet, utils

      Ton Client to interact with

      client = TonClient() # You might need to specify a node URL

Get private key from file

with open("private_key.txt", "r") as f: private_key = f.read().strip()

Create a wallet from the private key

wallet = TonWallet.from_private_key(private_key)

Fetch wallet state

state = client.get_account_state(wallet.get_address())

Get wallet balance

balance = state['balance'] / 10**9

print(f"Wallet address: {utils.address_from_raw(wallet.get_address())}") print(f"Wallet Balance: {balance} TON")


    2. **Sending a Transaction:**

        ```python
        from tonpy import TonClient, TonWallet

        # Ton Client to interact with
        client = TonClient()  # You might need to specify a node URL

        # Get private key from file
        with open("private_key.txt", "r") as f:
          private_key = f.read().strip()

        # Create a wallet from the private key
        wallet = TonWallet.from_private_key(private_key)

        # recipient address
        to_address = "EQCjV0H0F82H8jB_..."

        # send some TON
        tx_hash = wallet.send_ton(client, to_address, 0.1, "Test transfer")
        print(f"Transaction Hash: {tx_hash}")
  1. Interacting with a smart contract

      from tonpy import TonClient, Contract
    
     # ton client to interact with
      client = TonClient()  # You might need to specify a node URL
    
     # target contract address
      contract_address = 'EQCjV0H0F82H8jB_...'
    
      # creating a contract instance
      contract = Contract(contract_address, client)
    
      # running a get method and fetching result
      result = contract.get_method("getCounter", [])
      print(f"getCounter result: {result}")
    
      # send message to contract
      tx_hash = contract.send_message(client, "increment", [], 0.01)
      print(f"Transaction Hash: {tx_hash}")
    
  • Developer Introduction: ton-py is great for developers who want a clean and straightforward approach to interacting with the TON blockchain. You can quickly send transactions, deploy contracts, and retrieve data without being bogged down in low-level details.

2. pytonlib (tonlib)

  • Core Principle: This SDK is much closer to the metal. It provides a direct Python interface to the TON client's C++ core. It's more powerful but requires a deeper understanding of TON internals.

  • High-Level Module Overview:

    • pytonlib (Main Module):

      • LiteClient: Interacts with the TON lite client.

        • Key Methods:

          • __init__(config_path, liteserver, ...) : Constructor, requires configuration files.

          • get_account_state(address): Fetches account state.

          • send_boc(boc): Sends a raw BOC transaction.

          • run_get_method(address, method_name, stack): Executes contract get methods.

          • get_masterchain_info(): Fetches masterchain information.

      • Config: Handles configuration data for LiteClient.

        • Key Methods:

          • from_url(url): Creates config from a url

          • load_from_file(filename): Creates config from a file

      • Key: For generating and working with key pairs.

        • Key Methods:

          • generate(): Generates a new keypair
      • BOC: Creates a BOC instance from a given data.

        • Key Methods:

          • from_base64(boc_base64_str): Creates boc instance from base64 string.
      • Transaction: Handles the creation of transaction objects.

        • Key Methods:

          • create(message): Creates a transaction instance.
      • Message: Creates message data with proper types.

        • Key Methods:

          • create_internal(to_address, amount, boc_body): Creates internal message instance.
    • Submodules: The library often makes use of various helper submodules for handling serialization, deserialization, and different data types.

  • Basic Use Cases and Code Examples:

    1. Checking Account Balance (with pytonlib):

      ```python from pytonlib.client import LiteClient, Config from pytonlib.utils import address_from_raw

      Assuming you have a config.json file for a lite-client

      or fetch it by using config_url = "https://ton-blockchain.github.io/global.config.json" and call Config.from_url(config_url)

      config = Config.load_from_file("config.json") liteserver = ["127.0.0.1:12345"]

      create a lite client instance

      client = LiteClient(config, liteserver)

      Target account address

      accountaddress = "EQCjV0H0F82H8jB..."

Get account state

state = client.get_account_state(account_address)

Extract balance

balance = state['balance'] / 10**9

print(f"Account address: {address_from_raw(account_address)}") print(f"Account Balance: {balance} TON")


    2. **Sending a Transaction (Simplified):**


    ````python
      from pytonlib.client import LiteClient, Config
      from pytonlib.types import Transaction
      from pytonlib.boc import BOC
      from pytonlib.message import Message
      from pytonlib.key import Key
      import base64
     # Assuming you have a config.json file for a lite-client
      # or fetch it by using config_url = "https://ton-blockchain.github.io/global.config.json" and call Config.from_url(config_url)
      config = Config.load_from_file("config.json")
      liteserver = ["127.0.0.1:12345"]
      # create a lite client instance
      client = LiteClient(config, liteserver)

      # Target recipient address
      to_address = "EQCjV0H0F82H8jB_..."

      # Generate keys and get the public one.
      key_pair = Key.generate()
      public_key = base64.b64encode(key_pair.public).decode()
      secret_key = base64.b64encode(key_pair.secret).decode()

      # Create boc for body of the message
      # example is empty message body
      body = BOC.from_base64("te6ccgEBAQEAAgA=")

      # creating a message
      message = Message.create_internal(to_address, 100000000, body)

      # sign the message with the private key and create a transaction
      transaction = Transaction.create(message)
      signature = transaction.sign(key_pair.secret)

      # Attach the signature to the message
      transaction.attach_signature(signature)

      # Send it
      tx = client.send_boc(transaction.to_boc())
      print(tx)
  1. Interacting with a Smart contract

    from pytonlib.client import LiteClient, Config
    
    # Assuming you have a config.json file for a lite-client
    # or fetch it by using config_url = "https://ton-blockchain.github.io/global.config.json" and call Config.from_url(config_url)
    config = Config.load_from_file("config.json")
    liteserver = ["127.0.0.1:12345"]
    # create a lite client instance
    client = LiteClient(config, liteserver)
    
    # Target account address
    contract_address = "EQCjV0H0F82H8jB_..."
    
    # running get method
    result = client.run_get_method(contract_address, "getCounter", [])
    print(f"getCounter result: {result}")
    `
    
  • Developer Introduction: pytonlib is designed for developers who need maximum control and performance. It's suitable for building custom clients, advanced tooling, and core infrastructure within the TON ecosystem. However, the learning curve is steeper due to the need to work more closely with the underlying TON protocol.

Summary Table:

Featureton-pypytonlib
Abstraction LevelHigh-level, user-friendly APILow-level, direct access to TON client
Ease of UseEasier to learn and use, simpler APISteeper learning curve, more complex API
PerformanceGood for most typical applicationsVery high performance, direct access to core
FlexibilitySufficient for most common tasksMaximum flexibility, full control
Use CasesBuilding applications, basic tools, prototypingBuilding clients, core tooling, advanced apps
Key ModulesTonClient, TonWallet, Contract,BocLiteClient, Config,BOC, Transaction

Key Takeaways:

  • Start with ton-py: If you are new to TON or need to develop a common application, it's the ideal choice.

  • Use pytonlib for advanced work: If you require direct control, or have some specific needs around the core of ton, then pytonlib would be a good fit.

  • Always refer to official documentation: This explanation is a good starting point, but for specific methods and options, you should always consult the respective documentation for the chosen library.

  • TON is evolving rapidly: Stay up-to-date with the latest changes in the ecosystem and these libraries.

0
Subscribe to my newsletter

Read articles from Haftkhan Bot directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Haftkhan Bot
Haftkhan Bot

Full Stack Blockchain Dev Affiliated with https://www.linkedin.com/in/mbaneshi/