From Risks to Protection: Security Risks and Optimization Suggestions for TON Smart Contracts

Intermediate9/18/2024, 6:23:43 PM
Exploring the smart contract features of the TON blockchain platform, including its unique asynchronous messaging mechanism, account model, and gas fee model. The article provides a detailed analysis of the TON blockchain architecture, including the design of the main chain, work chains, and shard chains, and how they work together to enhance network throughput and scalability. It also emphasizes the security issues to be mindful of when writing smart contracts and offers practical advice and best practices to help developers avoid common security vulnerabilities.

In the rapidly evolving field of blockchain technology, TON (The Open Network) is gaining increasing attention from developers as an efficient and flexible blockchain platform. TON’s unique architecture and features provide powerful tools and rich possibilities for the development of decentralized applications.

However, with the increase in functionality and complexity, the security of smart contracts has become more critical. FunC, the smart contract programming language on TON, is known for its flexibility and efficiency, but it also presents many potential risks and challenges. Writing secure and reliable smart contracts requires developers to have a deep understanding of FunC’s characteristics and the potential risks involved.

This article will provide a detailed analysis of the smart contract-related features on the TON blockchain, as well as vulnerabilities in TON smart contracts that are often overlooked.

Analysis of TON’s Asynchronous Features and Account Mechanism

Asynchronous Calls in Smart Contracts

Network Sharding and Asynchronous Communication

The TON blockchain is designed with three types of chains: Masterchain, Workingchains, and Shardchains.

The Masterchain is the core of the entire network, responsible for storing the metadata and consensus mechanism of the entire network. It records the states of all Workingchains and Shardchains and ensures network consistency and security. Workingchains are independent blockchains, with a maximum of 2^32 chains, responsible for handling specific types of transactions and smart contracts. Each Workingchain can have its own rules and features to meet different application needs. Shardchains are sub-chains of Workingchains, used to further divide the workload of Workingchains, enhancing processing capacity and scalability. Each Workingchain can be split into up to 2^60 Shardchains, with Shardchains handling some transactions independently to achieve efficient parallel processing.

In theory, each account can exclusively occupy a Shardchain, with each account independently maintaining its COIN/TOKEN balance. Transactions between accounts can be fully parallelized. Accounts communicate via asynchronous messages, and the path for messages to travel between Shardchains is log_16(N) - 1, where N is the number of Shardchains.


Image source: https://frontierlabzh.medium.com/ton-weixin-e1d3ae3b3574 of the web3 worldIn Ton, interactions are conducted through sending and receiving messages. These messages can be internal (typically sent by smart contracts interacting with each other) or external (sent by external sources). The message passing process does not require immediate responses from the target contract, allowing the sender to continue executing the remaining logic. This asynchronous messaging mechanism offers greater flexibility and scalability compared to Ethereum’s synchronous calls, reducing performance bottlenecks caused by waiting for responses, while also introducing challenges in handling concurrency and race conditions.

Message format and structure

In TON, messages typically include information such as the sender, recipient, amount, and message body. The message body can consist of function calls, data transfers, or other custom content. TON’s message format is designed to be flexible and extensible, allowing for efficient communication of various types of information between different contracts.

Message queue and status processing

Each contract maintains a message queue to store messages that have not yet been processed. During execution, the contract processes messages one by one from the queue. Since message processing is asynchronous, the contract’s state will not be updated immediately upon receiving a message.

Advantages of asynchronous messaging

•Efficient Sharding Mechanism: TON’s asynchronous mechanism is highly compatible with its sharding design. Each shard independently handles contract messages and state changes, avoiding delays caused by cross-shard synchronization. This design enhances the overall network throughput and scalability.

•Reduced Resource Consumption: Asynchronous messages do not require immediate responses, allowing TON contracts to execute across multiple blocks and avoiding excessive resource consumption within a single block. This enables TON to support more complex and resource-intensive smart contracts.

•Fault Tolerance and Reliability: The asynchronous message passing mechanism increases system fault tolerance. For instance, if a contract cannot respond to a message in a timely manner due to resource limitations or other reasons, the sender can continue processing other logic, preventing the system from stalling due to delays in a single contract.

Challenges of asynchronous contract design

•State Consistency Issues: Due to the asynchronous nature of message passing, contracts may receive different messages at different times, which requires developers to pay special attention to state consistency. When designing contracts, it is crucial to consider how different message orders might affect state changes and ensure the system maintains consistency under all conditions.

•Race Conditions and Protection: Asynchronous message processing introduces potential race condition issues, where multiple messages might simultaneously attempt to modify the contract state. Developers need to implement appropriate locking mechanisms or use transactional operations to prevent state conflicts.

•Security Considerations: Asynchronous contracts are susceptible to risks such as man-in-the-middle attacks or replay attacks when handling cross-contract communication. Therefore, when designing asynchronous contracts, it is essential to address these potential security risks and take preventive measures, such as using timestamps, random numbers, or multi-signature approaches.

Ledger model

TON (The Open Network) employs a unique account abstraction and ledger model in designing its blockchain infrastructure. This model’s flexibility is reflected in how it manages account states, message passing, and contract execution.

Account abstraction

TON’s account model uses a contract-based abstraction, where each account can be viewed as a contract. This is somewhat similar to Ethereum’s account abstraction model but is more flexible and general. In TON, accounts are not merely containers for assets; they also include contract code and state data. Each account comprises its code, data, and message handling logic.

Account Structure: Every TON account has a unique address, which is generated from a combination of the account code’s hash value, initial data at deployment, and other parameters. This means that the same code and initial data deployed in different environments (e.g., different blockchains or shards) may produce different addresses.

Flexibility: Since each account can execute its own contract code, TON accounts can implement very complex logic. Accounts are not just simple balance holders but can handle complex state transitions, inter-account message communication, and even automation based on specific conditions. This makes TON’s account model more scalable and flexible compared to traditional blockchain account models.

Ledger structure

TON’s ledger structure is designed to efficiently handle large-scale concurrent transactions, supporting asynchronous message passing and multi-shard operations. Each account’s state is stored in a Merkle tree structure, providing efficient state validation capabilities.

State Storage

Account state information is stored in persistent storage and organized via a Merkle tree to ensure integrity and security. This design also supports efficient querying and verification of states, especially in cross-shard transactions.

An account or smart contract state typically includes the following:

  1. Balance of base currency 2. Balance of other currencies 3. Smart contract code (or its hash) 4. Persistent data of the smart contract (or its Merkle hash) 5. Statistics on the number of persistent storage units and the raw byte usage 6. Recent timestamp of payments to the smart contract’s persistent storage (essentially the main chain block number) 7. Public key required for transferring currency and sending messages from this account (optional; by default, this is equal to the account_id itself). In some cases, more complex signature check codes may be found here, similar to Bitcoin transaction outputs; in such cases, account_id will be the hash of this code.

Not all information is required for every account. For example, smart contract code is only relevant for smart contracts, not for “simple” accounts. Additionally, while every account must have a non-zero balance of the base currency (e.g., Gram for the base working chain and shard chains), other currency balances may be zero. To avoid retaining unused data, a sum-product type is defined during the creation of a working chain, using different marking bytes to distinguish various “constructor functions.” Ultimately, the account state is saved as a collection of units in TVM’s persistent storage.

Message Passing and Processing

TON’s ledger structure includes built-in support for asynchronous message passing. Each account can independently process received messages and update its state. This asynchronous messaging mechanism allows for complex interactions between accounts without affecting the normal operation of other accounts due to delays in any single operation.

Gas model

TON (The Open Network) significantly optimizes the execution efficiency of smart contracts through its unique gas fee model. This gas fee model is used to measure and limit the resources consumed during smart contract execution. Compared to traditional blockchains like Ethereum, TON’s model is more complex and efficient, allowing for more precise management of resource consumption during contract execution.

TON’s gas model can accurately measure the computational resources, storage operations, and message passing costs consumed during smart contract execution. By providing detailed measurements for resources such as computation, storage, and messaging, TON’s gas model prevents operations with excessive complexity from consuming too many resources. By limiting gas consumption, TON ensures that each network node can fairly allocate computational resources, avoiding overuse of network resources by a single contract or operation.

TON supports parallel processing of smart contracts, allowing multiple contracts to run simultaneously on different shards without blocking each other. In this design, the gas model is closely integrated with the parallel execution and sharding mechanisms. By processing contracts in parallel across multiple shards, TON can distribute gas computation and payment across different nodes and chains, avoiding network congestion while maximizing resource utilization.

TON’s gas model includes a dynamic adjustment mechanism that allows gas fees to be adjusted based on the real-time load of the network. This means that during periods of lower network load, users can execute contracts at lower gas fees, encouraging operations during off-peak times and balancing network resource usage. This mechanism not only enhances user experience but also controls peak resource usage through a market-driven approach.

Ton smart contracts are easy to ignore loopholes

In our previous security analysis article on TON, we have detailed the common security vulnerabilities within the TON ecosystem. For further reference, please see the table below:


This article will focus on the vulnerabilities in TON contracts that are often overlooked, as summarized by our team:

(1) Code Readability Optimization

In TON smart contracts, numbers are often used to store data related to message sending. For example, in the code below, multiple instances of numbers are used to represent corresponding identifiers and data storage lengths, which significantly reduces code readability and maintainability. Other developers may find it challenging to understand the meaning and purpose of these numbers when reading the code. To improve readability and maintainability, it is recommended to define key numerical values as named constants. For instance, define 0x18 as NON_BOUNCEABLE.

  1. check_std_addr(address);was 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);

In addition, for the error message in the contract judgment conditions, it is also recommended to define corresponding variables to replace the error codes.

(2) Using end_parse() to Ensure Data Integrity

In TON contracts, data parsing follows a fixed order, loading specified types of data step by step from the raw data. This parsing method ensures data consistency and accuracy, as illustrated below:

Note that end_parse() is used to check if a data slice is empty. If the slice is not empty, the function will throw an exception. This ensures that the data’s format and content are as expected. If the end_parse() function detects remaining data in the slice, it may indicate that the data parsing did not proceed as intended or that there is an issue with the data format. Therefore, by calling end_parse(), you can verify if there are any omissions or anomalies during the parsing process.

(3) Exceptions Caused by Mismatched Data Storage and Types

This mainly concerns the matching of int and uint storage types. For example, in the following code, the store_int() function is used to store an int value of -42, but load_uint() is used to load this value, which may result in an exception.

(4) Proper Use of inline_ref and inline Modifiers

First, it’s important to distinguish between the inline and inline_ref modifiers:

inline: Functions with the inline modifier have their code inserted directly at the call site each time they are called. This means that the function’s actual code is copied to the call location rather than being executed through a function jump, which reduces function call overhead but may lead to code duplication.

inline_ref: Functions with the inline_ref modifier store their code in a separate cell. Each time the function is called, TVM executes the code stored in the cell via the CALLREF command, avoiding code duplication and improving efficiency for more complex functions or those called multiple times.

In summary, use inline for simple functions to reduce call overhead, but be aware of potential code duplication. Use inline_ref for larger or frequently called functions to improve efficiency and avoid code repetition.

(5) Determining the Correct Workchain

TON allows the creation of up to 2^32 workchains, each of which can be further subdivided into up to 2^60 shards. Initially, there are two workchains: the masterchain (-1) and the basechain (0). When computing target addresses in contracts, it is crucial to specify the correct workchain ID to ensure that the generated wallet address is on the correct workchain. To avoid generating incorrect addresses, it is recommended to use force_chain() to explicitly specify the chain ID.

(6) Avoiding Error Code Conflicts

Effective management of error codes is crucial for contract design to ensure consistency and avoid confusion. For TON smart contracts, make sure that each error code is unique within the contract to prevent conflicts and ambiguous error messages. Additionally, avoid conflicts with standard error codes defined by the TON platform or underlying system. For instance, error code 333 indicates a chain ID mismatch. It is advisable to use error codes between 400 and 1000 to prevent such conflicts.

(7) Storing Data and Calling return() After Operation Completion

In TON smart contracts, message handling involves selecting different logic based on the op-code. After completing the corresponding logic, two additional steps are necessary: First, if data has been modified, call save_data() to ensure that the changes are stored; otherwise, the changes will be ineffective. Second, call return() to indicate that the operation is complete; otherwise, a throw(0xffff) exception will be triggered.

() 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, the 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 crucial role in the TON ecosystem, security issues cannot be overlooked. Developers should deeply understand the characteristics of the TON ecosystem, adhere strictly to best practices, and enhance security auditing processes to ensure the robustness and security of contracts. Only by doing so can the advantages of the TON platform be fully realized, building safer and more reliable decentralized applications and safeguarding the healthy development of the entire ecosystem.

The TON ecosystem is currently experiencing rapid growth, attracting significant funding and active users. However, the accompanying security issues cannot be ignored. To ensure the security and reliability of the TON ecosystem, Beosin provides comprehensive and professional security audits tailored to the characteristics of TON smart contract calls and operations, supporting the ecosystem’s development.

Beosin has numerous successful cases within the TON ecosystem. Previously, Beosin conducted thorough security audits for leading decentralized stablecoin project Aqua Protocol and DeFi infrastructure ONTON Finance. The audit covered multiple aspects, including the security of smart contract code, correctness of business logic implementation, gas optimization of contract code, and detection and remediation of potential vulnerabilities.

Statement:

  1. This article is reproduced from [Beosin], original title “Beosin Hard Core Research | From Risk to Protection: Security Risks and Optimization Suggestions of TON Smart Contracts》, the copyright belongs to the original author [Beosin ], if you have any objection to the reprint, please contact Gate Learn Team, the team will handle it as soon as possible according to relevant procedures.

  2. Disclaimer: The views and opinions expressed in this article represent only the author’s personal views and do not constitute any investment advice.

  3. Other language versions of the article are translated by the Gate Learn team and are not mentioned in Gate.io, the translated article may not be reproduced, distributed or plagiarized.

From Risks to Protection: Security Risks and Optimization Suggestions for TON Smart Contracts

Intermediate9/18/2024, 6:23:43 PM
Exploring the smart contract features of the TON blockchain platform, including its unique asynchronous messaging mechanism, account model, and gas fee model. The article provides a detailed analysis of the TON blockchain architecture, including the design of the main chain, work chains, and shard chains, and how they work together to enhance network throughput and scalability. It also emphasizes the security issues to be mindful of when writing smart contracts and offers practical advice and best practices to help developers avoid common security vulnerabilities.

In the rapidly evolving field of blockchain technology, TON (The Open Network) is gaining increasing attention from developers as an efficient and flexible blockchain platform. TON’s unique architecture and features provide powerful tools and rich possibilities for the development of decentralized applications.

However, with the increase in functionality and complexity, the security of smart contracts has become more critical. FunC, the smart contract programming language on TON, is known for its flexibility and efficiency, but it also presents many potential risks and challenges. Writing secure and reliable smart contracts requires developers to have a deep understanding of FunC’s characteristics and the potential risks involved.

This article will provide a detailed analysis of the smart contract-related features on the TON blockchain, as well as vulnerabilities in TON smart contracts that are often overlooked.

Analysis of TON’s Asynchronous Features and Account Mechanism

Asynchronous Calls in Smart Contracts

Network Sharding and Asynchronous Communication

The TON blockchain is designed with three types of chains: Masterchain, Workingchains, and Shardchains.

The Masterchain is the core of the entire network, responsible for storing the metadata and consensus mechanism of the entire network. It records the states of all Workingchains and Shardchains and ensures network consistency and security. Workingchains are independent blockchains, with a maximum of 2^32 chains, responsible for handling specific types of transactions and smart contracts. Each Workingchain can have its own rules and features to meet different application needs. Shardchains are sub-chains of Workingchains, used to further divide the workload of Workingchains, enhancing processing capacity and scalability. Each Workingchain can be split into up to 2^60 Shardchains, with Shardchains handling some transactions independently to achieve efficient parallel processing.

In theory, each account can exclusively occupy a Shardchain, with each account independently maintaining its COIN/TOKEN balance. Transactions between accounts can be fully parallelized. Accounts communicate via asynchronous messages, and the path for messages to travel between Shardchains is log_16(N) - 1, where N is the number of Shardchains.


Image source: https://frontierlabzh.medium.com/ton-weixin-e1d3ae3b3574 of the web3 worldIn Ton, interactions are conducted through sending and receiving messages. These messages can be internal (typically sent by smart contracts interacting with each other) or external (sent by external sources). The message passing process does not require immediate responses from the target contract, allowing the sender to continue executing the remaining logic. This asynchronous messaging mechanism offers greater flexibility and scalability compared to Ethereum’s synchronous calls, reducing performance bottlenecks caused by waiting for responses, while also introducing challenges in handling concurrency and race conditions.

Message format and structure

In TON, messages typically include information such as the sender, recipient, amount, and message body. The message body can consist of function calls, data transfers, or other custom content. TON’s message format is designed to be flexible and extensible, allowing for efficient communication of various types of information between different contracts.

Message queue and status processing

Each contract maintains a message queue to store messages that have not yet been processed. During execution, the contract processes messages one by one from the queue. Since message processing is asynchronous, the contract’s state will not be updated immediately upon receiving a message.

Advantages of asynchronous messaging

•Efficient Sharding Mechanism: TON’s asynchronous mechanism is highly compatible with its sharding design. Each shard independently handles contract messages and state changes, avoiding delays caused by cross-shard synchronization. This design enhances the overall network throughput and scalability.

•Reduced Resource Consumption: Asynchronous messages do not require immediate responses, allowing TON contracts to execute across multiple blocks and avoiding excessive resource consumption within a single block. This enables TON to support more complex and resource-intensive smart contracts.

•Fault Tolerance and Reliability: The asynchronous message passing mechanism increases system fault tolerance. For instance, if a contract cannot respond to a message in a timely manner due to resource limitations or other reasons, the sender can continue processing other logic, preventing the system from stalling due to delays in a single contract.

Challenges of asynchronous contract design

•State Consistency Issues: Due to the asynchronous nature of message passing, contracts may receive different messages at different times, which requires developers to pay special attention to state consistency. When designing contracts, it is crucial to consider how different message orders might affect state changes and ensure the system maintains consistency under all conditions.

•Race Conditions and Protection: Asynchronous message processing introduces potential race condition issues, where multiple messages might simultaneously attempt to modify the contract state. Developers need to implement appropriate locking mechanisms or use transactional operations to prevent state conflicts.

•Security Considerations: Asynchronous contracts are susceptible to risks such as man-in-the-middle attacks or replay attacks when handling cross-contract communication. Therefore, when designing asynchronous contracts, it is essential to address these potential security risks and take preventive measures, such as using timestamps, random numbers, or multi-signature approaches.

Ledger model

TON (The Open Network) employs a unique account abstraction and ledger model in designing its blockchain infrastructure. This model’s flexibility is reflected in how it manages account states, message passing, and contract execution.

Account abstraction

TON’s account model uses a contract-based abstraction, where each account can be viewed as a contract. This is somewhat similar to Ethereum’s account abstraction model but is more flexible and general. In TON, accounts are not merely containers for assets; they also include contract code and state data. Each account comprises its code, data, and message handling logic.

Account Structure: Every TON account has a unique address, which is generated from a combination of the account code’s hash value, initial data at deployment, and other parameters. This means that the same code and initial data deployed in different environments (e.g., different blockchains or shards) may produce different addresses.

Flexibility: Since each account can execute its own contract code, TON accounts can implement very complex logic. Accounts are not just simple balance holders but can handle complex state transitions, inter-account message communication, and even automation based on specific conditions. This makes TON’s account model more scalable and flexible compared to traditional blockchain account models.

Ledger structure

TON’s ledger structure is designed to efficiently handle large-scale concurrent transactions, supporting asynchronous message passing and multi-shard operations. Each account’s state is stored in a Merkle tree structure, providing efficient state validation capabilities.

State Storage

Account state information is stored in persistent storage and organized via a Merkle tree to ensure integrity and security. This design also supports efficient querying and verification of states, especially in cross-shard transactions.

An account or smart contract state typically includes the following:

  1. Balance of base currency 2. Balance of other currencies 3. Smart contract code (or its hash) 4. Persistent data of the smart contract (or its Merkle hash) 5. Statistics on the number of persistent storage units and the raw byte usage 6. Recent timestamp of payments to the smart contract’s persistent storage (essentially the main chain block number) 7. Public key required for transferring currency and sending messages from this account (optional; by default, this is equal to the account_id itself). In some cases, more complex signature check codes may be found here, similar to Bitcoin transaction outputs; in such cases, account_id will be the hash of this code.

Not all information is required for every account. For example, smart contract code is only relevant for smart contracts, not for “simple” accounts. Additionally, while every account must have a non-zero balance of the base currency (e.g., Gram for the base working chain and shard chains), other currency balances may be zero. To avoid retaining unused data, a sum-product type is defined during the creation of a working chain, using different marking bytes to distinguish various “constructor functions.” Ultimately, the account state is saved as a collection of units in TVM’s persistent storage.

Message Passing and Processing

TON’s ledger structure includes built-in support for asynchronous message passing. Each account can independently process received messages and update its state. This asynchronous messaging mechanism allows for complex interactions between accounts without affecting the normal operation of other accounts due to delays in any single operation.

Gas model

TON (The Open Network) significantly optimizes the execution efficiency of smart contracts through its unique gas fee model. This gas fee model is used to measure and limit the resources consumed during smart contract execution. Compared to traditional blockchains like Ethereum, TON’s model is more complex and efficient, allowing for more precise management of resource consumption during contract execution.

TON’s gas model can accurately measure the computational resources, storage operations, and message passing costs consumed during smart contract execution. By providing detailed measurements for resources such as computation, storage, and messaging, TON’s gas model prevents operations with excessive complexity from consuming too many resources. By limiting gas consumption, TON ensures that each network node can fairly allocate computational resources, avoiding overuse of network resources by a single contract or operation.

TON supports parallel processing of smart contracts, allowing multiple contracts to run simultaneously on different shards without blocking each other. In this design, the gas model is closely integrated with the parallel execution and sharding mechanisms. By processing contracts in parallel across multiple shards, TON can distribute gas computation and payment across different nodes and chains, avoiding network congestion while maximizing resource utilization.

TON’s gas model includes a dynamic adjustment mechanism that allows gas fees to be adjusted based on the real-time load of the network. This means that during periods of lower network load, users can execute contracts at lower gas fees, encouraging operations during off-peak times and balancing network resource usage. This mechanism not only enhances user experience but also controls peak resource usage through a market-driven approach.

Ton smart contracts are easy to ignore loopholes

In our previous security analysis article on TON, we have detailed the common security vulnerabilities within the TON ecosystem. For further reference, please see the table below:


This article will focus on the vulnerabilities in TON contracts that are often overlooked, as summarized by our team:

(1) Code Readability Optimization

In TON smart contracts, numbers are often used to store data related to message sending. For example, in the code below, multiple instances of numbers are used to represent corresponding identifiers and data storage lengths, which significantly reduces code readability and maintainability. Other developers may find it challenging to understand the meaning and purpose of these numbers when reading the code. To improve readability and maintainability, it is recommended to define key numerical values as named constants. For instance, define 0x18 as NON_BOUNCEABLE.

  1. check_std_addr(address);was 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);

In addition, for the error message in the contract judgment conditions, it is also recommended to define corresponding variables to replace the error codes.

(2) Using end_parse() to Ensure Data Integrity

In TON contracts, data parsing follows a fixed order, loading specified types of data step by step from the raw data. This parsing method ensures data consistency and accuracy, as illustrated below:

Note that end_parse() is used to check if a data slice is empty. If the slice is not empty, the function will throw an exception. This ensures that the data’s format and content are as expected. If the end_parse() function detects remaining data in the slice, it may indicate that the data parsing did not proceed as intended or that there is an issue with the data format. Therefore, by calling end_parse(), you can verify if there are any omissions or anomalies during the parsing process.

(3) Exceptions Caused by Mismatched Data Storage and Types

This mainly concerns the matching of int and uint storage types. For example, in the following code, the store_int() function is used to store an int value of -42, but load_uint() is used to load this value, which may result in an exception.

(4) Proper Use of inline_ref and inline Modifiers

First, it’s important to distinguish between the inline and inline_ref modifiers:

inline: Functions with the inline modifier have their code inserted directly at the call site each time they are called. This means that the function’s actual code is copied to the call location rather than being executed through a function jump, which reduces function call overhead but may lead to code duplication.

inline_ref: Functions with the inline_ref modifier store their code in a separate cell. Each time the function is called, TVM executes the code stored in the cell via the CALLREF command, avoiding code duplication and improving efficiency for more complex functions or those called multiple times.

In summary, use inline for simple functions to reduce call overhead, but be aware of potential code duplication. Use inline_ref for larger or frequently called functions to improve efficiency and avoid code repetition.

(5) Determining the Correct Workchain

TON allows the creation of up to 2^32 workchains, each of which can be further subdivided into up to 2^60 shards. Initially, there are two workchains: the masterchain (-1) and the basechain (0). When computing target addresses in contracts, it is crucial to specify the correct workchain ID to ensure that the generated wallet address is on the correct workchain. To avoid generating incorrect addresses, it is recommended to use force_chain() to explicitly specify the chain ID.

(6) Avoiding Error Code Conflicts

Effective management of error codes is crucial for contract design to ensure consistency and avoid confusion. For TON smart contracts, make sure that each error code is unique within the contract to prevent conflicts and ambiguous error messages. Additionally, avoid conflicts with standard error codes defined by the TON platform or underlying system. For instance, error code 333 indicates a chain ID mismatch. It is advisable to use error codes between 400 and 1000 to prevent such conflicts.

(7) Storing Data and Calling return() After Operation Completion

In TON smart contracts, message handling involves selecting different logic based on the op-code. After completing the corresponding logic, two additional steps are necessary: First, if data has been modified, call save_data() to ensure that the changes are stored; otherwise, the changes will be ineffective. Second, call return() to indicate that the operation is complete; otherwise, a throw(0xffff) exception will be triggered.

() 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, the 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 crucial role in the TON ecosystem, security issues cannot be overlooked. Developers should deeply understand the characteristics of the TON ecosystem, adhere strictly to best practices, and enhance security auditing processes to ensure the robustness and security of contracts. Only by doing so can the advantages of the TON platform be fully realized, building safer and more reliable decentralized applications and safeguarding the healthy development of the entire ecosystem.

The TON ecosystem is currently experiencing rapid growth, attracting significant funding and active users. However, the accompanying security issues cannot be ignored. To ensure the security and reliability of the TON ecosystem, Beosin provides comprehensive and professional security audits tailored to the characteristics of TON smart contract calls and operations, supporting the ecosystem’s development.

Beosin has numerous successful cases within the TON ecosystem. Previously, Beosin conducted thorough security audits for leading decentralized stablecoin project Aqua Protocol and DeFi infrastructure ONTON Finance. The audit covered multiple aspects, including the security of smart contract code, correctness of business logic implementation, gas optimization of contract code, and detection and remediation of potential vulnerabilities.

Statement:

  1. This article is reproduced from [Beosin], original title “Beosin Hard Core Research | From Risk to Protection: Security Risks and Optimization Suggestions of TON Smart Contracts》, the copyright belongs to the original author [Beosin ], if you have any objection to the reprint, please contact Gate Learn Team, the team will handle it as soon as possible according to relevant procedures.

  2. Disclaimer: The views and opinions expressed in this article represent only the author’s personal views and do not constitute any investment advice.

  3. Other language versions of the article are translated by the Gate Learn team and are not mentioned in Gate.io, the translated article may not be reproduced, distributed or plagiarized.

Start Now
Sign up and get a
$100
Voucher!