Building on TON
A comprehensive developer's guide to The Open Network
Learn how to leverage FunC and Fift to build scalable dApps and smart contracts on TON's multi-blockchain platform.
In This Guide
What is TON?
A high-performance, scalable multi-blockchain platform
Multi-Blockchain Architecture
TON is designed as a collection of blockchains, including a masterchain and multiple workchains. Workchains can have different rules and virtual machines, offering flexibility and specialization. This architecture allows for high scalability and adaptability.
Why Build on TON?
Developers choose TON for its scalability, speed, low transaction fees, and its Turing-complete smart contract capabilities. TON's unique architecture enables it to handle millions of transactions per second.
Architecture & Components
Key components include the Masterchain (coordination and governance), Workchains (customizable blockchains), Shardchains (partitions of workchains for scalability), and the TON Virtual Machine (TVM) for executing smart contracts. TON uses a Proof-of-Stake (PoS) consensus mechanism.
Development Ecosystem
TON development primarily uses FunC for high-level smart contract programming and Fift for low-level operations and assembly. The TON SDK (available in multiple languages) provides tools for interacting with the TON blockchain.
Understanding TON's Architecture
The technical components that make up The Open Network
The FunC Programming Language
Technical components of the high-level language for TON smart contracts
Statically Typed
FunC is a statically-typed language, meaning that the types of variables are checked at compile time. This helps catch errors early and improves code safety. Type inference is also supported, reducing the need for explicit type annotations.
Functional Paradigm
FunC is primarily a functional language, encouraging the use of pure functions and immutable data. This makes it easier to reason about code and reduces the risk of side effects. Functional programming principles are well-suited for smart contract development.
TVM-Oriented
FunC is specifically designed for the TON Virtual Machine (TVM). Its features and syntax are tailored to the capabilities of TVM, making it efficient and easy to compile to TVM bytecode. The language provides direct access to TVM primitives.
Algebraic Data Types
FunC supports algebraic data types (ADTs), allowing developers to define custom data structures. ADTs provide a powerful way to represent complex data and ensure type safety. They are commonly used for defining message structures and contract state.
Tuples and Cells
Fundamental data types in FunC include Tuples and Cells. Tuples are ordered collections of values, while Cells are the basic building blocks of data storage on TON. Understanding Cells and how to manipulate them is crucial for FunC programming.
Standard Library
FunC has a standard library that provides functions for common operations, such as working with cells, cryptography, and interacting with the blockchain. The standard library simplifies development and promotes code reuse.
Inline Assembly (Fift)
FunC allows for inline Fift assembly code, giving developers low-level control when needed. This is useful for optimizing performance-critical parts of a smart contract or accessing specific TVM features. However, it should be used sparingly to maintain code readability and safety.
Compiler
The FunC compiler translates FunC code into Fift assembly code, which is then assembled into TVM bytecode. The compiler performs type checking, optimizations, and other tasks to ensure the correctness and efficiency of the generated code.
The Fift Assembly Language
Technical components of the low-level language for TON
Stack-Based
Fift is a stack-based language, meaning that operations are performed on a stack of values. This is similar to other virtual machine languages like Forth and PostScript. Understanding the stack is crucial for writing Fift code.
TVM Instructions
Fift provides direct access to the instructions of the TON Virtual Machine (TVM). Each Fift word corresponds to a TVM instruction or a sequence of instructions. This allows for fine-grained control over the execution of smart contracts.
Data Manipulation
Fift provides words for manipulating data on the stack, including arithmetic operations, logical operations, and bitwise operations. It also provides words for working with cells, which are the fundamental data storage units on TON.
Control Flow
Fift supports control flow structures like conditional statements (`IF`, `IFELSE`, `THEN`) and loops (`WHILE`, `UNTIL`, `REPEAT`). These allow for creating complex logic in Fift programs.
Debugging
Fift includes debugging features, such as the ability to print values from the stack and trace the execution of code. This helps developers identify and fix errors in their Fift programs.
Assembler and Disassembler
The Fift assembler translates Fift code into TVM bytecode, and the Fift disassembler translates TVM bytecode back into Fift code. These tools are essential for working with Fift and understanding the low-level behavior of TON smart contracts.
Used for Booting Contracts
Fift is often used to create the initial state (or 'bootcode') of a smart contract. This includes setting up the contract's data and code. The Fift code is executed to initialize the contract's storage.
Cryptography Support
Fift includes words for cryptographic operations, such as hashing and digital signatures. This is essential for securing smart contracts and verifying the authenticity of transactions. TON uses the Ed25519 signature scheme.
TL-B Schema
Defining data structures and message formats on TON
Type Language - Base
TL-B (Type Language - Base) is a language for describing data structures and message formats used in TON. It's similar to Protocol Buffers or Thrift. TL-B schemas define how data is serialized and deserialized for storage and communication.
Combinators
TL-B uses *combinators* to define data types and constructors. A combinator specifies the name, type, and serialization format of a data structure. Combinators are used to build complex data types from simpler ones.
Constructors
Constructors are specific instances of a combinator, defining concrete data structures. For example, a `user` combinator might have constructors for different types of user profiles. Each constructor has a unique tag that identifies it during serialization and deserialization.
Serialization and Deserialization
TL-B schemas define how data is serialized (converted to a byte stream) and deserialized (converted from a byte stream back to a data structure). This ensures that data can be stored and transmitted consistently across the network. The serialization format is compact and efficient.
Message Layouts
TL-B is used to define the layout of messages in TON. Messages are used for all interactions, including transactions and smart contract calls. The TL-B schema specifies the format of the message body and how it should be interpreted.
Data Structures for Contracts
TL-B schemas also define the data structures used in smart contracts, including their persistent storage. This ensures consistency between the contract's code and its data. The schema specifies how the contract's state is stored in cells.
Generating Code
Tools exist to automatically generate code (e.g., in FunC) from TL-B schemas. This simplifies development by eliminating the need to manually write serialization and deserialization logic. The generated code ensures that the data is handled according to the TL-B schema.
Example Usage
A simple TL-B schema for a message might look like: `message#1234 data:bytes = Message;`. This defines a message with a constructor tag `#1234` and a data field of type `bytes`.
TON Messages
Understanding message types and their role in TON communication
Smart Contract Development
Building with FunC and Fift on TON
Development Tools
Essential tools for building on TON
TON SDKs
TON provides SDKs in multiple programming languages, including Python, JavaScript, C++, Go, and Java. These SDKs provide libraries for interacting with the TON blockchain, creating transactions, and managing accounts. The SDKs simplify the development of client applications that interact with TON.
FunC Compiler
The FunC compiler translates FunC code into Fift assembly code. It performs type checking, optimizations, and other tasks to ensure the correctness and efficiency of the generated code. The compiler is an essential tool for FunC development.
Fift Assembler/Disassembler
The Fift assembler translates Fift code into TVM bytecode, and the Fift disassembler does the reverse. These tools are essential for working with Fift and understanding the low-level behavior of TON smart contracts. They are often used in conjunction with the FunC compiler.
TON Lib
tonlib (TON Library) is a low-level C++ library that provides a direct interface to the TON blockchain. It's used by many of the higher-level SDKs and provides the core functionality for interacting with TON. It's useful for advanced development and building custom tools.
Local Testnet
Developers can run a local instance of the TON blockchain for testing and development. This allows for rapid iteration and experimentation without needing to connect to the public testnet or mainnet. The local testnet simulates the behavior of the TON network and provides a controlled environment.
TON Blockchain Explorer
TON blockchain explorers (e.g., tonscan.org, ton.live) allow you to view transactions, accounts, and smart contracts on the TON blockchain. Explorers are valuable tools for debugging and understanding the state of the network. They provide a visual representation of blockchain activity.
IDE Extensions
IDE extensions (e.g., for Visual Studio Code) provide syntax highlighting, code completion, and other helpful features for FunC and Fift development. These extensions improve developer productivity and help catch errors early.
Blueprint
Blueprint is a development environment and framework for building, testing, and deploying TON smart contracts. It simplifies common tasks and provides a standardized workflow for TON development, making it easier to create and manage complex projects.
toncli
toncli is a command-line tool that simplifies various aspects of TON development, including project initialization, building, testing, and deploying smart contracts. It provides a convenient interface for interacting with the TON blockchain and managing development workflows.
Testing & Deployment
Best practices for validating and launching TON applications
Gas & TON Economics
Understanding gas fees, TON Crystal, and economic incentives
Gas on TON
Gas is a unit of measurement for the computational resources used to execute operations on the TON blockchain. Every operation in a smart contract consumes a certain amount of gas. The gas cost is calculated based on the complexity of the operation and the amount of storage used. Transactions specify a gas limit, and if the limit is exceeded, the transaction fails.
TON Crystal (TON)
TON Crystal (often abbreviated as TON) is the native cryptocurrency of The Open Network. It is used to pay for transaction fees (gas), storage fees, and to participate in the Proof-of-Stake consensus mechanism. TON is also used for cross-chain transfers and other network operations.
Transaction Fees
Transaction fees on TON are calculated based on the gas consumed by the transaction and the current gas price. The gas price can fluctuate based on network demand. Transaction fees are paid in TON Crystal and are distributed to the validators who process the transaction.
Storage Fees
TON charges fees for storing data on the blockchain. The storage fees are proportional to the amount of data stored and the duration of storage. This incentivizes efficient storage usage and helps prevent state bloat. Storage fees are paid in TON Crystal.
Proof-of-Stake Rewards
Validators who participate in the Proof-of-Stake consensus mechanism earn rewards in TON Crystal. The rewards are proportional to the amount of TON Crystal staked by the validator. This incentivizes validators to act honestly and maintain the security of the network.
Economic Model
TON's economic model is designed to be sustainable and to align incentives among all participants (users, developers, validators). The combination of transaction fees, storage fees, and staking rewards aims to create a balanced ecosystem where users pay for the resources they consume and validators are rewarded for securing the network.
Gas Calculation in TVM
The TON Virtual Machine (TVM) calculates gas consumption during the execution of smart contracts. Each TVM instruction has a predefined gas cost. The TVM keeps track of the total gas consumed and aborts the execution if the gas limit is reached.
Forwarding Fees
When a smart contract sends a message, it can include a 'forwarding fee' to cover the cost of processing the message by the recipient contract. This ensures that the recipient contract has enough gas to process the incoming message. The forwarding fee is part of the message value and is transferred to the recipient contract.
Security Best Practices
Protecting your applications in the TON ecosystem
FunC/Fift Security Considerations
When writing smart contracts in FunC or Fift, be aware of common security vulnerabilities. Avoid integer overflows/underflows, handle errors properly, and validate all inputs. Use the available tools (e.g., static analyzers) to check your code for potential issues. Be mindful of reentrancy attacks, although TON's message-passing model mitigates some risks.
Message Validation
Carefully validate all incoming messages to your smart contracts. Check the sender's address, the message value, and the message body. Ensure that the message conforms to the expected format (defined by the TL-B schema). Reject any invalid or unexpected messages.
Access Control
Implement appropriate access control to restrict who can modify the state of your smart contract. Use the sender's address and other message data to determine whether the sender is authorized to perform the requested operation. Consider using role-based access control or other access control mechanisms.
State Management
Manage the state of your smart contract carefully. Avoid unnecessary state changes and minimize the amount of data stored on-chain. Be aware of the potential for state bloat and design your contract to use storage efficiently. Understand how storage fees work and factor them into your design.
Error Handling
Handle errors gracefully in your smart contracts. Use FunC's `throw` and `throw_if` statements to signal errors and revert state changes if something goes wrong. Return informative error codes to help users understand why a transaction failed. Avoid silent failures that can lead to unexpected behavior.
Auditing and Testing
Thoroughly test your smart contracts with unit tests, integration tests, and end-to-end tests. Consider conducting security audits by independent experts to identify potential vulnerabilities. Testing is crucial for ensuring the correctness and security of your code.
Gas Limits
Be mindful of gas limits when designing your smart contracts. Avoid operations that consume excessive amounts of gas, as they may cause transactions to fail. Optimize your code to minimize gas consumption. Consider the potential for denial-of-service attacks that try to exhaust your contract's gas.
External Libraries
If you use external libraries in your smart contracts, ensure that they are well-vetted and secure. Review the code of any external libraries before using them. Be aware of the potential for supply chain attacks, where a malicious library could compromise your contract.
Formal Verification
Consider using formal verification techniques to prove the correctness of your smart contracts. Formal verification can help identify subtle bugs and ensure that your code behaves as intended. While not yet widespread for TON development, tools and techniques are emerging.
Real-World Examples
Success stories and use cases from the TON ecosystem
TON DNS
TON DNS is a decentralized domain name system built on TON. It allows users to register human-readable domain names (e.g., `example.ton`) and associate them with TON addresses. TON DNS is implemented as a set of smart contracts that manage the domain name registry.
TON Payments
TON Payments is a payment channel network built on TON. It allows users to make fast and cheap off-chain payments without needing to record every transaction on the blockchain. Payment channels are useful for micropayments and other high-frequency transactions.
TON Storage
TON Storage is a decentralized file storage system built on TON. It allows users to store and retrieve files in a secure and censorship-resistant manner. TON Storage is similar to IPFS or Filecoin but is integrated with the TON blockchain.
TON Proxy
TON Proxy is a decentralized VPN and proxy service built on TON. It allows users to access the internet anonymously and securely, bypassing censorship and surveillance. TON Proxy uses the TON network to route traffic and provide anonymity.
Jettons (Fungible Tokens)
Many projects on TON are creating their own fungible tokens (Jettons) for various purposes, such as in-game currencies, utility tokens, and governance tokens. These Jettons are implemented as smart contracts that follow the TON Jetton standard.
NFTs (Non-Fungible Tokens)
NFTs are gaining popularity on TON, with projects creating digital art, collectibles, and game items. TON's NFT standard provides a framework for creating and managing unique digital assets.
Decentralized Exchanges (DEXs)
Several decentralized exchanges (DEXs) are being built on TON, allowing users to trade TON Crystal and Jettons without relying on centralized intermediaries. These DEXs are implemented as smart contracts that facilitate token swaps.
Gaming Applications
TON's high throughput and low fees make it suitable for gaming applications. Developers are building games that leverage TON for in-game items (NFTs), currencies (Jettons), and other blockchain-based features.
Future of TON
Upcoming developments and the roadmap for the ecosystem
Frequently Asked Questions
Common questions about developing on TON
Additional Resources
Essential links and tools for TON developers
TON Documentation
Official documentation covering all aspects of TON, including architecture, development, and tutorials.
FunC Documentation
Documentation and examples for the FunC programming language.
Fift Book
Guide to the Fift assembly language.
TL-B Documentation
Documentation for the TL-B schema language.
TON SDKs
Links to the various TON SDKs (Python, JavaScript, C++, etc.).
TON GitHub
TON's official GitHub repositories.
TON Community
Links to TON developer communities (Telegram groups, forums).
toncli
Command-line tool for TON development.
Blueprint
Development environment and framework for TON smart contracts.
Awesome TON
A curated list of awesome TON libraries, tools, and resources.
Ready to Build on TON?
Take the next steps in your TON development journey