TON

Wallets

Wallets allow the addition of custom RPC endpoints either by directly modifying the settings of an existing network or by adding a custom network and specifying a custom RPC endpoint.

To obtain the address of your RPC endpoint, navigate to the node details on the Chainstack console and locate the Execution client HTTPS endpoint in the Access and credentials section.

Note that there are different versions of TON wallets. This is because, essentially, any wallet is a smart contract running on the TON Blockchain. These smart contracts can be configured in different ways and may have different features.

This wallet does not offer an option to set custom RPC endpoints through the user interface. However, since the wallet is open-source, you can modify the RPC endpoint directly in the source code. Additionally, the wallet supports switching between different versions of wallet contracts.

To switch to Testnet, go to Settings, click on the Tonkeeper Web icon 5 times, and then change the active network.

This wallet does not offer an option to set custom RPC endpoints through the user interface. However, since the wallet is open-source, you can modify the RPC endpoint directly in the source code. Additionally, the wallet supports switching between different versions of wallet contracts.

To switch to Testnet, go to Settings, click on the MyTonWallet label 5 times, and then change the active network.

This wallet offers an option to set custom RPC endpoints through the user interface. It is an open-source MetaMask extension equivalent for TON. The wallet supports switching between different versions of wallet contracts.

To set a custom RPC endpoint, navigate to Wallet Settings.

To switch to Testnet, change the active network in the top menu of the wallet window.

This wallet does not offer an option to set custom RPC endpoints through the user interface. However, since the wallet is open-source, you can modify the RPC endpoint directly in the source code. The wallet doesn’t support switching between different versions of wallet contracts.

IDEs

Cloud-based IDEs offer the flexibility to use injected providers. By adding a Chainstack RPC node to a wallet and connecting that wallet in your IDE, you can seamlessly interact with the network through the Chainstack node.

There are also multiple TON-related plugins for various IDEs. You can find them on the Awesome List page or the TON Research page.

To enable Nujan IDE to interact with the network via a Chainstack node, you can follow these steps:

  1. Install and set up OpenMask to use a Chainstack node for interaction. Refer to the guide on interacting through OpenMask for detailed instructions.
  2. Open the IDE and navigate to the Build & Deploy tab. Click on Connect Wallet and select a wallet with your configured custom RPC endpoint.

Blockchain interaction libraries

TON API types

Note that there are two types of APIs available for interacting with the TON network. The TON HTTP API enables access to indexed blockchain information, providing a way to work with data efficiently. On the other hand, the TON ADNL API offers a secure communication method based on the ADNL protocol, ensuring reliable and protected interactions with the TON network.

TonWeb

Build DApps on the TON Blockchain using TonWeb and custom RPC nodes.

Prerequisites

  1. Node.js installed on your machine.
  2. A package manager like npm or yarn.

Initialize a project

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

Install TonWeb

npm install tonweb

Initialize connection with a Chainstack RPC Node

// 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);
});

Ton.js

Build DApps on the TON Blockchain using Ton.js and custom RPC nodes.

Prerequisites

  1. Node.js installed on your machine.
  2. A package manager like npm or yarn.

Initialize a project

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

Install Ton.js

npm install ton

Initialize connection with a Chainstack RPC Node

// 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);
});

TonUtils

Build DApps on the TON Blockchain using TonUtils and custom RPC nodes.

Prerequisites

  1. Go installed on your machine (version 1.16 or higher).
  2. A Go package manager like go mod.

Initialize a project

go mod init go-tonproject

Please make sure that go.mod contains all required dependencies.

Install TonUtils

go get github.com/xssnick/tonutils-go@latest

Initialize connection with a Chainstack RPC Node

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())
	}
}

TonGo

Build DApps on the TON Blockchain using tongo and custom RPC nodes.

Prerequisites

  1. Go installed on your machine (version 1.16 or higher).
  2. A Go package manager like go mod.

Initialize a project

go mod init go-tonproject

Install TonGo

go get github.com/tonkeeper/tongo@latest

Initialize connection with a Chainstack RPC Node

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)
}

Tonlib-rs

Build DApps on the TON Blockchain using Tonlib-rs and custom RPC nodes.

Prerequisites

  1. Rust installed on your machine (version 1.56.0 or higher).
  2. Cargo (the Rust package manager) should be installed as part of the Rust installation.

Install required packages

For Linux, ensure the following packages are installed:

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

For macOS, ensure the following packages are installed:

brew install readline secp256k1 ccache pkgconfig cmake libsodium

For Windows, ensure the following are installed:

  1. CMake: Install via cmake.org

  2. Install libsodium and other dependencies via vcpkg:

    vcpkg install libsodium libsecp256k1 lz4
    

Initialize a project

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

Install tonlib-rs

  1. Open the Cargo.toml file in the root of your project.
  2. Add the following dependencies under [dependencies]:
[dependencies]
tokio = { version = "1", features = ["full"] }
tonlib = "0.15"
anyhow = "1.0"

Initialize connection with a Chainstack RPC Node

Create a new file named main.rs in the src directory and add the following code:

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);
    }
}

TONsdk

Build DApps on the TON Blockchain using TONsdk and custom RPC nodes.

Prerequisites

  1. Python installed on your machine (version 3.6.0 or higher).
  2. pip (Python package manager) should be installed as part of the Python installation.

Initialize a project

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

Install TONsdk

pip install tonsdk tvm_valuetypes aiohttp

Initialize connection with a Chainstack RPC Node

Create a new file named main.py in the project directory and add the following code:

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")

PyTONLib

Build DApps on the TON Blockchain using PyTONLib and custom RPC nodes.

Prerequisites

  1. Python installed on your machine (version 3.6.0 or higher).
  2. pip (Python package manager) should be installed as part of the Python installation.

Initialize a project

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

Install PyTONLib

pip install pytonlib

Initialize connection with a Chainstack RPC Node

Create a new file named main.py in the project directory and add the following code:

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..."))

Pytoniq

Build DApps on the TON Blockchain using Pytoniq and custom RPC nodes.

Prerequisites

  1. Python installed on your machine (version 3.6.0 or higher).
  2. pip (Python package manager) should be installed as part of the Python installation.

Initialize a project

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

Install Pytoniq

pip install pytoniq

Initialize connection with a Chainstack RPC Node

Create a new file named main.py in the project directory and add the following code:

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())

TonSdk.NET

Build DApps on the TON Blockchain using TonSdk.NET and custom RPC nodes.

Prerequisites

  1. .NET SDK installed on your machine (version 5.0 or higher).

Initialize a project

dotnet new console -n TonSdkNetProject
cd TonSdkNetProject

Install TonSDK.NET

dotnet add package TonSdk.Client --version 0.3.10

Initialize connection with a Chainstack RPC Node

Replace the contents of the Program.cs file with the following code:

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();
    }
}

Development frameworks and toolkits

Blueprint

Build DApps on the TON Blockchain using Blueprint and custom RPC nodes.

Prerequisites

  1. Node.js installed on your machine (version 18 or higher).
  2. A package manager like npm or yarn.

Initialize a Blueprint project

npm create ton@latest

Create or update the configuration file

Add to your the project configuration file named blueprint.config.ts your Chainstack endpoint:

import { Config } from '@ton/blueprint';

export const config: Config = {
    network: {
        endpoint: 'YOUR_CHAINSTACK_ENDPOINT',
        type: 'testnet',
        version: 'v2',
        key: 'YOUR_API_KEY',
    },
};

Compile and deploy contracts

Update contracts wrappers and deployment scripts if needed. Compile the contracts:

npx blueprint build

Pick the appropriate network after running the followind command to deploy the contracts:

npx blueprint run