• Pricing
  • Enterprise
  • Customers
  • Blog

TON: Ultimate guide to APIs and interaction libraries

Blockchain technology continues to transform how DApps are built and operated, offering Web3 developers new tools to create secure and scalable solutions. The TON Network, with its focus on performance and reliability, is one such blockchain that has captured the attention of forward-thinking developers. Whether you’re an experienced Web3 developer or just starting with TON, leveraging the right tools and APIs can be crucial to building successful DApps.

In this guide, we will dive deep into the various interaction libraries and APIs available for the TON network, helping you understand how to integrate custom RPC nodes, use Chainstack infrastructure, and build with libraries like TonWeb, Ton.js, TonUtils, TonGo, Tonlib-rs, and more. This comprehensive guide will walk you through the process of setting up your environment, installing the necessary libraries, and interacting with the TON blockchain effectively.

Let’s explore how to unlock the full potential of the TON network and build next-generation DApps!

What types of TON APIs are there?

The world of blockchain technology is indeed fascinating and full of opportunities for developers. Specifically, for Web3 developers, understanding APIs and their critical role in blockchain interaction is pivotal. Among these, TON APIs stand out with their uniquely designed features and functionalities. For the TON Network, two APIs are predominantly used: TON HTTP API and TON ADNL API.

What is the TON HTTP API?

The TON HTTP API is your gateway to access indexed blockchain information efficiently. Think of it as a well-organized library where you can swiftly get the information you need without having to go through heaps of data.

What is the TON ADNL API?

A sharp contrast to the HTTP API, the TON ADNL API brings a secure communication channel for interacting with the TON network. It’s based on the ADNL protocol, providing you with not just reliable but also protected interactions with the TON network.

Each of these APIs brings its own set of advantages, and depending on your specific use case, you might lean towards one over the other.

How to build DApps on TON?

The TON Network is a powerhouse for creating DApps. It’s not just about the flexibility it offers, but equally about the range of tools it provides to ease your development process. Let’s explore some of these tools and learn how to build DApps using each one, hand-in-hand with Chainstack RPC nodes. But before we do that let’s first get a better understanding of how to deploy one with this video:

How to build with TonWeb?

TonWeb is a potent tool in the developer’s arsenal when building DApps on the TON Network. To jump-start your project using TonWeb, you should have Node.js installed on your machine and be familiar with a package manager like npm or yarn.

To initialize a project and install TonWeb run the following in CLI:

mkdir tonweb-project
cd tonweb-project
npm init -y
npm install tonweb

After setting up your project and installing TonWeb, your primary task is to initialize a connection with a Chainstack RPC node. It’s like shaking hands before starting a conversation; in this case, the conversation is your DApp interaction with the TON network. To do that enter the following in your script:

// For ES Module
// import TonWeb from "tonweb";
// For CommonJS
const TonWeb = require('tonweb'); 
const rpcEndpoint = "YOUR_CHAINSTACK_RPC_ENDPOINT";
const tonweb = new TonWeb(new TonWeb.HttpProvider(rpcEndpoint));
tonweb.getBalance('EQ...').then(info => {
	console.log(info);
});

How to build DApps using Ton.js?

Ton.js serves as a reliable companion for developers looking to create DApps on the TON Blockchain. Similar to TonWeb, the prerequisites include having Node.js on your machine and a package manager such as npm or yarn.

You can initialize a project and install Ton.js by running this in your CLI:

mkdir ton-project
cd ton-project
npm init -y
npm install ton

Upon setting up your project and installing Ton.js, you will establish a connection with a Chainstack RPC node. This step is crucial as it sets the stage for your DApp to interact seamlessly with the TON network. Here’s what you should add to your script:

// For ES Module
// import { TonClient } from 'ton';
// For CommonJS
const { TonClient } = require('ton');
const rpcEndpoint = "YOUR_CHAINSTACK_RPC_ENDPOINT";
const tonClient = new TonClient({
  endpoint: rpcEndpoint
});
tonClient.getBalance('EQ...').then(info => {
    console.log(info);
});

How to build on TON with TonUtils?

If you’re a Go enthusiast, building DApps on the TON Network gets even more exciting with TonUtils. Before you embark on your development journey with TonUtils, ensure that you have Go (version 1.16 or higher) installed on your machine along with a Go package manager like go mod.

Initialize your project and install TonUtils with the following in CLI:

go mod init go-tonproject
go get github.com/xssnick/tonutils-go@latest

After setting up your project and installing TonUtils, you’ll be ready to initiate a connection with a custom Lite Server. Custom Lite Servers are excellent choices for developers looking for secure, lightweight, and customizable servers to kickstart their DApp functionalities on the TON Network. To do that add the following to your script:

package main
import (
	"context"
	"fmt"
	"log"
	"github.com/xssnick/tonutils-go/address"
	"github.com/xssnick/tonutils-go/liteclient"
	"github.com/xssnick/tonutils-go/ton"
)
func main() {
	client := liteclient.NewConnectionPool()
	// Add a connection to a custom Lite Server using the global config URL
	err := client.AddConnectionsFromConfigUrl(context.Background(), "<https://ton.org/global.config.json>")
	if err != nil {
		log.Fatalf("Connection error: %v", err)
	}
	// Initialize the API client with proof check policy
	api := ton.NewAPIClient(client, ton.ProofCheckPolicyFast).WithRetry()
	// Create a context bound to a single TON node
	ctx := client.StickyContext(context.Background())
	// Get the current masterchain block info
	block, err := api.CurrentMasterchainInfo(ctx)
	if err != nil {
		log.Fatalf("Error getting block info: %v", err)
	}
	// Specify the wallet address to check the balance
	walletAddr := address.MustParseAddr("EQ...")
	// Use WaitForBlock to ensure the block is ready
	account, err := api.WaitForBlock(block.SeqNo).GetAccount(ctx, block, walletAddr)
	if err != nil {
		log.Fatalf("Error getting account: %v", err)
	}
	// Display account information
	fmt.Printf("Is active: %v\\n", account.IsActive)
	if account.IsActive {
		fmt.Printf("Status: %s\\n", account.State.Status)
		fmt.Printf("Balance: %s TON\\n", account.State.Balance.String())
	}
}

How to build Go DApps using TonGo?

TonGo presents another favorable avenue for Go language fans to build DApps on the TON Network. Similar to TonUtils, the prerequisites here include Go (version 1.16 or higher) and a Go package manager like go mod.

Start a fresh project and install TonGo with the following:

go mod init go-tonproject
go get github.com/tonkeeper/tongo@latest

Once your project is set up and TonGo is installed, your next move involves establishing a connection with custom RPC nodes. TonGo allows seamless integration with these nodes, ensuring your DApps can interact effortlessly with the TON Network. Here’s what you should add to your script:

package main
import (
	"context"
	"fmt"
	"github.com/tonkeeper/tongo"
	"github.com/tonkeeper/tongo/liteapi"
)
func main() {
	// options, err := config.ParseConfigFile("path/to/config.json")
	tongoClient, err := liteapi.NewClientWithDefaultMainnet()
	if err != nil {
		fmt.Printf("Unable to create tongo client: %v", err)
	}
	tonAddress := tongo.MustParseAddress("EQ...")
	state, err := tongoClient.GetAccountState(context.Background(), tonAddress.ID)
	if err != nil {
		fmt.Printf("Get account state error: %v", err)
	}
	fmt.Printf("Account status: %v\\nBalance: %v\\n", state.Account.Status(), state.Account.Account.Storage.Balance.Grams)
}

How to build Rust DApps with Tonlib-rs?

For developers who are keen on Rust, Tonlib-rs brings a robust solution for building DApps on the TON Network. Before you get started, ensure that Rust (version 1.56.0 or higher) is installed on your device along with Cargo, the Rust package manager.

For Linux, you will need the following packages installed:

sudo apt install build-essential cmake libsodium-dev libsecp256k1-dev lz4 liblz4-dev

In turn, for macOS, use the following:

brew install readline secp256k1 ccache pkgconfig cmake libsodium

And if you’re on Windows, install CMake first, then libsodium and other dependencies via vcpkg

vcpkg install libsodium libsecp256k1 lz4

Next, to initialize your project run:

cargo new tonlib-rs-project
cd tonlib-rs-project

Then, to install tonlib-rs open your Cargo.toml file in your project’s root and add the following under [dependencies]:

[dependencies]
tokio = { version = "1", features = ["full"] }
tonlib = "0.15"
anyhow = "1.0"

After setting up your project and integrating Tonlib-rs, it’s time to initiate a connection with a Chainstack RPC node. Seamlessly connecting to this node allows your DApp to securely interact with the TON network, setting the stage for efficient and secure DApp functionalities. To do that create a new main.rs file in the src directory and add the following:

use tonlib::address::TonAddress;
use tonlib::client::TonClient;
use tonlib::client::TonClientInterface;
use anyhow::Result;
async fn get_state() -> Result<()> {  
    let client = TonClient::builder().build().await?;
    
    let address = TonAddress::from_base64_url(
        "EQ...",
    )?;
    
    let r = client.get_account_state(&address).await?;
    println!("Account balance: {:?}", r.balance);
    Ok(())
}
#[tokio::main]
async fn main() {
    if let Err(e) = get_state().await {
        eprintln!("Error: {:?}", e);
    }
}

How to build Python DApps with TONsdk?

TONsdk opens up new avenues for Python enthusiasts to build DApps on the TON Network. To set up your project with TONsdk, you’ll need Python version 3.6.0 or higher and pip, the Python package manager.

To start a fresh project and install the TONsdk, run the following in CLI:

mkdir tonsdk-project
cd tonsdk-project
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install tonsdk tvm_valuetypes aiohttp

After initializing your project and installing TONsdk, your key task involves setting up a connection with a Chainstack RPC node. This bridge establishes your DApp’s communication with the TON network, ensuring a smooth interaction right from the get-go. Add the following to your script to do that:

import asyncio
import aiohttp
from tonsdk.provider import ToncenterClient, prepare_address, address_state
from tonsdk.utils import TonCurrencyEnum, from_nano
async def get_wallet_balance(address: str):
    client = ToncenterClient(base_url="YOUR_CHAINSTACK_RPC_ENDPOINT", api_key="")
    address = prepare_address(address)
    
    async with aiohttp.ClientSession() as session:
        # Get the account state function and its arguments
        account_state_func = client.raw_get_account_state(address)
        
        # Invoke the function with the session
        account_state = await account_state_func['func'](session, *account_state_func['args'], **account_state_func['kwargs'])
        
        # Process the account state to get the balance
        account_state["state"] = address_state(account_state)
        if "balance" in account_state:
            if int(account_state["balance"]) < 0:
                account_state["balance"] = 0
            else:
                account_state["balance"] = from_nano(int(account_state["balance"]), TonCurrencyEnum.ton)
        
        return account_state["balance"]
address = "EQ..."
balance = asyncio.run(get_wallet_balance(address))
print(f"Balance: {balance} TON")

How to build on TON with PyTONLib?

For Python developers, PyTONLib offers an excellent toolkit to interact with the TON Network. Before diving into your project with PyTONLib, note that Python should be installed on your machine (version 3.6.0 or higher) along with pip.

To initialize your project and install PyTONLib run the following in your CLI:

mkdir new-project
cd new-project
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install pytonlib

Once your project is set up and PyTONLib is installed, you can initialize a connection with a Chainstack RPC node. From here you can check a TON wallet’s balance, marking the first step in your journey of interacting with the TON Blockchain using PyTONLib.

import requests
import asyncio
from pathlib import Path
from pytonlib import TonlibClient
async def get_address_balance(address):
    ton_config = requests.get('<https://ton.org/testnet-global.config.json>').json()
    keystore_dir = '/tmp/ton_keystore'
    Path(keystore_dir).mkdir(parents=True, exist_ok=True)
    client = TonlibClient(ls_index=4,
                        config=ton_config,
                        keystore=keystore_dir)
    await client.init()
    account_state = await client.raw_get_account_state(address)
    balance = int(account_state['balance']) / 1e9
    print(f"Balance: {balance} TON")
    await client.close()
if __name__ == "__main__":
    asyncio.run(get_address_balance("EQ..."))

How to build TON DApps with Pytoniq?

Pytoniq offers a Python-centric approach to build DApps on the TON Network. Like PyTONLib, you need Python (version 3.6.0 or higher) and pip for starting your Pytoniq-based project.

You can start a fresh project and install Pytoniq using this in CLI:

mkdir new-project
cd new-project
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\\Scripts\\activate
pip install pytoniq

Once your project is initialized and Pytoniq is installed, your next task is to establish a connection with custom Lite servers. After the connection is up and running, your DApp can smoothly interact with the TON network, leveraging the power and flexibility of the Pytoniq library. You can do that by adding the following to your script:

import asyncio
from pytoniq import LiteClient
async def main():
    client = LiteClient.from_mainnet_config()
    await client.connect()
    account_state = await client.get_account_state("EQ...")
    print(f"Balance: {account_state.balance}")
if __name__ == "__main__":
    asyncio.run(main())

How to build DApps with TonSDK.NET?

TonSDK.NET caters to .NET-oriented developers who aspire to build DApps on the TON Blockchain. To kick off your innovative project with TonSDK.NET, you’d need the .NET SDK (version 5.0 or higher) installed on your device.

Initialize your project and install TonSDK.NET using the following:

dotnet new console -n TonSdkNetProject
cd TonSdkNetProject
dotnet add package TonSdk.Client --version 0.3.10

After setting up your project and integrating TonSDK.NET, your primary task is to initiate a connection with a Chainstack RPC Node. This connection anchors your DApp’s interaction with the TON network, ensuring a seamless and efficient development experience. Add the following to your script to achieve that:

using TonSdk.Client;
using TonSdk.Core;
class Program
{
    static async Task Main(string[] args)
    {
        var clientParams = new HttpParameters() { Endpoint = "YOUR_CHAINSTACK_ENDPOINT", ApiKey = "" };
        var client = new TonClient(TonClientType.HTTP_TONCENTERAPIV2, clientParams);
        var address = new Address("EQ...");
        var accBalance = await client.GetBalance(address);
        var balance = accBalance.ToDecimal() / 1_000_000_000;
        Console.WriteLine($"Balance: {balance} TON");
        client.Dispose();
    }
}

Further reading

Expand your TON knowledge and development skills with these comprehensive Chainstack resources:

Bringing it all together

If you’re a Web3 developer exploring the landscape of blockchain technologies, the TON Network provides some of the most powerful tools and libraries to kickstart your DApp development journey.

With each tool offering its unique characteristics, you have a versatile range of choices from TonWeb, Ton.js, and TonUtils, to TonGo, Tonlib-rs, TONsdk, PyTONLib, Pytoniq, or TonSDK.NET. These allow you to pick what suits your preferences, whether it’s a language choice or a specific function. And with Chainstack RPC Nodes easily accessible, the key connection between your DApps and the TON Network is effortlessly established.

The world of DApp development is ready for you to make a mark. Start building on TON today!

Power-boost your project on Chainstack

Have you already explored what you can achieve with Chainstack? Get started for free today.

SHARE THIS ARTICLE
Customer Stories

Benqi

Benqi powers hundreds of Avalanche Subnets validators using Chainstack infrastructure for its Ignite program.

CertiK

CertiK cut Ethereum archive infrastructure costs by 70%+ for its radical take on Web3 security.

Hypernative

Hypernative reinforces Web3 security with resilient Chainstack infrastructure, optimizing asset protection and efficiency.