Exploring the Technical Features and Smart Contract Development of TON

Intermediate6/19/2024, 1:28:58 AM
TON presents a high technical barrier and its DApp development model differs greatly from mainstream blockchain protocols. Web3Mario provides an in-depth analysis of TON’s core design concepts, its infinite sharding mechanism, actor-model-based smart contracts, and fully parallel execution environment.

Introduction: After Binance launched Notcoin, the biggest game in the TON ecosystem, and its fully circulating token economy created a huge wealth effect, TON quickly gained a lot of attention. Talking with friends, I found out that TON has a high technical barrier and its DApp development model is very different from mainstream blockchain protocols. So, I spent some time researching this topic in depth and have some insights to share with you. In short, TON’s core design philosophy is to rebuild traditional blockchain protocols from the ground up, focusing on achieving high concurrency and scalability, even if it means sacrificing interoperability.

TON’s Core Design Principles - High Concurrency and Scalability

It can be said that the purpose of all complex technology selections in TON comes from the pursuit of high concurrency and high scalability. Of course, it is not difficult for us to understand this from the background of its birth. TON, or The Open Network, is a decentralized computing network that includes an L1 blockchain and multiple components. TON was originally developed by Telegram founder Nikolai Durov and his team, and is now supported and maintained by a global community of independent contributors. Its birth dates back to 2017, when the Telegram team began exploring blockchain solutions for themselves. Since no existing L1 blockchain at the time could support Telegram’s nine-figure user base, they decided to design their own blockchain, then called Telegram Open Network. The time came in 2018. In order to obtain the resources needed to implement TON, Telegram launched a sale of Gram tokens (later renamed Toncoin) in the first quarter of 2018. In 2020, the Telegram team withdrew from the TON project due to regulatory issues. Subsequently, a small group of open source developers and Telegram competition winners took over TON’s codebase, renamed the project to The Open Network, and continue to actively develop the blockchain to this day, adhering to the principles outlined in the original TON white paper.

As TON was designed to be Telegram’s decentralized execution environment, it had to address two main challenges: high concurrent requests and massive data. Even the highest tested TPS (transactions per second) of Solana, which claims to be the fastest, is only 65,000, far short of the million-level TPS needed for Telegram. Additionally, the huge amount of data generated by Telegram can’t be managed by a blockchain where every node stores a complete copy of the data.

To tackle these challenges, TON optimized mainstream blockchain protocols in two ways:

l It uses an “Infinite Sharding Paradigm” to reduce data redundancy, enabling it to handle large amounts of data and alleviate performance bottlenecks.

l By introducing a fully parallel execution environment based on the Actor model, network TPS is greatly improved;

Building a Blockchain of Chains - Providing Each Account with Its Own Dedicated Chain Through Infinite Sharding

We now know that sharding has become the mainstream solution for most blockchain protocols to improve performance and reduce costs, and TON has taken this to the extreme and proposed the infinite sharding paradigm, the so-called infinite sharding paradigm. Refers to allowing the blockchain to dynamically increase or decrease the number of shards based on network load. This paradigm enables TON to handle large-scale transactions and smart contract operations while maintaining high performance. In theory, TON can establish an exclusive account chain for each account and ensure the interoperability between these chains through certain rules. consistency,

In essence, TON’s chain structure consists of four layers

AccountChain: This layer represents a series of transactions linked to a specific account. Transactions form a chain because, in a state machine, consistent execution rules ensure that the state machine produces the same results when processing instructions in the same order. Therefore, all blockchain systems require transactions to be linked in a chain, and TON is no different. The AccountChain is the most fundamental unit in the TON network. Typically, the AccountChain is a virtual concept, and an independent AccountChain is unlikely to exist.

ShardChain: In most contexts, the ShardChain is the actual unit within TON. A ShardChain is essentially a collection of AccountChains.

WorkChain: Also known as a set of shard chains with custom rules, such as creating a WorkChain based on the EVM to run Solidity smart contracts. In theory, anyone in the community can create their own WorkChain. However, building one is quite complex and requires paying the (high) creation fee and obtaining approval from 2/3 of the validators.

MasterChain: In TON, there is a unique chain called the MasterChain, which provides finality to all shard chains. When the hash value of a shard chain block is included in a MasterChain block, that shard chain block and all its parent blocks are considered final, meaning they are fixed and immutable, referenced by all subsequent shard chain blocks.

This paradigm gives the TON network three key features:

Dynamic Sharding: TON can automatically split and merge shard chains to adapt to changing loads, ensuring new blocks are quickly generated and transactions don’t experience long delays.

High Scalability: With its infinite sharding paradigm, TON can support almost an unlimited number of shards, theoretically up to 2^60 WorkChains.

Adaptability: When part of the network experiences increased load, it can subdivide into more shards to handle the higher transaction volume. Conversely, when the load decreases, shards can merge to improve efficiency.

In a multi-chain system like this, the primary challenge is cross-chain communication. With the capability for infinite sharding, when the number of shards in the network grows significantly, routing information between chains becomes complex. For example, imagine a network with four nodes, each maintaining an independent WorkChain. Each node, besides managing its own transaction sorting, must also monitor and process state changes in other chains. In TON, this is done by monitoring messages in the output queue.

Suppose Account A in WorkChain 1 wants to send a message to Account C in WorkChain 3. This requires designing a message routing solution. In this example, there are two routing paths: WorkChain 1 -> WorkChain 2 -> WorkChain 3, and WorkChain 1 -> WorkChain 4 -> WorkChain 3.

In more complex scenarios, an efficient and low-cost routing algorithm is necessary for fast message communication. TON uses the “hypercube routing algorithm” for cross-chain message routing discovery. A hypercube structure is a special network topology where an n-dimensional hypercube has 2^n vertices, each uniquely identified by an n-bit binary number. In this structure, any two vertices are adjacent if their binary representations differ by only one bit. For instance, in a 3-dimensional hypercube, vertex 000 and vertex 001 are adjacent because they differ only in the last bit. The example above is a 2-dimensional hypercube.

In the hypercube routing protocol, the routing of a message from the source WorkChain to the target WorkChain is done by comparing their binary addresses. The algorithm finds the minimum distance between these addresses (i.e., the number of differing bits) and forwards the message through adjacent WorkChains until it reaches its destination. This ensures that the data packet follows the shortest path, enhancing network communication efficiency. To simplify this process, TON also offers an optimistic solution. If a user can provide valid proof of a routing path, typically a Merkle trie root, the node can immediately verify the message’s authenticity. This is known as instant hypercube routing.As a result, TON addresses differ significantly from those in other blockchain protocols. Most blockchain protocols use the hash of a public key generated by elliptic encryption algorithms as an address, focusing on uniqueness without needing routing functions. In TON, addresses consist of two parts: (workchain_id, account_id), with workchain_id encoded according to the hypercube routing algorithm.One might wonder why not relay all cross-chain information through the MasterChain, similar to Cosmos. In TON’s design, the MasterChain handles only the most critical task of maintaining the finality of the WorkChains. While it is possible to route messages through the MasterChain, the associated fees would be prohibitively high.

Finally, let’s briefly discuss its consensus algorithm. TON employs a combination of BFT (Byzantine Fault Tolerance) and PoS (Proof of Stake). This means that any staker can participate in block creation. The TON election governance contract periodically selects a group of validators randomly from all stakers. These selected validators then use the BFT algorithm to create blocks. If a validator creates invalid blocks or acts maliciously, their staked tokens are confiscated. Conversely, they receive rewards for successfully creating valid blocks. This method is quite common, so we won’t go into further detail here.

Smart contracts utilizing the Actor model within a fully parallel execution environment

Another key difference in TON compared to mainstream blockchain protocols is its smart contract execution environment. To overcome the TPS limitations faced by mainstream blockchain protocols, TON uses a bottom-up design approach and employs the Actor model to reconstruct smart contracts and their execution, enabling fully parallel execution capabilities.

Most mainstream blockchain protocols use a single-threaded, serial execution environment. For instance, Ethereum’s execution environment, the EVM, operates as a state machine that processes transactions sequentially. After a block is formed and transactions are ordered, they are executed one by one through the EVM. This entirely serial, single-threaded process means only one transaction is processed at any given time. The advantage is that once transaction order is established, the execution results remain consistent across a distributed network. Moreover, since only one transaction is executed at a time, no other transactions can alter the state data being accessed, ensuring interoperability between smart contracts. For example, when using Uniswap to buy ETH with USDT, the liquidity pool’s distribution is a fixed value during execution. This allows mathematical models to determine the exact outcome. Conversely, if other liquidity providers added liquidity during the bonding curve calculation, the results would be outdated, which is clearly unacceptable.

However, this architecture also has clear limitations, particularly the TPS bottleneck, which feels outdated with modern multi-core processors. It’s similar to playing old computer games like Red Alert on a brand-new PC; when the number of combat units reaches a certain level, you still encounter significant lag. This is due to software architecture issues.

Some protocols are addressing this problem and have proposed their own parallel solutions. For example, Solana, which claims to have the highest TPS, also supports parallel execution. However, Solana’s design differs from TON’s. Solana’s core idea is to group all transactions based on their execution dependencies, ensuring that different groups do not share any state data. This means there are no shared dependencies, allowing transactions in different groups to execute in parallel without conflict. Transactions within the same group are still executed serially.

In contrast, TON completely abandons the serial execution architecture and adopts a development paradigm specifically designed for parallelism, using the Actor model to reconstruct its execution environment. The Actor model, first proposed by Carl Hewitt in 1973, aims to solve the complexity of shared states in traditional concurrent programs through message passing. Each Actor has its own private state and behavior and does not share state information with other Actors. The Actor model is a concurrency computation model that achieves parallel processing through message passing. In this model, an “Actor” is a basic unit that can handle received messages, create new Actors, send additional messages, and decide how to respond to subsequent messages. The Actor model must have the following characteristics:

Encapsulation and Independence: Each Actor operates completely independently when processing messages, allowing for parallel message processing without interference.

Message Passing: Actors interact solely through sending and receiving messages, with message passing being asynchronous.

Dynamic Structure: Actors can create additional Actors at runtime, allowing the Actor model to dynamically expand the system as needed.

TON adopts this architecture for its smart contract model, meaning that each smart contract in TON is based on the Actor model and has completely independent storage because it does not depend on any external data. Moreover, calls to the same smart contract are executed in the order of messages in the receive queue. This enables transactions in TON to be executed in parallel efficiently, without concerns about conflicts.However, this design also introduces some new challenges. For DApp developers, their familiar development paradigm will be disrupted in the following ways:

  1. Asynchronous Smart Contract Calls: In TON, it is impossible to atomically call external contracts or access external contract data within smart contracts. In Solidity, for instance, it is straightforward for Contract A’s function1 to call Contract B’s function2 or access certain state data through Contract C’s read-only function3, all in a single transaction. However, in TON, this cannot be achieved. Any interaction with external smart contracts will be executed asynchronously by creating new transactions, referred to as internal messages initiated by smart contracts. The execution process cannot be blocked to await the result.

For example, if we are developing a DEX and follow the common EVM paradigm, we typically have a unified router contract to manage transaction routing, while each pool independently manages the LP data for specific trading pairs. Let’s say we have two pools: USDT-DAI and DAI-ETH. When a user wants to buy ETH directly with USDT, they can use the router contract to sequentially interact with these two pools in a single atomic transaction. However, in TON, this process is not as straightforward and requires a different development approach. If we try to reuse this EVM paradigm, the information flow would involve an external message initiated by the user and three internal messages to complete the transaction (note that this example is to highlight the differences; in actual development, even the ERC20 paradigm would need to be redesigned).

  1. Careful consideration is required for error handling in cross-contract calls, designing appropriate bounce functions for each inter-contract interaction. In mainstream EVM systems, if an error occurs during transaction execution, the entire transaction is rolled back to its initial state. This is straightforward in a serial single-threaded model. However, in TON, since inter-contract calls are executed asynchronously, if an error occurs at a later stage, the earlier successfully executed transactions have already been confirmed, potentially causing issues. Therefore, TON has introduced a special message type called a bounce message. If an error occurs in the subsequent execution of an internal message, the triggered contract can use the bounce function reserved in the triggering contract to reset certain states in the triggering contract.

  2. In complex scenarios, transactions that are received first may not be completed first, so you cannot assume a specific execution order. In an asynchronous and parallel smart contract system, defining the processing order can be challenging. This is why every message in TON has its logical time, known as Lamport time (lt). It helps determine which event triggered another and what validators need to process first. In a simple model, transactions received first are executed first.

In this model, A and B represent two smart contracts. If msg1_lt < msg2_lt, then tx1_lt < tx2_lt in terms of sequence.

However, in more complex situations, this rule can be broken. The official documentation provides an example: suppose we have three contracts, A, B, and C. In one transaction, A sends two internal messages, msg1 and msg2, one to B and the other to C. Although they are created in a specific order (msg1 first, then msg2), we cannot be certain that msg1 will be processed before msg2. This uncertainty arises because the routes from A to B and from A to C might differ in length and validator sets. If these contracts are in different shard chains, one message might take several blocks to reach the target contract. Therefore, there are two possible transaction paths, as illustrated.

  1. In TON, the persistent storage for smart contracts uses a directed acyclic graph (DAG) structure with cells as units. Data is compactly compressed into a cell according to specific encoding rules and extends downward in a DAG manner. This contrasts with the hashmap-based structure used in EVM for state data. Due to different data access algorithms, TON assigns varying gas prices for processing data at different depths; deeper cell data processing requires more gas. Consequently, TON faces a type of DOS attack, where malicious users flood a smart contract with a large number of junk messages, filling all the shallow cells. This increases storage costs for honest users. In contrast, EVM’s hashmap has a query complexity of O(1), ensuring consistent gas costs and avoiding similar issues. Therefore, TON Dapp developers should avoid using unbounded data types in smart contracts. When unbounded data types are necessary, they should be partitioned using sharding.

  1. Some features are less unique, such as the requirement for smart contracts to pay rent for storage. In TON, smart contracts are inherently upgradeable and come with native abstract account functions, meaning that all wallet addresses in TON are smart contracts, just uninitialized. Developers need to pay close attention to these aspects.

Disclaimer:

  1. This article is reprinted from [Theblockbeats]. All copyrights belong to the original author [Web3Mario]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

Exploring the Technical Features and Smart Contract Development of TON

Intermediate6/19/2024, 1:28:58 AM
TON presents a high technical barrier and its DApp development model differs greatly from mainstream blockchain protocols. Web3Mario provides an in-depth analysis of TON’s core design concepts, its infinite sharding mechanism, actor-model-based smart contracts, and fully parallel execution environment.

Introduction: After Binance launched Notcoin, the biggest game in the TON ecosystem, and its fully circulating token economy created a huge wealth effect, TON quickly gained a lot of attention. Talking with friends, I found out that TON has a high technical barrier and its DApp development model is very different from mainstream blockchain protocols. So, I spent some time researching this topic in depth and have some insights to share with you. In short, TON’s core design philosophy is to rebuild traditional blockchain protocols from the ground up, focusing on achieving high concurrency and scalability, even if it means sacrificing interoperability.

TON’s Core Design Principles - High Concurrency and Scalability

It can be said that the purpose of all complex technology selections in TON comes from the pursuit of high concurrency and high scalability. Of course, it is not difficult for us to understand this from the background of its birth. TON, or The Open Network, is a decentralized computing network that includes an L1 blockchain and multiple components. TON was originally developed by Telegram founder Nikolai Durov and his team, and is now supported and maintained by a global community of independent contributors. Its birth dates back to 2017, when the Telegram team began exploring blockchain solutions for themselves. Since no existing L1 blockchain at the time could support Telegram’s nine-figure user base, they decided to design their own blockchain, then called Telegram Open Network. The time came in 2018. In order to obtain the resources needed to implement TON, Telegram launched a sale of Gram tokens (later renamed Toncoin) in the first quarter of 2018. In 2020, the Telegram team withdrew from the TON project due to regulatory issues. Subsequently, a small group of open source developers and Telegram competition winners took over TON’s codebase, renamed the project to The Open Network, and continue to actively develop the blockchain to this day, adhering to the principles outlined in the original TON white paper.

As TON was designed to be Telegram’s decentralized execution environment, it had to address two main challenges: high concurrent requests and massive data. Even the highest tested TPS (transactions per second) of Solana, which claims to be the fastest, is only 65,000, far short of the million-level TPS needed for Telegram. Additionally, the huge amount of data generated by Telegram can’t be managed by a blockchain where every node stores a complete copy of the data.

To tackle these challenges, TON optimized mainstream blockchain protocols in two ways:

l It uses an “Infinite Sharding Paradigm” to reduce data redundancy, enabling it to handle large amounts of data and alleviate performance bottlenecks.

l By introducing a fully parallel execution environment based on the Actor model, network TPS is greatly improved;

Building a Blockchain of Chains - Providing Each Account with Its Own Dedicated Chain Through Infinite Sharding

We now know that sharding has become the mainstream solution for most blockchain protocols to improve performance and reduce costs, and TON has taken this to the extreme and proposed the infinite sharding paradigm, the so-called infinite sharding paradigm. Refers to allowing the blockchain to dynamically increase or decrease the number of shards based on network load. This paradigm enables TON to handle large-scale transactions and smart contract operations while maintaining high performance. In theory, TON can establish an exclusive account chain for each account and ensure the interoperability between these chains through certain rules. consistency,

In essence, TON’s chain structure consists of four layers

AccountChain: This layer represents a series of transactions linked to a specific account. Transactions form a chain because, in a state machine, consistent execution rules ensure that the state machine produces the same results when processing instructions in the same order. Therefore, all blockchain systems require transactions to be linked in a chain, and TON is no different. The AccountChain is the most fundamental unit in the TON network. Typically, the AccountChain is a virtual concept, and an independent AccountChain is unlikely to exist.

ShardChain: In most contexts, the ShardChain is the actual unit within TON. A ShardChain is essentially a collection of AccountChains.

WorkChain: Also known as a set of shard chains with custom rules, such as creating a WorkChain based on the EVM to run Solidity smart contracts. In theory, anyone in the community can create their own WorkChain. However, building one is quite complex and requires paying the (high) creation fee and obtaining approval from 2/3 of the validators.

MasterChain: In TON, there is a unique chain called the MasterChain, which provides finality to all shard chains. When the hash value of a shard chain block is included in a MasterChain block, that shard chain block and all its parent blocks are considered final, meaning they are fixed and immutable, referenced by all subsequent shard chain blocks.

This paradigm gives the TON network three key features:

Dynamic Sharding: TON can automatically split and merge shard chains to adapt to changing loads, ensuring new blocks are quickly generated and transactions don’t experience long delays.

High Scalability: With its infinite sharding paradigm, TON can support almost an unlimited number of shards, theoretically up to 2^60 WorkChains.

Adaptability: When part of the network experiences increased load, it can subdivide into more shards to handle the higher transaction volume. Conversely, when the load decreases, shards can merge to improve efficiency.

In a multi-chain system like this, the primary challenge is cross-chain communication. With the capability for infinite sharding, when the number of shards in the network grows significantly, routing information between chains becomes complex. For example, imagine a network with four nodes, each maintaining an independent WorkChain. Each node, besides managing its own transaction sorting, must also monitor and process state changes in other chains. In TON, this is done by monitoring messages in the output queue.

Suppose Account A in WorkChain 1 wants to send a message to Account C in WorkChain 3. This requires designing a message routing solution. In this example, there are two routing paths: WorkChain 1 -> WorkChain 2 -> WorkChain 3, and WorkChain 1 -> WorkChain 4 -> WorkChain 3.

In more complex scenarios, an efficient and low-cost routing algorithm is necessary for fast message communication. TON uses the “hypercube routing algorithm” for cross-chain message routing discovery. A hypercube structure is a special network topology where an n-dimensional hypercube has 2^n vertices, each uniquely identified by an n-bit binary number. In this structure, any two vertices are adjacent if their binary representations differ by only one bit. For instance, in a 3-dimensional hypercube, vertex 000 and vertex 001 are adjacent because they differ only in the last bit. The example above is a 2-dimensional hypercube.

In the hypercube routing protocol, the routing of a message from the source WorkChain to the target WorkChain is done by comparing their binary addresses. The algorithm finds the minimum distance between these addresses (i.e., the number of differing bits) and forwards the message through adjacent WorkChains until it reaches its destination. This ensures that the data packet follows the shortest path, enhancing network communication efficiency. To simplify this process, TON also offers an optimistic solution. If a user can provide valid proof of a routing path, typically a Merkle trie root, the node can immediately verify the message’s authenticity. This is known as instant hypercube routing.As a result, TON addresses differ significantly from those in other blockchain protocols. Most blockchain protocols use the hash of a public key generated by elliptic encryption algorithms as an address, focusing on uniqueness without needing routing functions. In TON, addresses consist of two parts: (workchain_id, account_id), with workchain_id encoded according to the hypercube routing algorithm.One might wonder why not relay all cross-chain information through the MasterChain, similar to Cosmos. In TON’s design, the MasterChain handles only the most critical task of maintaining the finality of the WorkChains. While it is possible to route messages through the MasterChain, the associated fees would be prohibitively high.

Finally, let’s briefly discuss its consensus algorithm. TON employs a combination of BFT (Byzantine Fault Tolerance) and PoS (Proof of Stake). This means that any staker can participate in block creation. The TON election governance contract periodically selects a group of validators randomly from all stakers. These selected validators then use the BFT algorithm to create blocks. If a validator creates invalid blocks or acts maliciously, their staked tokens are confiscated. Conversely, they receive rewards for successfully creating valid blocks. This method is quite common, so we won’t go into further detail here.

Smart contracts utilizing the Actor model within a fully parallel execution environment

Another key difference in TON compared to mainstream blockchain protocols is its smart contract execution environment. To overcome the TPS limitations faced by mainstream blockchain protocols, TON uses a bottom-up design approach and employs the Actor model to reconstruct smart contracts and their execution, enabling fully parallel execution capabilities.

Most mainstream blockchain protocols use a single-threaded, serial execution environment. For instance, Ethereum’s execution environment, the EVM, operates as a state machine that processes transactions sequentially. After a block is formed and transactions are ordered, they are executed one by one through the EVM. This entirely serial, single-threaded process means only one transaction is processed at any given time. The advantage is that once transaction order is established, the execution results remain consistent across a distributed network. Moreover, since only one transaction is executed at a time, no other transactions can alter the state data being accessed, ensuring interoperability between smart contracts. For example, when using Uniswap to buy ETH with USDT, the liquidity pool’s distribution is a fixed value during execution. This allows mathematical models to determine the exact outcome. Conversely, if other liquidity providers added liquidity during the bonding curve calculation, the results would be outdated, which is clearly unacceptable.

However, this architecture also has clear limitations, particularly the TPS bottleneck, which feels outdated with modern multi-core processors. It’s similar to playing old computer games like Red Alert on a brand-new PC; when the number of combat units reaches a certain level, you still encounter significant lag. This is due to software architecture issues.

Some protocols are addressing this problem and have proposed their own parallel solutions. For example, Solana, which claims to have the highest TPS, also supports parallel execution. However, Solana’s design differs from TON’s. Solana’s core idea is to group all transactions based on their execution dependencies, ensuring that different groups do not share any state data. This means there are no shared dependencies, allowing transactions in different groups to execute in parallel without conflict. Transactions within the same group are still executed serially.

In contrast, TON completely abandons the serial execution architecture and adopts a development paradigm specifically designed for parallelism, using the Actor model to reconstruct its execution environment. The Actor model, first proposed by Carl Hewitt in 1973, aims to solve the complexity of shared states in traditional concurrent programs through message passing. Each Actor has its own private state and behavior and does not share state information with other Actors. The Actor model is a concurrency computation model that achieves parallel processing through message passing. In this model, an “Actor” is a basic unit that can handle received messages, create new Actors, send additional messages, and decide how to respond to subsequent messages. The Actor model must have the following characteristics:

Encapsulation and Independence: Each Actor operates completely independently when processing messages, allowing for parallel message processing without interference.

Message Passing: Actors interact solely through sending and receiving messages, with message passing being asynchronous.

Dynamic Structure: Actors can create additional Actors at runtime, allowing the Actor model to dynamically expand the system as needed.

TON adopts this architecture for its smart contract model, meaning that each smart contract in TON is based on the Actor model and has completely independent storage because it does not depend on any external data. Moreover, calls to the same smart contract are executed in the order of messages in the receive queue. This enables transactions in TON to be executed in parallel efficiently, without concerns about conflicts.However, this design also introduces some new challenges. For DApp developers, their familiar development paradigm will be disrupted in the following ways:

  1. Asynchronous Smart Contract Calls: In TON, it is impossible to atomically call external contracts or access external contract data within smart contracts. In Solidity, for instance, it is straightforward for Contract A’s function1 to call Contract B’s function2 or access certain state data through Contract C’s read-only function3, all in a single transaction. However, in TON, this cannot be achieved. Any interaction with external smart contracts will be executed asynchronously by creating new transactions, referred to as internal messages initiated by smart contracts. The execution process cannot be blocked to await the result.

For example, if we are developing a DEX and follow the common EVM paradigm, we typically have a unified router contract to manage transaction routing, while each pool independently manages the LP data for specific trading pairs. Let’s say we have two pools: USDT-DAI and DAI-ETH. When a user wants to buy ETH directly with USDT, they can use the router contract to sequentially interact with these two pools in a single atomic transaction. However, in TON, this process is not as straightforward and requires a different development approach. If we try to reuse this EVM paradigm, the information flow would involve an external message initiated by the user and three internal messages to complete the transaction (note that this example is to highlight the differences; in actual development, even the ERC20 paradigm would need to be redesigned).

  1. Careful consideration is required for error handling in cross-contract calls, designing appropriate bounce functions for each inter-contract interaction. In mainstream EVM systems, if an error occurs during transaction execution, the entire transaction is rolled back to its initial state. This is straightforward in a serial single-threaded model. However, in TON, since inter-contract calls are executed asynchronously, if an error occurs at a later stage, the earlier successfully executed transactions have already been confirmed, potentially causing issues. Therefore, TON has introduced a special message type called a bounce message. If an error occurs in the subsequent execution of an internal message, the triggered contract can use the bounce function reserved in the triggering contract to reset certain states in the triggering contract.

  2. In complex scenarios, transactions that are received first may not be completed first, so you cannot assume a specific execution order. In an asynchronous and parallel smart contract system, defining the processing order can be challenging. This is why every message in TON has its logical time, known as Lamport time (lt). It helps determine which event triggered another and what validators need to process first. In a simple model, transactions received first are executed first.

In this model, A and B represent two smart contracts. If msg1_lt < msg2_lt, then tx1_lt < tx2_lt in terms of sequence.

However, in more complex situations, this rule can be broken. The official documentation provides an example: suppose we have three contracts, A, B, and C. In one transaction, A sends two internal messages, msg1 and msg2, one to B and the other to C. Although they are created in a specific order (msg1 first, then msg2), we cannot be certain that msg1 will be processed before msg2. This uncertainty arises because the routes from A to B and from A to C might differ in length and validator sets. If these contracts are in different shard chains, one message might take several blocks to reach the target contract. Therefore, there are two possible transaction paths, as illustrated.

  1. In TON, the persistent storage for smart contracts uses a directed acyclic graph (DAG) structure with cells as units. Data is compactly compressed into a cell according to specific encoding rules and extends downward in a DAG manner. This contrasts with the hashmap-based structure used in EVM for state data. Due to different data access algorithms, TON assigns varying gas prices for processing data at different depths; deeper cell data processing requires more gas. Consequently, TON faces a type of DOS attack, where malicious users flood a smart contract with a large number of junk messages, filling all the shallow cells. This increases storage costs for honest users. In contrast, EVM’s hashmap has a query complexity of O(1), ensuring consistent gas costs and avoiding similar issues. Therefore, TON Dapp developers should avoid using unbounded data types in smart contracts. When unbounded data types are necessary, they should be partitioned using sharding.

  1. Some features are less unique, such as the requirement for smart contracts to pay rent for storage. In TON, smart contracts are inherently upgradeable and come with native abstract account functions, meaning that all wallet addresses in TON are smart contracts, just uninitialized. Developers need to pay close attention to these aspects.

Disclaimer:

  1. This article is reprinted from [Theblockbeats]. All copyrights belong to the original author [Web3Mario]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Start Now
Sign up and get a
$100
Voucher!