Перейти к основному содержимому

Reading from network

Introduction

This guide will walk you through reading data from the TON Blockchain. You'll learn how to:

  • Fetch account information
  • Call get methods
  • Retrieve account transactions

By the end, you'll understand how to interact with TON HTTP-based APIs. Particularly, in this guide TON Center is used, a fast and reliable HTTP API for TON.

Setup environment

First, visit installation pages and install NodeJS and npm for your OS. Check that installation is correct by running those commands:

node -v
npm -v

Version of node and npm should be at least v20 and v10 correspondingly.

Project setup

Let's set up our project structure:

  1. Create a new directory for your project
  2. Initialize a Node.js project
  3. Install required dependencies

Run these commands in your terminal:

mkdir reading-from-ton && cd reading-from-ton # create new directory and cd to it
npm init -y # initialize Node.js project
npm install typescript ts-node @ton/ton @ton/core @ton/crypto #install required dependecies
npx tsc --init # initialize typesctipt

To run scripts, use the following command:

npx ts-node script.ts

Reading account information

Account information includes the balance, state, code, and data.

  • balance: The amount of TON the account holds.
  • state: Can be one of:
    • Nonexist: The address has no data.
    • Uninit: The address has a balance but no smart contract code.
    • Active: The address is live with code and balance.
    • Frozen: The address is locked due to insufficient balance for storage costs.
  • code: The contract's code in raw format.
  • data: Serialized contract data stored in a Cell.

Account state may be obtained using getContractState method.

Implementation

Create a new file 1-get-account-state.ts:

1-get-account-state.ts
import { Address, TonClient } from "@ton/ton";

async function main() {
// Initializaing TON HTTP API Client
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
});

const accountAddress = Address.parse('0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A-'); // Replace with any address

// Calling method on http api
const state = await tonClient.getContractState(accountAddress);


console.log('State: ', state.state);
console.log('Balance: ', state.balance);
console.log('Data: ', state.data?.toString('hex'));
console.log('Code: ', state.code?.toString('hex'));
}

main();

Run this example using following command:

npx ts-node 1-get-account-state.ts

Expected result

State:  active
Balance: 3722511000883n
Data: b5ee9c7241010101002...fd1e976824402aa67b98
Code: b5ee9c7241021401000...c9ed54696225e5

Calling get methods

Get methods are special functions in smart contracts that allow you to observe current state of smart contract. Their execution doesn't cost any fees and can't change smart contract storage.

Result of calling get method from TON HTTP API comes in stack format and may be deserialized one by one using readNumber() or similar function.

Implementation

Create a new file 2-call-get-method.ts:

2-call-get-method.ts
import { Address, TonClient, TupleBuilder } from "@ton/ton";

async function main() {
// Initializaing TON HTTP API Client
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
});

// Building optional get method parameters list
const builder = new TupleBuilder();
builder.writeAddress(Address.parse('0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A-'));

const accountAddress = Address.parse('kQD0GKBM8ZbryVk2aESmzfU6b9b_8era_IkvBSELujFZPsyy')

// Calling http api to run get method on specific contract
const result = await tonClient.runMethod(
accountAddress, // address to call get method on
'get_wallet_address', // method name
builder.build(), // optional params list
);

// Deserializing get method result
const address = result.stack.readAddress();
console.log(address.toRawString());
}

main();

Run this example using following command:

npx ts-node 2-call-get-method.ts

Expected result

0:25f2bf1ce8f83ed0c0fd73ea27aac77093cdcf900c750b071df7fb0288e019b2

Get methods may also be called using Tonviewer:

  1. Navigate to get methods section.
  2. Select get_wallet_address.
  3. Insert address from example 0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A- to slice section.
  4. Press Execute.

You will end up with same address you got from console.

Using wrappers for simplicity

Wrappers are classes that simplify interactions with smart contracts by turning complex blockchain operations into simple functions calls - instead of manually serializing cells and transactions, you can just call methods like jettonMaster.getWalletAddress() that already performs it for you. Here's an example of using a wrapper functionally equivalent to previous code snippet:

import { Address, JettonMaster, TonClient } from "@ton/ton";

async function main() {
// Initializaing TON HTTP API Client
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
});

// Initializing wrappers
const jettonMaster = tonClient.open(
JettonMaster.create(Address.parse('kQD0GKBM8ZbryVk2aESmzfU6b9b_8era_IkvBSELujFZPsyy')),
);

// Calling get method through wrapper
const address = jettonMaster.getWalletAddress(Address.parse('0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A-'));
console.log(address);
}

main();

Fetching account transactions

Interaction within account on blockchain happens due to messages and transactions.

What is a transaction?

A transaction in TON consists of the following:

  • the incoming message that initially triggers the contract (special ways to trigger exist)
  • contract actions caused by the incoming message, such as an update to the contract's storage (optional)
  • outgoing messages generated and sent to other actors (optional)

Key transaction fields

Transaction obtained from API have the following structure:

{
"@type": "raw.transaction",
"address": {
"@type": "accountAddress",
"account_address": "EQD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje02Zx"
},
"utime": 1738588970,
...
"in_msg": {
...
},
"out_msgs": [...]
}
  • address: The account address where the transaction occurred.
  • utime: The UNIX timestamp of the transaction.
  • in_msg: The incoming message that triggered the transaction.
  • out_msgs: Outgoing messages sent during the transaction.

What is a message?

A message is a packet of data exchanged between actors (users, applications, or smart contracts). It typically contains information instructing the receiver on what action to perform, such as updating storage or sending a new message.

Key message fields

{
"@type": "raw.message",
"hash": "mcHdqltDAB8ODQHqtedtYQIS6MQL7x4ut+nf9tXWGqg=",
"source": "EQAJTegD8OO-HksHfI4KVDqb7vW9Dlqi5C1FTcL1dECeosTf",
"destination": "EQD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje02Zx",
"value": "20000000",
...
"msg_data": {
"@type": "msg.dataRaw",
"body": "te6cckEBAQEAAgAAAEysuc0=",
...
},
...
}
  • source: The address of the sender (the account that initiated the message).
  • destination: The address of the receiver (the account that will process the message).
  • value: The amount of TON (in nanoTON) attached to the message.
  • msg_data: Contains message body and state init.

Implementation

Create a new file 3-fetch-account-transaction.ts:

3-fetch-account-transaction.ts
import { Address, TonClient } from "@ton/ton";

async function main() {
// Initializaing TON HTTP API Client
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
});

// Calling method on http api
// full api: https://testnet.toncenter.com/api/v2/#/accounts/get_transactions_getTransactions_get
const transactions = await tonClient.getTransactions(
Address.parse('0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A-'), // Address to fetch transactions
{
limit: 10, //maximum ammount of recieved transactions
archival: true, //search in all history
},
);

const firstTx = transactions[0];
const { inMessage } = firstTx;

console.log('Timestamp:', firstTx.now);
if (inMessage?.info?.type === 'internal') {
console.log('Value:', inMessage.info.value.coins);
console.log('Sender:', inMessage.info.src);
}
}

main();

Run this example using following command:

npx ts-node 3-fetch-account-transaction.ts

Expected result

Timestamp: 1743516631
Value: 100000000n
Sender: EQBui16XCF61MSWauIDpVFbKAOJmjLHRxXvXeqiN9dYaIgjq
к сведению

More complex example about traversing transactions graph may be found here.