### Install Dependencies and Start Dev Server Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tma/tutorials/app-examples.mdx Install project dependencies and start the development server. The --host option provides an IP address for testing, and the basic-ssl plugin is recommended for testing on web.telegram.org. ```bash # npm npm install npm run dev --host # or yarn yarn yarn dev --host ``` -------------------------------- ### Send and Verify Message Example Setup Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/transactions/hash-based-tracking.mdx Initializes the TON client, loads wallet keys from a mnemonic, and creates a wallet contract instance. Demonstrates how to check the wallet's on-chain state. ```typescript async function sendAndVerifyMessage() { // Client configuration // - Testnet: endpoint = https://testnet.toncenter.com/api/v2/jsonRPC // - Mainnet: endpoint = https://toncenter.com/api/v2/jsonRPC // Note: Many providers require an API key on both networks. Replace with your key. const client = new TonClient({ endpoint: "https://testnet.toncenter.com/api/v2/jsonRPC", apiKey: "your api key", // Get your API key via @toncenter bot }); // Load wallet key pair from mnemonic const mnemonic = "your seed phrase".split(" "); // Insert your seed phrase here const keyPair = await mnemonicToPrivateKey(mnemonic); // Wallet selection // - V5R1 on Testnet: walletId.networkGlobalId = -3 (may need to be set) // - V5R1 on Mainnet: walletId.networkGlobalId = -239 (default value) // - V4/V3R2 on either: no walletId field, only { workchain, publicKey } const walletContract = WalletContractV5R1.create({ publicKey: keyPair.publicKey, workchain: 0, //walletId: { networkGlobalId: -3 }, // testnet }); const wallet = client.open(walletContract); // Log on-chain state to be sure that the wallet has funds to send a message console.log( "Wallet address (bounceable): ", wallet.address.toString({ testOnly: false, bounceable: true }) ); console.log( "Wallet address (non-bounceable):", wallet.address.toString({ testOnly: false, bounceable: false }) ); const onchainState = await retry( () => client.getContractState(wallet.address), { retries: 2, delay: 2000, progress: true, progressLabel: "getContractState", } ); const isDeployed = onchainState.state === "active"; ``` -------------------------------- ### Start API and Database with Docker Compose Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/asset-processing/compressed-nfts.mdx Initiate the API and database services using Docker Compose. Ensure Docker and Docker Compose are installed and configured. ```bash docker-compose up -d db api ``` -------------------------------- ### Install ts-node and arg for Manual Setup Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/single-nominator-pool.mdx Install necessary Node.js packages for manual setup of the single nominator pool. Ensure Node.js v16 or later is installed. ```bash $ sudo apt install ts-node $ sudo npm i arg -g ``` -------------------------------- ### Create TON Wallet V4R2 and get address/mnemonics (Python) Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/asset-processing/payments-processing.mdx Example using pytoniq to create a WalletV4R2 contract, obtain its address, and retrieve the mnemonics. Requires an asyncio provider. ```python import asyncio from pytoniq.contract.wallets.wallet import WalletV4R2 from pytoniq.liteclient.balancer import LiteBalancer async def main(): provider = LiteBalancer.from_mainnet_config(2) await provider.start_up() mnemonics, wallet = await WalletV4R2.create(provider) print(f"{wallet.address=} and {mnemonics=}") await provider.close_all() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example: Set wallet version Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/nodes/mytonctrl/overview.mdx Example of setting the wallet version to 'v3' for a wallet with the address 'kf9tZrL46Xjux3ZqvQFSgQkOIlteJK52slSYWbasqtOjrKUT'. ```bash MyTonCtrl> swv kf9tZrL46Xjux3ZqvQFSgQkOIlteJK52slSYWbasqtOjrKUT v3 ``` -------------------------------- ### Project Setup for TON Interaction Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/quick-start/blockchain-interaction/writing-to-network.mdx Commands to create a new project directory, initialize a Node.js project, install necessary TON SDK dependencies, and initialize TypeScript configuration. ```bash mkdir writing-to-ton && cd writing-to-ton npm init -y npm install typescript ts-node @ton/ton @ton/core @ton/crypto npx tsc --init ``` -------------------------------- ### Example: Import a pool Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/nodes/mytonctrl/overview.mdx Example of importing a pool named 'name' with the address 'kf_JcC5pn3etTAdwOnc16_tyMmKE8-ftNUnf0OnUjAIdDJpX'. ```bash MyTonCtrl> import_pool name kf_JcC5pn3etTAdwOnc16_tyMmKE8-ftNUnf0OnUjAIdDJpX ``` -------------------------------- ### Install aiofiles for storage Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/frameworks/python.mdx Install the aiofiles library to implement file-based storage for user wallet connection data. ```bash pip install aiofiles ``` -------------------------------- ### Install Dependencies and Initialize TypeScript Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/multisig-js.mdx Installs necessary packages and initializes the TypeScript compiler configuration for the project. ```bash yarn add typescript @types/node ton ton-crypto ton-core buffer @orbs-network/ton-access yarn tsc --init -t es2022 ``` -------------------------------- ### Install tonutils SDK Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/frameworks/python.mdx Install the recommended SDK for Python applications to interact with TON Connect. ```bash pip install tonutils ``` -------------------------------- ### Install Python Libraries Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-2.mdx Install the necessary PyPi libraries for the Telegram bot. Ensure you have Python installed. ```bash pip install aiogram==2.21 requests ``` -------------------------------- ### Install Project Libraries Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/nft-minting-guide.mdx Installs necessary libraries for interacting with Pinata, environment variables, and the TON blockchain. ```bash npm install @pinata/sdk dotenv @ton/ton @ton/crypto @ton/core buffer ``` -------------------------------- ### Install Pyth TON SDK Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/infra/oracles/pyth.mdx Install the Pyth TON SDK and other necessary dependencies using npm or yarn. ```bash npm install @pythnetwork/pyth-ton-js @pythnetwork/hermes-client @ton/core @ton/ton @ton/crypto ``` ```bash yarn add @pythnetwork/pyth-ton-js @pythnetwork/hermes-client @ton/core @ton/ton @ton/crypto ``` -------------------------------- ### Get Nominator Data Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/smart-contracts/contracts-specs/nominator-pool.mdx Example of how to call the get_nominator_data method with a raw nominator address. ```bash get_nominator_data 0x348bcf827469c5fc38541c77fdd91d4e347eac200f6f2d9fd62dc08885f0415f ``` -------------------------------- ### Handle /start and /help Commands Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-2.mdx Responds to the /start and /help commands by checking if the user exists in the database, adding them if not, and sending a welcome message with a custom keyboard. ```python @dp.message_handler(commands=['start', 'help']) async def welcome_handler(message: types.Message): uid = message.from_user.id # Not neccessary, just to make code shorter # If user doesn't exist in database, insert it if not db.check_user(uid): db.add_user(uid) # Keyboard with two main buttons: Deposit and Balance keyboard = ReplyKeyboardMarkup(resize_keyboard=True) keyboard.row(KeyboardButton('Deposit')) keyboard.row(KeyboardButton('Balance')) # Send welcome text and include the keyboard await message.answer('Hi!\nI am example bot ' 'made for [this article](docs.ton.org/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-2).\n' 'My goal is to show how simple it is to receive ' 'payments in Toncoin with Python.\n\n' 'Use keyboard to test my functionality.', reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN) ``` -------------------------------- ### Example Console Output of Get Method Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/get-started-with-ton.mdx This is an example of the console output when a smart contract get method returns a tuple of integer values. The output format is a `TupleReader` with an array of items, each specifying its type and value. ```text TupleReader { items: [ { type: 'int', value: 7237005577332262213973186563042994240829374041602535252466099000494570602496n }, { type: 'int', value: 1730818693n }, { type: 'int', value: 281644526620911853868912633959724884177n }, { type: 'int', value: 30n }, { type: 'int', value: 171n }, { type: 'int', value: 252n } ] } ``` -------------------------------- ### Navigate to project and install dependencies Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/quick-start/developing-smart-contracts/setup-environment.mdx After creating the project template, change your directory to the generated project folder and install all required dependencies. ```bash cd ./Example npm install ``` -------------------------------- ### Set up Prerequisites for Building MyLocalTon from Source Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/running-nodes/running-a-local-ton.mdx Install the Java Development Kit (JDK) version 21 or higher and the Maven build automation tool. Verify the Java installation. ```bash # Install Java Development Kit (JDK) 21 sudo apt update && sudo apt install -y openjdk-21-jdk # Install Maven build automation tool sudo apt install -y maven ``` ```bash java -version ``` -------------------------------- ### Install Unattended Upgrades Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/running-nodes/secure-guidelines.mdx Configure unattended upgrades for automatic security updates. This example shows installation for Debian/Ubuntu and RHEL/Fedora. ```bash # Debian/Ubuntu: sudo apt install unattended-upgrades # RHEL/Fedora: sudo dnf install dnf-automatic -y && sudo systemctl enable --now dnf-automatic.timer ``` -------------------------------- ### Install TON Libraries for Go Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/wallet.mdx Install the required TON libraries for Go development using go get. This includes the core tonutils-go library and its ADNL and address modules. ```bash go get github.com/xssnick/tonutils-go go get github.com/xssnick/tonutils-go/adnl go get github.com/xssnick/tonutils-go/address ``` -------------------------------- ### Deploy Message Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/smart-contracts/tolk/tolk-vs-func/create-message.mdx Illustrates how to create a message that can be used for deployment by attaching `stateInit`. The message is then sent using `send`. ```tolk val deployMsg = createMessage({ ... }); deployMsg.send(mode); ``` -------------------------------- ### MyTonCtrl 'only-node' mode installation log Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/maintenance-guidelines/mytonctrl-remote-controller.mdx Example log output from the 'only-node' installation, indicating the successful creation of a backup file. This backup is crucial for migrating the node to the controller server. ```text ... [debug] 01.01.2025, 00:00:00.000 (UTC) start CreateSymlinks function Local DB path: /home/user/.local/share/mytoncore/mytoncore.db [info] 01.01.2025, 00:00:00.000 (UTC) start ConfigureOnlyNode function [1/2] Copied files to /tmp/mytoncore/backupv2 [2/2] Backup successfully created in mytonctrl_backup_hostname_timestamp.tar.gz! If you wish to use archive package to migrate node to different machine please make sure to stop validator and mytoncore on donor (this) host prior to migration. [info] 01.01.2025, 00:00:00.000 (UTC) Backup successfully created. Use this file on the controller server with `--only-mtc` flag on installation. [debug] 01.01.2025, 00:00:00.000 (UTC) Start/restart mytoncore service [debug] 01.01.2025, 00:00:00.000 (UTC) sleep 1 sec [5/5] MytonCtrl installation completed ``` -------------------------------- ### Prefix Code Example with Binary Tags Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/data-formats/tlb/overview.mdx Demonstrates constructors 'example_a', 'example_b', 'example_c', and 'example_d' for type 'A', each with a unique binary tag, ensuring a prefix code. ```tlb example_a$10 = A; example_b$01 = A; example_c$11 = A; example_d$00 = A; ``` -------------------------------- ### Install MyTonCtrl in 'only-node' mode Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/maintenance-guidelines/mytonctrl-remote-controller.mdx Installs MyTonCtrl in validator mode on the node server, enabling 'only-node' mode. This command also creates a backup archive required for the controller server setup. ```bash wget https://raw.githubusercontent.com/ton-blockchain/mytonctrl/master/scripts/install.sh sudo bash install.sh -m validator -l ``` -------------------------------- ### Check if a plugin is installed using JavaScript Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/wallet.mdx Checks if a specific plugin is installed on a TON wallet by calling the `is_plugin_installed` GET method. It converts the plugin address to a hash and passes it along with the workchain ID. ```javascript const hash = BigInt(`0x${subscriptionAddress.address.hash.toString("hex")}`); getResult = await client.runMethodWithError( oldWalletAddress, "is_plugin_installed", [ { type: "int", value: BigInt("0") }, // pass workchain as int { type: "int", value: hash }, // pass plugin address hash as int ] ); console.log(getResult.stack.readNumber()); // -1 ``` -------------------------------- ### Get Jetton Wallet Data Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/cookbook/jetton-transfer.mdx An example demonstrating how to connect to the TON client and retrieve data for a specific Jetton wallet address using the `get_wallet_data` method. This requires an API key and endpoint. ```typescript import { Address, TonClient, beginCell, StateInit, storeStateInit } from '@ton/ton' async function main() { const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', apiKey: 'enter your API key' }) const jettonWalletAddress = Address.parse('Sender_Jetton_Wallet'); let jettonWalletDataResult = await client.runMethod(jettonWalletAddress, 'get_wallet_data'); ``` -------------------------------- ### Example: Create Multisig Key Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/multisig.mdx An example of creating a private key file named 'multisig_key'. This will generate a 'multisig_key.pk' file containing the private key. ```bash fift -s new-key.fif multisig_key ``` -------------------------------- ### Serialize HTTP GET Request for foundation.ton Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/network/protocols/rldp.mdx Example of serializing an http.request TL object for a GET request to 'foundation.ton', including TL ID, random ID, method, URL, HTTP version, and Host header. ```tlb e191b161 -- TL ID http.request 116505dac8a9a3cdb464f9b5dd9af78594f23f1c295099a9b50c8245de471194 -- id = {random} 03 474554 -- method = string `GET` 16 687474703a2f2f666f756e646174696f6e2e746f6e2f 00 -- url = string `http://foundation.ton/` 08 485454502f312e31 000000 -- http_version = string `HTTP/1.1` 01000000 -- headers (1) 04 486f7374 000000 -- name = Host 0e 666f756e646174696f6e2e746f6e 00 -- value = foundation.ton ``` -------------------------------- ### Handle /start Command with Inline Keyboard (JavaScript) Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-js.mdx Defines the handler for the /start command, which sends a welcome message and an inline keyboard. The keyboard includes options to buy and a link to the tutorial. ```javascript import { InlineKeyboard } from "grammy"; export default async function handleStart(ctx) { const menu = new InlineKeyboard() .text("Buy dumplings🥟", "buy") .row() .url("Article with a detailed explanation of the bot's work", "docs.ton.org/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot-js"); await ctx.reply( `Hello stranger!\nWelcome to the best Dumplings Shop in the world and concurrently an example of accepting payments in TON `, { reply_markup: menu, parse_mode: "HTML" } ); } ``` -------------------------------- ### Start Storage Daemon Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/web3/ton-storage/storage-daemon.mdx Launches the storage daemon with specified configuration. Ensure you have the global config file downloaded. ```bash storage-daemon -v 3 -C global.config.json -I :3333 -p 5555 -D storage-db ``` -------------------------------- ### Check if a plugin is installed using Go Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/wallet.mdx Checks if a specific plugin is installed on a TON wallet by calling the `is_plugin_installed` GET method. It converts the plugin address to a byte slice and passes it along with the workchain ID. ```go import ( "math/big" ) hash := big.NewInt(0).SetBytes(subscriptionAddress.Data()) // runGetMethod will automatically identify types of passed values getResult, err = client.RunGetMethod(context.Background(), block, oldWalletAddress, "is_plugin_installed", 0, // pass workchain hash) // pass plugin address if err != nil { log.Fatalln("RunGetMethod err:", err.Error()) return } log.Println(getResult.MustInt(0)) // -1 ``` -------------------------------- ### /start Command Handler Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/telegram-bot-examples/accept-payments-in-a-telegram-bot.mdx Handles the /start command, checks if the user is new or existing in the database, and sets the bot's state to firstState. Displays the current WORKMODE. ```python @dp.message_handler(commands=['start'], state='*') async def cmd_start(message: types.Message): await message.answer(f"WORKMODE: {WORK_MODE}") # check if user is in database. if not, add him isOld = db.check_user( message.from_user.id, message.from_user.username, message.from_user.first_name) # if user already in database, we can address him differently if isOld == False: await message.answer(f"You are new here, {message.from_user.first_name}!") await message.answer(f"to buy air send /buy") else: await message.answer(f"Welcome once again, {message.from_user.first_name}!") await message.answer(f"to buy more air send /buy") await DataInput.firstState.set() ``` -------------------------------- ### Valid Function Name Examples Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/smart-contracts/func/docs/functions.mdx Demonstrates valid function names in FunC, including those starting with '.' or '~' which have special meanings. ```func udict_add_builder? dict_set ~dict_set ``` -------------------------------- ### Start Project Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/nft-minting-guide.mdx Executes the command to start the project, typically launching the application or script that utilizes the NFT minting and sale functionalities. ```bash yarn start ``` -------------------------------- ### Clone Vanilla JS Boilerplate Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tma/tutorials/app-examples.mdx Clone the repository to get a minimalistic starting point for your TMA. Navigate to the project directory after cloning. ```bash git clone https://github.com/Telegram-Mini-Apps-Dev/vanilla-js-boilerplate.git ``` ```bash cd vanilla-js-boilerplate ``` -------------------------------- ### Clone and Setup snarkjs Repo Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/zero-knowledge-proofs.mdx Clones the adjusted snarkjs repository and installs its dependencies. This repository is specifically modified to support FunC contracts. ```bash git clone https://github.com/kroist/snarkjs.git cd snarkjs npm ci cd ../simple-zk ``` -------------------------------- ### Initialize npm Project Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/nft-minting-guide.mdx Initializes a new Node.js project with default settings. ```bash npm init -y ``` -------------------------------- ### Get Total from Contract Data Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/get-methods.mdx Loads and returns a 32-bit number stored in the contract's data. This is a simple example of reading data from a contract. ```func (int) get_total() method_id { return get_data().begin_parse().preload_uint(32); ;; load and return the 32-bit number from the data } ``` -------------------------------- ### Clone and Run TON Connect React UI Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/quick-start.mdx Clone the official react-ui-example repository to run a local demo of TON Connect. This is useful for testing transactions with real TON. ```bash git clone https://github.com/memearchivarius/react-ui-example.git cd react-ui-example npm install npm run dev # default on http://localhost:5173 ``` -------------------------------- ### Setup Collator with ADNL Address and Shards Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/running-nodes/collators-validators.mdx Example command to set up a collator, specifying an existing ADNL address and the shards it should monitor and collate blocks for. ```bash setup_collator --adnl 5889072E81219A0E656F31E8784EA09C93A562AA74308E1B25364EE87EEE6631 0:2000000000000000 0:6000000000000000 ``` -------------------------------- ### Build and Serve Project Locally Source: https://github.com/ton-community/ton-docs/blob/main/README.md Use these commands to build the project with multiple locales and then serve it locally. This is useful for testing the production build before deployment. ```bash npm run build npm run serve ``` -------------------------------- ### Get Masterchain Info Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/apis-sdks/nownodes-ton-api.mdx This example shows how to retrieve the current masterchain state using the NOWNodes API. It requires your API key and specifies the endpoint for this query. ```APIDOC ## GET /getMasterchainInfo ### Description Retrieves the current masterchain state information. ### Method GET ### Endpoint https://ton.nownodes.io/getMasterchainInfo ### Parameters #### Headers - **api-key** (string) - Required - Your NOWNodes API key. - **Content-Type** (string) - Required - application/json ### Request Example ```bash curl --location 'https://ton.nownodes.io/getMasterchainInfo' \ --header 'api-key: YOUR_API_KEY' \ --header 'Content-Type: application/json' ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **result** (object) - Contains the masterchain information. - **@type** (string) - Type of the result, e.g., "blocks.masterchainInfo". - **last** (object) - Information about the last block. - **@type** (string) - Type of the block ID, e.g., "ton.blockIdExt". - **workchain** (integer) - The workchain ID. - **shard** (string) - The shard ID. - **seqno** (integer) - The sequence number of the block. - **root_hash** (string) - The root hash of the block. - **file_hash** (string) - The file hash of the block. - **state_root_hash** (string) - The root hash of the current state. - **init** (object) - Initial block information. - **@type** (string) - Type of the block ID, e.g., "ton.blockIdExt". - **workchain** (integer) - The workchain ID. - **shard** (string) - The shard ID. - **seqno** (integer) - The sequence number of the block. - **root_hash** (string) - The root hash of the block. - **file_hash** (string) - The file hash of the block. - **@extra** (string) - Additional information. #### Response Example ```json { "ok": true, "result": { "@type": "blocks.masterchainInfo", "last": { "@type": "ton.blockIdExt", "workchain": -1, "shard": "-9223372036854775808", "seqno": 52266460, "root_hash": "uQzcsabTYGT9rO4yF+ZxIhdAWIpOkq/bSvVBs90NG9c=", "file_hash": "nPP70Hz95nRRze16USISEzlB15obheSQ23FrWuIK36U=" }, "state_root_hash": "gTl/1j0sZukHTBI8yLPkBtp7g5wo4Kq+Lz6BCv+GEZw=", "init": { "@type": "ton.blockIdExt", "workchain": -1, "shard": "0", "seqno": 0, "root_hash": "F6OpKZKqvqeFp6CQmFomXNMfMj2EnaUSOXN+Mh+wVWk=", "file_hash": "XplPz01CXAps5qeSWUtxcyBfdAo5zVb1N979KLSKD24=" }, "@extra": "1758640859.1752262:6:0.6899334555338705" } } ``` ``` -------------------------------- ### Full blueprint.config.ts Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/testing/blueprint-config.mdx This example demonstrates a comprehensive configuration including plugins, network settings (endpoint, version, type, key), compilation options, timeouts, and manifest URL. Secrets like API keys should be stored in environment variables. ```typescript import { Config } from '@ton/blueprint'; import { ScaffoldPlugin } from 'blueprint-scaffold'; export const config: Config = { plugins: [new ScaffoldPlugin()], network: { endpoint: 'https://toncenter.com/api/v2/jsonRPC', version: 'v2', type: 'mainnet', key: process.env.TONCENTER_KEY, // keep secrets in env vars }, separateCompilables: true, recursiveWrappers: true, requestTimeout: 15_000, // 15 seconds manifestUrl: 'https://example.com/my-dapp/manifest.json', }; ``` -------------------------------- ### Setup Master Wallet with Assets CLI Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/web3-game-example.mdx Initialize your environment and create a master wallet using the assets-cli. This wallet will manage jettons, NFTs, SBTs, and receive payments. Ensure you select 'testnet' for the network and 'highload-v2' for the wallet type. ```sh assets-cli setup-env ``` -------------------------------- ### Retrieve Conditional Data: Get Ready Status Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/get-methods.mdx This pattern retrieves data based on specific conditions, such as the current time. This example checks if a certain timestamp has passed. ```func (int) get_ready_to_be_used() method_id { int ready? = now() >= 1686459600; return ready?; } ``` -------------------------------- ### Start Storage Daemon CLI Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/web3/ton-storage/storage-daemon.mdx Initializes the storage daemon command-line interface, connecting to the running daemon. Key paths for client and server are required. ```bash storage-daemon-cli -I 127.0.0.1:5555 -k storage-db/cli-keys/client -p storage-db/cli-keys/server.pub ``` -------------------------------- ### Get Account State with TON SDK Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/quick-start/blockchain-interaction/reading-from-network.mdx Fetches and logs the state, balance, data, and code of a TON account using the TonClient. Replace the example address with your Testnet address. ```typescript 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', }); // Replace with your Testnet address const accountAddress = Address.parse('0QD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje04A-'); // Calling tonClient.getContractState(), which corresponds to TON Center’s getAddressInformation endpoint 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(); ``` -------------------------------- ### Install UFW and JQ Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/node-maintenance-and-security.mdx Install the Uncomplicated Firewall (UFW) and jq JSON processor using apt. These tools are essential for network security configuration. ```sh sudo apt install -y ufw jq ``` -------------------------------- ### Deployment Output Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/dapps/tutorials/mint-your-first-token.mdx This output shows a successful deployment of a Jetton token, including the contract address, transaction details, and a post-deployment test result confirming the token's metadata. ```text > @ton-defi.org/jetton-deployer-contracts@0.0.2 deploy > ts-node ./build/_deploy.ts ================================================================= Deploy script running, let's find some contracts to deploy.. - We are working with 'mainnet' - Config file '.env' found and will be used for deployment! - Wallet address used to deploy from is: YOUR-ADDRESS - Wallet balance is YOUR-BALANCE TON, which will be used for gas - Found root contract 'build/jetton-minter.deploy.ts - let's deploy it': - Based on your init code+data, your new contract address is: YOUR-ADDRESS - Let's deploy the contract on-chain. - Deploy transaction sent successfully - Block explorer link: https://tonwhales.com/explorer/address/YOUR-ADDRESS - Waiting up to 20 seconds to check if the contract was actually deployed. - SUCCESS! Contract deployed successfully to address: YOUR-ADDRESS - New contract balance is now YOUR-BALANCE TON, make sure it has enough to pay rent - Running a post deployment test: { name: 'MyJetton', description: 'My jetton', image: 'https://www.linkpicture.com/q/download_183.png', symbol: 'JET1' } ``` -------------------------------- ### Parse Data from a Cell - TypeScript Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/cookbook/cells.mdx Use `beginParse()` on a cell to get a slice, then use `load...()` functions in the same order data was stored. This example loads an unsigned integer, an address, and coins. ```typescript const slice = cell.beginParse(); const uint = slice.loadUint(64); const address = slice.loadAddress(); const coins = slice.loadCoins(); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/ton-community/ton-docs/blob/main/README.md Run this command to start a local development server. The server will automatically open in your browser, and most changes will reflect live without requiring a server restart. ```bash npm run start ``` -------------------------------- ### Fetching NFT Metadata with TonWeb Source: https://context7.com/ton-community/ton-docs/llms.txt Retrieve on-chain or off-chain metadata for TON NFTs using the TonWeb SDK. This example shows how to get data for both individual NFT items and NFT collections. ```javascript import TonWeb from "tonweb"; const tonweb = new TonWeb(); // NFT Item contract – get_nft_data() const nftItem = new TonWeb.token.nft.NftItem(tonweb.provider, { address: 'EQ_ITEM_ADDRESS', }); const nftData = await nftItem.getData(); console.log('Initialized:', nftData.isInitialized); console.log('Index:', nftData.index); console.log('Collection:', nftData.collectionAddress?.toString(true, true, true)); console.log('Owner:', nftData.ownerAddress?.toString(true, true, true)); console.log('Content:', nftData.contentUri); // off-chain URI or on-chain cell // NFT Collection – get_collection_data() const nftCollection = new TonWeb.token.nft.NftCollection(tonweb.provider, { address: 'EQ_COLLECTION_ADDRESS', }); const collData = await nftCollection.getCollectionData(); console.log('Next item index:', collData.nextItemIndex); console.log('Collection content:', collData.collectionContentUri); console.log('Owner:', collData.ownerAddress?.toString(true, true, true)); ``` -------------------------------- ### Get Jetton Wallet Data Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/cookbook/jetton-transfer.mdx Retrieves data for a Jetton wallet, including its owner's address, using the `get_wallet_data` method. This is useful for preparing transaction details or verifying wallet information. ```typescript import { Address, TonClient, beginCell, StateInit, storeStateInit } from '@ton/ton' async function main() { const client = new TonClient({ endpoint: 'https://toncenter.com/api/v2/jsonRPC', apiKey: 'enter your API key' }) const jettonWalletAddress = Address.parse('Sender_Jetton_Wallet'); let jettonWalletDataResult = await client.runMethod(jettonWalletAddress, 'get_wallet_data'); jettonWalletDataResult.stack.readNumber(); const ownerAddress = jettonWalletDataResult.stack.readAddress(); ``` -------------------------------- ### Prefix Code Example with Hex Tags Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/data-formats/tlb/overview.mdx Illustrates constructors 'example_a', 'example_b', and 'example_c' for type 'A', each with a unique hexadecimal tag, adhering to the prefix code rule. ```tlb example_a#0 = A; example_b#1 = A; example_c#f = A; ``` -------------------------------- ### Create a Cell with Data - TypeScript Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/ton-connect/cookbook/cells.mdx Use `beginCell()` to start building a cell and `store...()` functions to add data. Close the cell with `endCell()`. This example stores an unsigned integer, an address, and coins. ```typescript import { Address, beginCell } from "@ton/core"; const cell = beginCell() .storeUint(99, 64) // Stores uint 99 in 64 bits .storeAddress(Address.parse("EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c")) // Stores an address .storeCoins(123) // Stores 123 as coins .endCell(); // Closes the cell ``` -------------------------------- ### Fift Hello World Example Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/smart-contracts/fift/overview.mdx A basic 'Hello World' example demonstrating Fift syntax for string manipulation and execution. This snippet is useful for understanding fundamental Fift operations. ```fift { ."hello " } execute ."world" hello world ok ``` -------------------------------- ### Installing TON Full Node with MyTonCtrl Source: https://context7.com/ton-community/ton-docs/llms.txt Automate the setup of a TON full node on Ubuntu/Debian using the MyTonCtrl script. Supports mainnet and testnet configurations, with options for faster sync and custom settings. ```bash # Step 1: Create and switch to a non-root user (required) sudo adduser tonnode sudo usermod -aG sudo tonnode ssh tonnode@ # Step 2: Download and run the MyTonCtrl installation script wget https://raw.githubusercontent.com/ton-blockchain/mytonctrl/master/scripts/install.sh # Mainnet full node (default): sudo bash install.sh # Testnet liteserver (example with flags): sudo bash install.sh -m liteserver -c https://ton.org/testnet-global.config.json # Flags: # -d download blockchain state dump (faster initial sync) # -m validator | liteserver # -c custom global config URL # -t disable telemetry # Step 3: Start MyTonCtrl and check status mytonctrl status # Mainnet # status fast # Testnet ``` -------------------------------- ### Constructor Tagging Examples Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/data-formats/tlb/overview.mdx Demonstrates various ways to specify constructor tags, including hex, binary, and implicit or empty tags. ```tlb some#3f5476ca a:(## 32) = AMultiTagInt; b#1111 a:(## 32) = AMultiTagInt; c#5FE a:(## 32) = AMultiTagInt; d#3F5476CA a:(## 32) = AMultiTagInt; ``` -------------------------------- ### Calculate Election Periods (Mainnet Example) Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/network/config-params/overview.mdx Demonstrates how to calculate election start, end, and hold periods based on a given election ID and predefined constants. This calculation is essential for understanding the timing of network elections. ```python election_id = 1600032768 constants = { 'elections_start_before': 32768, 'elections_end_before': 8192, 'validators_elected_for': 65536, 'stake_held_for': 32768 } election_start = election_id - constants['elections_start_before'] election_end = election_id - constants['elections_end_before'] hold_start = election_id + constants['validators_elected_for'] hold_end = hold_start + constants['stake_held_for'] ``` -------------------------------- ### Build Project with Blueprint Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/documentation/smart-contracts/contracts-specs/vesting-contract.mdx Use this command to build the project with the blueprint tool. It's essential for compiling smart contracts and preparing them for deployment. ```bash npx blueprint build yarn blueprint build ``` -------------------------------- ### Retrieve Computed Data: Get Wallet Address Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/get-methods.mdx Use this pattern when the desired data is not stored directly but needs to be calculated based on the contract's state and input arguments. This example calculates a user's Jetton wallet address. ```func slice get_wallet_address(slice owner_address) method_id { (int total_supply, slice admin_address, cell content, cell jetton_wallet_code) = load_data(); return calculate_user_jetton_wallet_address(owner_address, my_address(), jetton_wallet_code); } ``` -------------------------------- ### Querying TON Center HTTP API (REST) Source: https://context7.com/ton-community/ton-docs/llms.txt Interact with the TON Center REST API to fetch account information, transaction history, and run smart contract get methods. Also includes an example for sending external messages. ```bash # Get account information (balance, state, code, data) curl "https://toncenter.com/api/v2/getAddressInformation?address=EQD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje02Zx" # Get last N transactions for an account curl "https://toncenter.com/api/v2/getTransactions?address=EQD-SuoCHsCL2pIZfE8IAKsjc0aDpDUQAoo-ALHl2mje02Zx&limit=10" # Run a get method (e.g. get_wallet_address on a Jetton master) curl -X POST "https://toncenter.com/api/v3/runGetMethod" \ -H "Content-Type: application/json" \ -d '{ "address": "EQD0GKBM8ZbryVk2aESmzfU6b9b_8era_IkvBSELujFZPsyy", "method": "get_wallet_address", "stack": [{"type":"slice","value":""}] }' # Send an external message (signed transaction BoC in base64) curl -X POST "https://toncenter.com/api/v2/sendBoc" \ -H "Content-Type: application/json" \ -d '{"boc": ""}' ``` -------------------------------- ### Log in as new user Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/nodes/running-nodes/full-node.mdx Connect to the server using the new non-root user account. Ensure you stop the current root session and reconnect with the correct user credentials. ```bash ssh @ ``` -------------------------------- ### Run Lite Client with Config Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/howto/compile/compilation-instructions.mdx Launches the TON Lite Client, connecting to a full node using the specified global configuration file. ```bash ./lite-client/lite-client -C global.config.json ``` -------------------------------- ### Example TON Smart Contract with Get Method Source: https://github.com/ton-community/ton-docs/blob/main/docs/v3/guidelines/smart-contracts/get-methods.mdx This contract demonstrates handling internal messages for updating and querying a number. Op-code 1 updates the number, op-code 2 queries it and sends a response, and op-code 3 is used in the response message. ```func #include "imports/stdlib.fc"; int get_total() method_id { return get_data().begin_parse().preload_uint(32); } () recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure { if (in_msg_body.slice_bits() < 32) { return (); } slice cs = in_msg_full.begin_parse(); cs~skip_bits(4); slice sender = cs~load_msg_addr(); int op = in_msg_body~load_uint(32); ;; load the operation code if (op == 1) { ;; increase and update the number int number = in_msg_body~load_uint(32); int total = get_total(); total += number; set_data(begin_cell().store_uint(total, 32).end_cell()); } elseif (op == 2) { ;; query the number int total = get_total(); send_raw_message(begin_cell() .store_uint(0x18, 6) .store_slice(sender) .store_coins(0) .store_uint(0, 107) ;; default message headers .store_uint(3, 32) ;; response operation code .store_uint(total, 32) ;; the requested number .end_cell(), 64); } } ```