
From Risk to Protection: Security Vulnerabilities and Optimization Recommendations for TON Smart Contracts
TechFlow Selected TechFlow Selected

From Risk to Protection: Security Vulnerabilities and Optimization Recommendations for TON Smart Contracts
This article will provide a detailed analysis of smart contract-related features on the TON blockchain, as well as commonly overlooked vulnerabilities in TON smart contracts.
Author: Beosin
As blockchain technology rapidly evolves, TON (The Open Network) has emerged as a highly efficient and flexible blockchain platform, drawing increasing attention from developers. TON's unique architecture and features offer powerful tools and rich possibilities for building decentralized applications.
However, as functionality and complexity grow, the security of smart contracts becomes increasingly critical. FunC, the smart contract programming language on TON, is known for its flexibility and efficiency, but it also introduces many potential risks and challenges. Writing secure and reliable smart contracts requires developers to have a deep understanding of FunC’s language characteristics and associated vulnerabilities.
This article provides an in-depth analysis of key smart contract-related features on the TON blockchain, along with commonly overlooked vulnerability points in TON smart contracts.

Ton Asynchronous Features and Account Mechanism Explained
Smart Contract Asynchronous Calls
Network Sharding and Asynchronous Communication
The TON blockchain is architecturally divided into three types of chains: the Masterchain, Workingchains, and Shardchains.
The Masterchain serves as the core of the entire network, storing global metadata and managing consensus mechanisms. It records the states of all Workingchains and Shardchains, ensuring consistency and security across the network. Workingchains are independent blockchains—up to 2^32 in number—responsible for processing specific transaction types and smart contracts. Each Workingchain can have its own rules and features tailored to different application needs. Shardchains are sub-chains of Workingchains, further splitting their workload to enhance processing capacity and scalability. Each Workingchain can be divided into up to 2^60 Shardchains, enabling parallel transaction processing by distributing workloads.
Theoretically, each account can occupy its own shard chain. Each account independently maintains its COIN/TOKEN balance, and transactions between accounts can be fully parallelized. Accounts communicate via asynchronous messages, with message routing paths between shard chains calculated as log_16(N) - 1, where N is the number of shard chains.

Image source: https://frontierlabzh.medium.com/ton-web3-worlds-weixin-e1d3ae3b3574
In Ton, smart contracts interact by sending and receiving messages. These messages can be internal (typically sent between smart contracts) or external (originating from outside sources). Message delivery does not require immediate response from the target contract; the sender can continue executing other logic. This asynchronous messaging mechanism offers greater flexibility and scalability compared to Ethereum’s synchronous calls, reducing performance bottlenecks caused by waiting for responses. However, it also introduces challenges in handling concurrency and race conditions.
Message Format and Structure
In Ton, messages typically include fields such as sender, recipient, amount, and message body. The message body may contain function calls, data transfers, or custom content. Ton’s message format is flexible and extensible, enabling efficient transmission of various information types between contracts.
cell msg = begin_cell()
.store_uint(0x18, 6)
.store_slice(addr)
.store_coins(amount)
.store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
.store_slice(message_body)
.end_cell();
Message Queue and State Handling
Each contract maintains a message queue storing unprocessed messages. During execution, the contract processes these messages sequentially. Because message handling is asynchronous, the contract’s state does not update immediately upon message receipt.
Advantages of Asynchronous Messaging
-
Efficient sharding mechanism: Ton's asynchronous design integrates seamlessly with its sharding architecture. Each shard independently handles message processing and state changes, avoiding delays from cross-shard synchronization. This significantly improves network throughput and scalability.
-
Reduced resource consumption: Since asynchronous messages do not require instant replies, contract execution can span multiple blocks, preventing excessive resource usage within a single block. This allows Ton to support more complex and resource-intensive smart contracts.
-
Fault tolerance and reliability: The asynchronous model enhances system resilience. For example, if a contract cannot respond promptly due to resource constraints, the sender can still proceed with other operations, preventing system-wide halts caused by individual delays.
Challenges in Asynchronous Contract Design
-
State consistency issues: Due to asynchronous message delivery, a contract may receive messages at different times, potentially leading to inconsistent states. Developers must carefully manage state transitions and ensure consistency regardless of message order.
-
Race conditions and protections: Asynchronous processing introduces potential race conditions where multiple messages attempt to modify contract state simultaneously. Developers should implement appropriate locking mechanisms or use atomic operations to prevent conflicts.
-
Security considerations: Asynchronous inter-contract communication is vulnerable to man-in-the-middle or replay attacks. When designing asynchronous contracts, developers must address these risks using measures like timestamps, nonces, or multi-signature schemes.
Ledger Model
Ton (The Open Network) employs a unique account abstraction and ledger model in its blockchain infrastructure. This model demonstrates flexibility in managing account states, message passing, and contract execution.
Account Abstraction
Ton’s account model uses contract-based abstraction, where each account functions as a smart contract—a concept similar to Ethereum’s account abstraction but more flexible and general-purpose. In Ton, accounts are not merely asset holders; they encapsulate contract code and state data. Each account consists of Code, Data, and Message Handling logic.
Account structure: Every Ton account has a unique address derived from the hash of its code, initial deployment data, and additional parameters. As a result, identical code and data deployed under different environments (e.g., different chains or shards) may yield different addresses.
Flexibility: Since every account can run custom contract code, Ton supports highly sophisticated logic. Accounts go beyond simple balance storage, enabling complex state transitions, cross-account messaging, and conditional automation. This makes Ton’s account model far more scalable and flexible than traditional blockchain account models.
Ledger Structure
Ton’s ledger is designed for high-performance concurrent transaction processing, supporting asynchronous messaging and multi-shard operations. Account states are stored in Merkle trees, enabling efficient state verification.
State Storage
Account state information is persisted and organized using Merkle trees to ensure integrity and security. This structure enables efficient querying and validation, especially in cross-shard scenarios.
An account or smart contract state typically includes:
-
Balance of base currency
-
Balances of other currencies
-
Smart contract code (or its hash)
-
Persistent data of the smart contract (or its Merkle hash)
-
Statistics on used storage cells and raw byte counts
-
Last payment time for persistent storage (effectively a masterchain block number)
-
Public key required to transfer funds and send messages from this account (optional; defaults to account_id itself). In some cases, more complex signature verification logic—similar to Bitcoin transaction outputs—can be embedded here, making account_id equal to the hash of that code.
Not all information is required for every account. For instance, smart contract code applies only to contracts, not "simple" accounts. While every account must maintain a non-zero balance of the primary currency (e.g., Grams on the mainchain or shardchains), balances of other currencies may be zero. To avoid storing unused data, a sum-product type is defined during Workingchain creation, using distinct tag bytes to differentiate various constructors. Ultimately, the account state is stored as a collection of cells in TVM persistent storage.
Message Passing and Processing
Ton’s ledger natively supports asynchronous message passing. Each account independently processes incoming messages and updates its state accordingly. This asynchronous mechanism enables complex interactions between accounts without one operation’s delay affecting others.
Gas Model
The TON (The Open Network) blockchain optimizes smart contract execution efficiency through its unique Gas fee model. Gas fees measure and limit resource consumption during contract execution. Compared to traditional blockchains like Ethereum, TON’s model is more complex and efficient, allowing precise management of resource usage during contract execution.
Granular Gas Consumption Measurement
Ton’s Gas model precisely measures computational resources, storage operations, and message transmission costs consumed during contract execution. By finely measuring computation, storage, and messaging, TON prevents overly complex operations from consuming disproportionate resources. Enforcing Gas limits ensures fair allocation of computing resources among network nodes, preventing any single contract or operation from monopolizing network resources.
Parallel Processing and Gas Optimization
Ton supports parallel execution of smart contracts, allowing multiple contracts to run simultaneously across different shards without blocking each other. Its Gas model is tightly integrated with this parallel execution and sharding architecture. By distributing contract processing across multiple shards, TON spreads Gas computation and payment across different nodes and chains, alleviating congestion and maximizing resource utilization.
Dynamic Gas Adjustment Mechanism
Ton’s Gas model includes a dynamic adjustment mechanism that adapts Gas fees based on real-time network load. During low-load periods, users can execute contracts at lower Gas costs, encouraging off-peak activity and balancing resource usage. This mechanism improves user experience and controls resource peaks through market-driven dynamics.
Commonly Overlooked Vulnerabilities in Ton Smart Contracts
In our previous security analysis article on TON, we detailed common security vulnerabilities in the TON ecosystem. Refer to the table below:


This article focuses on vulnerability points in TON contracts that our team has identified as frequently overlooked:
(1) Improve Code Readability
In TON smart contracts, numbers are often used to represent message-sending parameters. For example, in the following code snippet, numeric values are repeatedly used to indicate identifiers and data lengths, significantly reducing code readability and maintainability. Other developers reading this code may struggle to understand the meaning and purpose of these numbers. To improve clarity, recommend defining key numeric values as named constants—for instance, define 0x18 as NON_BOUNCEABLE.
check_std_addr(address);var msg = begin_cell() store_uint(0x18, 6) ;; nobounce store_slice(address) store_coins(amount) store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1) end_cell();send_raw_message(msg, 1);
Similarly, error codes in conditional checks should be replaced with descriptive variables for better clarity.
throw_unless(705, equal_slices(owner_address, sender_address));
(2) Use end_parse() to Ensure Data Integrity
Data parsing in TON contracts follows a fixed sequence, loading specified data types step-by-step from raw data. This ensures consistency and accuracy. Example:
() load_data() impure {
slice ds = get_data().begin_parse();
storage::owner = ds~load_msg_addr();
storage::amount = ds~load_uint(256);
storage::data = ds~load_ref();
storage::api_data = ds~load_ref();
ds.end_parse();
}
Here, end_parse() checks whether the slice is empty. If not, it throws an exception, ensuring the data format and content match expectations. If end_parse() detects remaining data, it indicates incomplete parsing or malformed input. Thus, calling end_parse() helps verify complete and correct data parsing.
(3) Exceptions Caused by Mismatched Data Loading and Storage Types
A key point here is matching int and uint types during storage and retrieval. In the following code, store_int() stores an int value (-42), but load_uint() is used to retrieve it, which can lead to exceptions.
() Test_Function() {
var cell = begin_cell();
cell = cell.store_int(-42, 32);
var my_cell = cell.end_cell();
slice s = my_cell.begin_parse();
var result = s.load_uint(32);
}
(4) Proper Use of inline_ref and inline Modifiers
First, clarify the difference between inline_ref and inline modifiers:
inline: Functions marked with inline have their code directly inserted at each call site. Instead of jumping to a function body, the actual code is copied into the caller’s location, eliminating function call overhead.
inline_ref: Functions marked with inline_ref store their code in a separate cell. At runtime, TVM executes the code via the CALLREF instruction rather than inlining it.
Thus, the inline modifier suits small, simple functions to reduce call overhead, though it may cause code duplication. The inline_ref modifier is better for larger or frequently called functions, improving efficiency by storing code externally and avoiding redundancy. Summary: use inline_ref for large or widely reused functions; otherwise, use inline.
(5) Specify the Correct Working Chain
TON allows up to 2^32 Workingchains, each divisible into up to 2^60 shards. Currently, only two Workingchains exist: the Masterchain (-1) and the Basechain (0). When calculating destination addresses in contracts, developers must explicitly specify the target chain ID to ensure wallet addresses reside on the correct Workingchain. To prevent incorrect address generation, use force_chain() to enforce the chain ID.
(6) Avoid Error Code Conflicts
Error code management is crucial for maintaining clarity and avoiding confusion in contract design. First, ensure each error code is unique within a contract to prevent ambiguity from duplicates. Second, avoid conflicting with standard system-defined error codes—e.g., error code 333 indicates chain ID mismatch. Therefore, it is recommended to assign custom error codes in the range 400–1000.
(7) Store Data and Call return() After Operations
In TON smart contracts, message handling branches based on op-codes. After completing business logic, two steps are essential: First, if state changes occur, call save_data() to persist them—otherwise, changes are lost. Second, call return() to signal completion; failure to do so triggers a throw(0xffff) exception.
() recv_internal(int my_balance, int msg_value, cell in_msg_full, slice in_msg_body) impure {
int flags = cs~load_uint(4);
if (flags & 1) {
;; ignore all bounced messages
return ();
}
slice sender_address = cs~load_msg_addr();
load_data();
int op = in_msg_body~load_op();
if ((op == op::op_1())) {
handle_op1();
save_data();
return ();
}
if ((op == op::op_2())) {
handle_op2();
save_data();
return ();
}
if ((op == op::op_3())) {
handle_op3();
save_data();
return ();
}
throw(0xffff);
}
In summary, TON blockchain, with its innovative architecture and flexible development environment, is becoming an ideal platform for decentralized application developers. However, as smart contracts play an increasingly vital role in the TON ecosystem, contract security cannot be overlooked. Developers must thoroughly understand TON’s ecosystem characteristics, strictly follow best practices, strengthen security audit processes, and ensure contract robustness and safety. Only then can the full advantages of the TON platform be realized, enabling the construction of more secure and reliable decentralized applications and safeguarding the healthy development of the entire ecosystem.
The TON ecosystem is currently growing rapidly, attracting significant capital and active users. Yet, the accompanying security challenges must not be ignored.
Join TechFlow official community to stay tuned
Telegram:https://t.me/TechFlowDaily
X (Twitter):https://x.com/TechFlowPost
X (Twitter) EN:https://x.com/BlockFlow_News














