> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TON tooling

> TON blockchain development tools guide. Use TonWeb, Ton.js, Blueprint, wallets, and SDKs for Python, Go, Rust, and .NET with Chainstack endpoints.

## 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](https://docs.ton.org/participate/wallets/contracts). 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.

### [Tonkeeper](https://github.com/tonkeeper/tonkeeper-web/)

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.

### [MyTonWallet](https://github.com/mytonwalletorg/mytonwallet)

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.

### [OpenMask](https://github.com/OpenProduct/openmask-extension)

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.

### [TON Wallet](https://github.com/toncenter/ton-wallet)

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](https://github.com/ton-community/awesome-ton) or [the TON Research page](https://tonresear.ch/t/ton-ecosystem/505).

### [Nujan IDE](https://ide.nujan.io/)

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](https://docs.ton.org/v3/guidelines/dapps/apis-sdks/api-types) 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](https://docs.ton.org/v3/documentation/network/protocols/adnl/overview), ensuring reliable and protected interactions with the TON network.

<Check>
  ### ADNL support on dedicated nodes

  Chainstack TON dedicated nodes support both HTTP API and ADNL protocol, enabling advanced low-level network communication for specialized use cases.
</Check>

### TonWeb

Build DApps on the TON Blockchain using [TonWeb](https://github.com/toncenter/tonweb) and custom RPC nodes.

**Prerequisites**

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

**Initialize a project**

<CodeGroup>
  ```bash Bash theme={"system"}
  mkdir tonweb-project
  cd tonweb-project
  npm init -y
  ```
</CodeGroup>

**Install TonWeb**

<CodeGroup>
  ```bash Bash theme={"system"}
  npm install tonweb
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

<CodeGroup>
  ```javascript Javascript theme={"system"}
  // 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);
  });
  ```
</CodeGroup>

### Ton.js

Build DApps on the TON Blockchain using [Ton.js](https://github.com/ton-org/ton) and custom RPC nodes.

**Prerequisites**

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

**Initialize a project**

<CodeGroup>
  ```bash Bash theme={"system"}
  mkdir ton-project
  cd ton-project
  npm init -y
  ```
</CodeGroup>

**Install Ton.js**

<CodeGroup>
  ```bash Bash theme={"system"}
  npm install ton
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

<CodeGroup>
  ```javascript Javascript theme={"system"}
  // 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);
  });
  ```
</CodeGroup>

### TonUtils

Build DApps on the TON Blockchain using [TonUtils](https://github.com/xssnick/tonutils-go) 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**

<CodeGroup>
  ```bash Bash theme={"system"}
  go mod init go-tonproject
  ```
</CodeGroup>

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

**Install TonUtils**

<CodeGroup>
  ```bash Bash theme={"system"}
  go get github.com/xssnick/tonutils-go@latest
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

<CodeGroup>
  ```go Go theme={"system"}
  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())
  	}
  }
  ```
</CodeGroup>

### TonGo

Build DApps on the TON Blockchain using [tongo](https://github.com/tonkeeper/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**

<CodeGroup>
  ```bash Bash theme={"system"}
  go mod init go-tonproject
  ```
</CodeGroup>

**Install TonGo**

<CodeGroup>
  ```bash Bash theme={"system"}
  go get github.com/tonkeeper/tongo@latest
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

<CodeGroup>
  ```go Go theme={"system"}
  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)
  }
  ```
</CodeGroup>

### Tonlib-rs

Build DApps on the TON Blockchain using [Tonlib-rs](https://github.com/ston-fi/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:

<CodeGroup>
  ```bash Bash theme={"system"}
  sudo apt install build-essential cmake libsodium-dev libsecp256k1-dev lz4 liblz4-dev
  ```
</CodeGroup>

For macOS, ensure the following packages are installed:

<CodeGroup>
  ```bash Bash theme={"system"}
  brew install readline secp256k1 ccache pkgconfig cmake libsodium
  ```
</CodeGroup>

For Windows, ensure the following are installed:

1. CMake: Install via [cmake.org](http://cmake.org/)

2. Install `libsodium` and other dependencies via `vcpkg`:

   ```bash theme={"system"}
   vcpkg install libsodium libsecp256k1 lz4
   ```

**Initialize a project**

<CodeGroup>
  ```bash Bash theme={"system"}
  cargo new tonlib-rs-project
  cd tonlib-rs-project
  ```
</CodeGroup>

**Install tonlib-rs**

1. Open the `Cargo.toml` file in the root of your project.
2. Add the following dependencies under `[dependencies]`:

<CodeGroup>
  ```toml TOML theme={"system"}
  [dependencies]
  tokio = { version = "1", features = ["full"] }
  tonlib = "0.15"
  anyhow = "1.0"
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

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

<CodeGroup>
  ```Rust Rust theme={"system"}
  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);
      }
  }
  ```
</CodeGroup>

### TONsdk

Build DApps on the TON Blockchain using [TONsdk](https://github.com/tonfactory/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**

<CodeGroup>
  ```bash Bash theme={"system"}
  mkdir tonsdk-project
  cd tonsdk-project
  python3 -m venv venv
  source venv/bin/activate  # On Windows: venv\Scripts\activate
  ```
</CodeGroup>

**Install TONsdk**

<CodeGroup>
  ```bash Bash theme={"system"}
  pip install tonsdk tvm_valuetypes aiohttp
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

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

<CodeGroup>
  ```python Python theme={"system"}
  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")
  ```
</CodeGroup>

### PyTONLib

Build DApps on the TON Blockchain using [PyTONLib](https://github.com/toncenter/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**

<CodeGroup>
  ```bash Bash theme={"system"}
  mkdir new-project
  cd new-project
  python3 -m venv venv
  source venv/bin/activate  # On Windows: venv\Scripts\activate
  ```
</CodeGroup>

**Install PyTONLib**

<CodeGroup>
  ```bash Bash theme={"system"}
  pip install pytonlib
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

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

<CodeGroup>
  ```python Python theme={"system"}
  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..."))
  ```
</CodeGroup>

### Pytoniq

Build DApps on the TON Blockchain using [Pytoniq](https://github.com/yungwine/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**

<CodeGroup>
  ```bash Bash theme={"system"}
  mkdir new-project
  cd new-project
  python3 -m venv venv
  source venv/bin/activate  # On Windows: venv\Scripts\activate
  ```
</CodeGroup>

**Install Pytoniq**

<CodeGroup>
  ```bash Bash theme={"system"}
  pip install pytoniq
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

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

<CodeGroup>
  ```python Python theme={"system"}
  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())
  ```
</CodeGroup>

### TonSdk.NET

Build DApps on the TON Blockchain using [TonSdk.NET](https://github.com/continuation-team/TonSdk.NET) and custom RPC nodes.

**Prerequisites**

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

**Initialize a project**

<CodeGroup>
  ```bash Bash theme={"system"}
  dotnet new console -n TonSdkNetProject
  cd TonSdkNetProject
  ```
</CodeGroup>

**Install TonSDK.NET**

<CodeGroup>
  ```bash Bash theme={"system"}
  dotnet add package TonSdk.Client --version 0.3.10
  ```
</CodeGroup>

**Initialize connection with a Chainstack RPC Node**

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

<CodeGroup>
  ```csharp C# theme={"system"}
  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();
      }
  }
  ```
</CodeGroup>

## Development frameworks and toolkits

### Blueprint

Build DApps on the TON Blockchain using [Blueprint](https://github.com/ton-org/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**

<CodeGroup>
  ```csharp Bash theme={"system"}
  npm create ton@latest
  ```
</CodeGroup>

**Create or update the configuration file**

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

<CodeGroup>
  ```typescript TypeScript theme={"system"}
  import { Config } from '@ton/blueprint';

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

**Compile and deploy contracts**

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

<CodeGroup>
  ```tsx Bash theme={"system"}
  npx blueprint build
  ```
</CodeGroup>

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

<CodeGroup>
  ```tsx Bash theme={"system"}
  npx blueprint run
  ```
</CodeGroup>
