Auditing Smart Contracts on TON

A technical guide to TON-specific vulnerabilities, asynchronous message flows, and smart contract security best practices.

TON has an execution model that differs in several important ways from EVM-based blockchains. Contracts communicate through messages rather than synchronous calls, each contract maintains its own state, and an operation involving several contracts can span multiple transactions. These differences affect how applications handle authorization, asset transfers, failures, and accounting.

TON contracts execute on the TON Virtual Machine (TVM). Tolk is the current official language for new smart contracts. FunC remains relevant to existing deployments, although it is now considered a legacy language. Tact is also used in the ecosystem. Regardless of the language, developers need to understand TON's message model, transaction phases, and cell-based data representation.

In short: A security review of a TON application needs to follow complete message flows. It should examine how incoming messages are authenticated, how state changes across transactions, what happens when messages fail, and how value and fees are handled. Jetton wallet verification, external-message replay protection, cell parsing, contract upgrades, and randomness also introduce specific security considerations.
How does TON's message model affect application security?

An internal message triggers a transaction on the receiving contract. That transaction can update the contract's persistent state and create outgoing messages to other contracts. Each recipient processes its own message in a separate transaction. The TON message and transaction model describes how these transactions are connected.

This means that a multi-contract operation is not atomic. A transaction can complete successfully and send a message that is processed later. If a subsequent step fails, the earlier transaction is not automatically rolled back.

Consider a withdrawal involving a vault and a token wallet. The vault may first reserve the user's balance and send a message requesting the token transfer. The token wallet processes that message separately. If the transfer fails, the vault needs to account for the failure and restore or otherwise resolve the user's claim. It cannot rely on the earlier transaction being undone.

The same issue arises when several operations are in progress. Suppose a user has enough balance for one withdrawal and submits two requests before either operation completes. If both requests check the same available balance without accounting for the first pending withdrawal, both may pass validation. The combined transfers can then exceed the user's actual balance.

Multiple message flows acting on shared state at different stages cause this problem, even when no race condition occurs within a single transaction.

An audit should trace each operation across the contracts involved. It should establish when balances and permissions are updated, when an operation is considered complete, and how the application handles requests that overlap with pending operations. Each message handler should validate the state relevant to its own transition rather than relying on a check performed earlier in the flow.

Query IDs and explicit operation states can help associate messages with the actions that initiated them. However, a query ID alone does not establish authorization or prove that an operation is still valid. The contract should also verify the expected sender, operation type, amount, and current pending state.

How should TON contracts authenticate incoming messages?

A message body does not establish who sent the message. A contract must validate the actual sender before accepting an instruction.

For internal messages, this usually means checking that the source address is an expected contract or wallet. A contract should not authorize an operation merely because the message contains a familiar operation code, address, or other value. An arbitrary contract can construct a message with the same format.

Jetton integrations are a particularly important example. Under the Jetton standard, TEP-74, each token has a master contract and individual wallet contracts for its holders. A recipient processing a transfer_notification must establish that the sending contract is the authentic wallet for the expected Jetton.

Checking the message format or trusting the wallet's claimed master address is not enough. The application should verify the wallet against the trusted master contract, including checking the wallet address derived by the master and the wallet implementation expected by the application. This is especially important for bridges and other applications that accept assets from multiple Jettons.

The risk is not theoretical. In May 2026, the TAC Bridge was exploited after accepting messages from a counterfeit Jetton wallet. The bridge did not verify the sender wallet's code and master relationship, allowing an attacker to present unbacked tokens as legitimate assets and trigger corresponding minting on the destination network. The TAC Bridge postmortem describes the attack and the missing validation steps.

The notification's fields also need to be parsed and checked. The application should establish which owner initiated the transfer, what amount was transferred, and whether the payload contains valid application-specific data. A notification from an authentic wallet does not automatically mean that every value in its payload is valid for the receiving application.

It is also important to distinguish the token transfer from the notification. Under TEP-74, a transfer notification is sent when the transfer includes a positive forward_ton_amount. Applications that rely on notifications for deposits must account for this behavior and define what happens when a transfer occurs without a notification.

The review should examine the complete trust relationship between the master contract, individual Jetton wallets, and the application receiving the notification. It should also check that the application credits only the amount actually transferred, validates the deposit payload, and cannot credit the same deposit more than once. TON's Jetton payment processing guide provides additional implementation details.

What happens when a TON message fails?

A TON transaction can fail at different stages, and the consequences depend on where the failure occurs. This matters because a multi-contract operation is not atomic: one contract may update its state successfully while a later transaction in the message flow fails.

TON transactions can include storage, credit, compute, action, and bounce phases. A failure during the compute phase may trigger a bounce if the incoming message is bounceable. An action-phase failure has different behavior: the transaction may produce a bounce when the relevant send action uses the +16 flag. The +2 flag can suppress certain action errors, allowing the transaction to complete while skipping failed actions.

This creates an important accounting risk. Consider a Jetton transfer: the sender's wallet processes the transfer and sends a message to the recipient's wallet. If the recipient's transaction fails, the sender's wallet must correctly handle the resulting bounce. If it does not, the sender's balance may be reduced without the recipient receiving the tokens.

A secure implementation must account for both successful and failed message delivery. In particular, contracts should:

  • Identify bounced messages and handle them through an explicit recovery path.
  • Restore or reconcile state changes when a downstream operation fails.
  • Avoid treating a sent message as proof that the intended operation completed.
  • Ensure that bounce handling cannot be triggered repeatedly to restore funds more than once.
  • Test failures at each stage of the message flow, including cases where a message cannot be delivered or an outbound action is skipped.

Bounced messages have a bounced flag, and their body begins with the 0xffffffff prefix. Contracts should check this flag and parse the bounced body carefully. They cannot assume the original message is available in full."

The key point is that sending a message and completing an operation are two different things. Contracts must preserve consistent accounting across both successful and failed message flows.

How should external messages be protected against replay?

External messages allow an outside party to submit a request to a contract. Unlike internal messages, they do not carry Toncoin and do not have an authenticated on-chain sender. The contract must establish whether the request is authorized before accepting it.

Wallet contracts commonly use signatures, sequence numbers, and expiration times. The signature authenticates the request, the sequence number prevents an already processed request from being reused, and the expiration time limits how long the signed request remains valid. TON's message signing guide describes the available signature mechanisms.

These checks must cover the operation being authorized. A signature should bind all relevant parameters, including the destination, amount, operation type, and any other values that affect execution. It should also include sufficient domain information to prevent the same signed request from being accepted in another contract or context.

This matters because a valid signature can be exposed before its intended transaction is processed. If the signature does not bind the recipient or other critical parameters, an attacker may copy the request and submit a modified transaction using the same signature. TON's security guidance discusses this type of signature front-running.

Replay protection also needs to be maintained when execution fails. A contract should not assume that updating a sequence number is sufficient without understanding how the transaction handles state changes and exceptions.

The order of validation and message acceptance is important. An incoming external message initially receives a limited gas credit. The ACCEPT instruction allows the contract to continue processing at the contract's expense. It does not authenticate the request or commit its state. See ACCEPT and gas credit.

A contract should perform inexpensive authorization and replay checks before accepting an external message. Otherwise, an attacker may repeatedly submit invalid messages and cause the contract to pay for their processing.

The interaction between ACCEPT and COMMIT also deserves attention. COMMIT saves the current persistent data and action list so that they can survive a later compute-phase exception. This can be useful for preserving replay-protection state, but it also changes the failure behavior of the operation. A contract must not commit a sequence number and then leave the corresponding request permanently incomplete without a recovery path.

An audit should check the exact data covered by signatures, domain separation, sequence-number and expiration checks, the placement of ACCEPT, and the behavior of replay protection when execution fails. It should also examine whether a request can be copied, modified, or submitted through another entry point.

How do send modes and message value affect TON contracts?

TON messages carry value, and a contract needs to account for the costs of computation, storage, and forwarding when it sends further messages. The amount attached to an incoming message is not necessarily the amount available for an outgoing transfer or a user balance credit.

In FunC, send_raw_message uses mode flags to determine how the outgoing message's value and fees are handled. Some commonly used modes have direct consequences for contract balances. The FunC standard library and TON's message sending modes documentation describe these behaviors:

  • Mode 64 carries the remaining value of the incoming message into the outgoing message, in addition to the value specified for that message.
  • Mode 128 sends the remaining balance of the contract.
  • Mode 1 pays forwarding fees separately from the message value.
  • Mode 2 ignores certain errors during the action phase.
  • Mode 16 requests a bounce if an outgoing action fails, subject to the applicable conditions.

These flags can be combined, and their interaction matters. In particular, +2 suppresses certain action errors and takes precedence over +16. A contract that expects an action failure to produce a bounce may therefore behave differently if the message also uses +2.

The use of mode 128 also deserves special attention. Sending the remaining contract balance can leave the contract without enough Toncoin to pay for future computation or storage. If this mode is reachable through an insufficiently restricted operation, an attacker may be able to drain funds needed for the contract's continued operation.

A common source of problems is updating application state without considering whether the corresponding outgoing action will succeed. For example, a contract may record a withdrawal as completed and create an outgoing transfer. If the action is skipped because of an error-handling flag, the contract's accounting may no longer match the assets transferred.

The review should examine the value and mode of every important outgoing message. It should establish which party pays the fees, how much value remains available after the operation, and whether the contract's state remains consistent when an outgoing action fails or is skipped. It should also check that the contract retains enough Toncoin to continue operating.

What should an audit check in TON's cell-based data model?

TON stores contract data and message bodies in cells. A cell can contain up to 1,023 bits and four references to other cells. More complex structures are represented as trees of cells, with dictionaries commonly used to store collections of key-value pairs. See the TON documentation on cells.

The layout of a cell is part of the data format. Contracts must agree on the order, width, and interpretation of fields when constructing and parsing messages. A difference in how two contracts interpret the same cell can change the meaning of an amount, address, operation identifier, or authorization field.

This really becomes important when contracts interact through custom message formats. The sender may serialize a value using one field width or reference layout, while the receiver expects another. If parsing is incomplete or validation is missing, the receiving contract may accept data that does not represent the intended operation.

For example, a contract may read the required fields from a message but fail to check whether additional data remains. If the application assumes that the message contains only those fields, trailing data may be interpreted differently by another component or accepted in a context where it was not intended. Similar problems arise when optional references, address formats, or integer widths are handled inconsistently.

Dictionaries introduce additional considerations. Their keys have defined bit widths, and lookups depend on the exact key representation. Incorrect key construction or parsing can cause a contract to access a different entry or fail to find an existing one. Iterating over large or attacker-influenced collections can also create gas-consumption problems.

An audit should examine both sides of every custom message format and compare the serialization and parsing logic. It should check that the contract validates the expected data and reference structure, handles optional fields consistently, rejects unexpected trailing data where appropriate, and does not rely on assumptions about cell contents that have not been enforced.

How should gas consumption and storage be reviewed in TON contracts?

A TON contract must have enough value to pay for computation, storage, and outgoing messages. An operation that is logically correct can still fail if it requires more gas than is available or if the contract cannot cover its ongoing storage costs.

Gas consumption depends on the work performed during a transaction. Parsing large data structures, iterating over dictionaries, processing multiple messages, and performing expensive computations can all affect whether an operation completes within the available gas. The TVM gas documentation describes the costs of different operations.

This matters when users can influence the amount of work a contract performs. For example, an operation that iterates over a collection whose size is controlled by users may become too expensive to execute. If that operation is required for withdrawals, liquidations, or other essential actions, the result can be a denial of service for users who depend on it.

The review should also consider the cost of message chains. A contract may have enough Toncoin to process an incoming message but attach insufficient value to the outgoing message needed to complete the operation. A downstream contract may then fail to execute because it cannot cover the required gas. The original contract must account for this possibility. Sending a message does not guarantee successful processing.

Storage costs affect the contract's lifecycle. TON accounts can become frozen when storage fees remain unpaid. In some circumstances, an account can eventually be deleted. The account status documentation describes these states and transitions. A protocol that depends on long-lived contracts needs to account for these costs and ensure that the necessary balances are maintained.

The review should examine worst-case gas consumption for important operations, particularly those that process user-controlled data. It should also establish how storage fees are funded, who is responsible for maintaining contract balances, and what happens if an account becomes frozen or unavailable.

How should TON contract upgrades and privileged operations be secured?

TON contracts can change their code if the existing implementation provides an upgrade path. In FunC, the SETCODE instruction creates an action that replaces the contract's code after the current transaction completes. Tolk provides corresponding upgrade functionality. See the TON guide to upgrading contracts.

The security of this mechanism depends on who can trigger it and what restrictions apply to the new code. An upgrade function that accepts arbitrary code from an insufficiently restricted sender can give an attacker control over the contract. Even when the upgrade authority is correctly protected, the upgrade process can introduce risks if the new implementation changes how persistent data is interpreted.

For example, a new version may expect a different storage layout or use a different interpretation of an existing field. If the upgrade does not account for the previous state, users may lose access to balances or the contract may process future messages incorrectly.

A related risk is accepting unvalidated data into persistent storage. If a contract replaces its stored state with a cell that does not follow the expected layout, later message handlers may fail when they try to parse it. This can make the contract unusable even if the upgrade itself was authorized.

The same review applies to privileged configuration changes. Administrators may be able to change fee parameters, trusted contracts, supported assets, or other values that affect application behavior. These permissions should be examined in the context of the protocol's economic and security assumptions.

An audit should identify every path that can change code, persistent storage, or privileged configuration. It should establish who controls it, check whether the transition preserves the protocol's required properties, and examine whether the upgrade process includes validation, migration, and recovery mechanisms. It should also consider whether a multisig or timelock is appropriate for high-impact changes.

What are the security considerations for randomness on TON?

TON provides built-in pseudo-random number generation, but its output is not automatically suitable for applications where an attacker can profit from influencing or predicting the result.

TON's random number generation uses a pseudorandom generator seeded with values derived from blockchain state, including block seeds generated by validators. This makes prediction harder for ordinary users, but it does not remove validator influence.

Validators can influence randomness by generating different seeds when producing blocks and choosing which blocks include external messages. This means a validator may be able to influence the result or the timing of an operation that depends on randomness. The TON randomness documentation describes these limitations and compares available approaches.

External-message entry points require particular care. Since external messages do not transfer Toncoin, a sender can submit requests repeatedly. If a contract generates a random result and performs an action based on it, an attacker may be able to keep submitting requests until a favorable result is obtained. Randomness generated in an external-message receiver should therefore not be treated as secure for high-value outcomes.

For applications involving significant value, the randomness mechanism should match the value at risk and the threat model. A commit-reveal scheme can reduce reliance on a single block producer, but it introduces its own requirements. In particular, the protocol needs to define what happens when a participant commits but does not reveal, and whether that participant can selectively prevent an unfavorable outcome.

An audit should examine where randomness is generated, which actors can influence the result, and whether users or validators can selectively retry, delay, or censor an operation based on its outcome.

Which invariants matter for TON applications?

An invariant is a property that must remain true across every valid state transition. In TON, these properties often involve several contracts and messages, so they need to account for pending operations, partial execution, and failures between transactions.

For a payment or Jetton application, relevant properties include:

  • A deposit is credited only after the corresponding assets have been received.
  • Only the expected Jetton wallet can trigger a deposit notification.
  • A transfer or deposit cannot be credited more than once.
  • The amount credited corresponds to the amount actually transferred.
  • A failed transfer restores or otherwise resolves the sender's accounting.

For a staking or lending protocol, relevant properties include:

  • Withdrawals cannot exceed the user's available balance.
  • Pending withdrawals are accounted for when validating new requests.
  • A failed downstream message cannot leave accounting in a state that permits duplicate claims.
  • Rewards and liabilities remain consistent with the assets held by the protocol.
  • Liquidations and repayments cannot be executed against stale or already consumed state.

For a bridge, relevant properties include:

  • Only authorized messages can trigger minting or unlocking.
  • The source asset and its corresponding destination asset are correctly identified.
  • A message cannot be executed more than once.
  • Source-chain and destination-chain accounting remain consistent.
  • Failed or delayed messages have a defined recovery path.

These properties should be checked across the full operation, which extends beyond any single message handler. A contract may enforce its local rules correctly while the overall protocol still allows an operation to be repeated, skipped, or left incomplete.

For example, a vault may correctly check a user's balance in its withdrawal handler. However, if it does not reserve the amount for a pending withdrawal, a second message may pass the same check before the first transfer is completed. The relevant invariant is that completed withdrawals plus pending withdrawals never exceed the user's available claim, which a balance check on each withdrawal alone does not enforce.

How should TON contracts be tested and formally verified?

Testing should cover both normal execution and the failure paths that arise from TON's message model. This includes delayed messages, bounced messages, duplicate requests, insufficient message value, and operations that fail after an earlier transaction has already changed state.

Tests should also cover unauthorized senders, invalid signatures, expired external requests, malformed cell data, unexpected message fields, and boundary values in financial calculations. For applications involving several contracts, tests need to exercise the complete message flow and check the final state of every contract involved.

The TON Sandbox provides an environment for running contract tests and simulating blockchain interactions. It can be used to examine transaction results, message delivery, and the behavior of contracts under different conditions.

Tests should go beyond a single successful sequence and vary the order and timing of messages.. For example, a withdrawal flow should be tested with two overlapping requests, a downstream failure, a bounce, a retry, and a late response arriving after the operation has already been cancelled or resolved.

Formal verification can provide stronger guarantees for properties that can be expressed precisely. For TON applications, useful properties include:

  • A state transition can only be triggered by an authorized sender and a valid message.
  • A pending operation cannot be finalized more than once.
  • A balance or liability cannot be reduced or increased incorrectly after a bounce.
  • The total value of completed and pending withdrawals cannot exceed the user's claim.
  • A replayed or delayed message cannot cause a second execution of an already processed operation.

The verification scope matters. Proving that an individual message handler preserves a local invariant does not automatically prove that the complete multi-contract operation is safe. The specification needs to account for the assumptions made about other contracts, the possible order of messages, and the failure behavior of the system.

Testing and formal verification should therefore be based on a clear description of the protocol's intended behavior, including its message flows, intermediate states, and recovery paths.

What should a team building on TON prepare before an audit?

A security review is more effective when the development team can explain the intended behavior of the application and the assumptions each contract makes about the others.

Before a review, a team should prepare:

  • A description of the contract architecture and the responsibilities of each contract.
  • Message formats, operation identifiers, and the expected sender for each message type.
  • Message-flow diagrams covering successful execution, failures, bounces, retries, and overlapping operations.
  • The expected behavior for delayed, duplicated, and failed messages.
  • The authorization model, including signatures, sequence numbers, expiration checks, and privileged roles.
  • The accounting model for attached value, execution fees, forwarding fees, and contract balances.
  • The cell layouts and dictionary formats used for persistent storage and message bodies.
  • The Jetton master addresses, wallet implementations, and other trusted external contracts.
  • The upgrade mechanism and the authorities that can change code, storage, or configuration.
  • The invariants the application is expected to preserve.
  • Tests covering normal execution, failure paths, and interactions across contracts.

These materials provide a baseline for checking whether the implementation matches the intended design. They also help identify assumptions that are not enforced by the code.

Further reading

Frequently asked questions

What is a TON smart contract audit?

A TON smart contract audit is a security review that follows complete message flows across contracts and transactions. It examines how incoming messages are authenticated, how state changes between transactions, what happens when messages fail, and how value and fees are handled. It also covers Jetton wallet verification, external-message replay protection, cell parsing, contract upgrades, and randomness, and it applies to contracts written in Tolk, FunC, or Tact.

Does Certora audit TON contracts?

Yes. Certora provides smart contract security audits and formal verification. If you're building on TON and are interested in a security review, get in touch with our team to discuss your project and its requirements.

What makes TON smart contracts different from EVM contracts?

TON contracts communicate through asynchronous messages, and each contract processes messages in its own transaction. An operation involving several contracts can therefore span multiple transactions. TON also uses cells to represent data and message bodies, making serialization and parsing important parts of the security review.

What is a bounced message on TON, and does it undo earlier transactions?

A bounce is a message returned to the sender when an internal message fails under the applicable conditions. The sender can then process the bounced message and update its state. A bounce does not automatically reverse transactions that have already completed in other contracts. The contract must implement the necessary accounting and recovery logic.

How do TON contracts prevent replay attacks?

External requests commonly use signatures, sequence numbers, and expiration times. The signature must cover the parameters that determine the operation, including its recipient and relevant context. Internal message flows also need operation identifiers and state checks to prevent duplicate processing.

What is the role of the Jetton master and wallet contracts?

Each Jetton has a master contract and separate wallet contracts for individual holders. Applications receiving Jettons should verify that the sending wallet is authentic and belongs to the expected master contract. They should also validate transfer notifications and account for the fact that notifications depend on the transfer's forward_ton_amount.

Are FunC and Tact contracts secure by default?

No. The language and its type system do not guarantee that application logic is correct. Developers still need to implement authorization, replay protection, message validation, failure handling, and consistent accounting.

STAY INFORMED

Security research, in your inbox.

Incident analysis, formal verification, and new tools from Certora.