> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tac.build/llms.txt
> Use this file to discover all available pages before exploring further.

# Cross-Chain Messaging

> How messages flow securely between TON and TAC EVM through the TON Adapter's validation and consensus system

Cross-chain messaging is the foundation of TAC's hybrid dApp functionality. It enables secure communication between TON users and EVM smart contracts through a structured system of message creation, validation, and execution. Understanding this messaging system helps developers build more effective applications and troubleshoot issues when they arise.

## Message Lifecycle Overview

Every cross-chain operation in TAC follows a predictable lifecycle that ensures security and reliability while maintaining reasonable performance for application use cases.

<Steps>
  <Step title="Message Creation" icon="plus">
    User initiates an action in a hybrid dApp, triggering the creation of a
    structured cross-chain message (usually done automatically via TAC SDK) containing operation details and asset
    information.
  </Step>

  <Step title="Sequencer Detection" icon="radar">
    Multiple sequencers detect the message simultaneously and begin independent
    validation processes to ensure message integrity.
  </Step>

  <Step title="Consensus Formation" icon="handshake">
    Sequencer groups reach internal consensus, then coordinate across groups to
    form network-wide agreement on message validity.
  </Step>

  <Step title="Target Execution" icon="play">
    Validated messages are executed on the target chain with cryptographic proof
    of consensus approval.
  </Step>

  <Step title="Result Delivery" icon="check">
    Execution results and any return assets flow back through the same secure
    messaging system to the original user.
  </Step>
</Steps>

## Message Structure

Cross-chain messages contain all the information needed for secure validation and execution across different blockchain architectures.

### Core Message Components

Every message includes essential metadata and operation-specific data.
The json example below is not a comprehensive structure but rather a general idea:

```javascript theme={null}
{
  timestamp: 1640995200,              // TON blockchain timestamp
  target: "0x742d35Cc6473...",        // Target smart contract address
  methodName: "swapTokens(bytes,bytes)", // Method signature
  arguments: "0x1234...",             // Encoded method parameters
  caller: "EQAbc123...",              // Original TON caller address
  mintTokens: [...],                  // Tokens to mint on TAC EVM
  unlockTokens: [...]                 // Tokens to unlock from previous operations
}
```

### TAC Header Information

The TON Adapter automatically augments messages with additional metadata that proxy contracts receive:

<Accordion title="TAC Header Fields" icon="info">
  * **shardsKey**: Unique identifier linking related transactions when multiple tokens are involved in a single operation.

  * **timestamp**: Block timestamp from the TON blockchain where the user's original message was created.

  * **operationId**: Unique identifier generated by TAC infrastructure for tracking and validation purposes.

  * **caller**: The user's wallet address that initiated the cross-chain operation.

  * **extraData**: Additional data provided by sequencers during execution, typically empty but available for special use cases.

  For the detailed header info please refer to the SDK's docs [here](/why-tac/cross-chain-operations/cross-chain-messaging#tac-header-fields).
</Accordion>

### Parameter Encoding

Application-specific parameters are encoded using standard Ethereum ABI encoding:

```javascript theme={null}
// Example: DEX swap parameters
const abi = new ethers.AbiCoder();
const swapParams = abi.encode(
  ["tuple(address,address,uint256,uint256,address,uint256)"],
  [[tokenIn, tokenOut, amountIn, minAmountOut, recipient, deadline]]
);
```

This encoding ensures that EVM proxy contracts can decode parameters correctly while maintaining compatibility with standard Ethereum tooling.

## Validation Process

The TON Adapter employs multiple layers of validation to ensure message integrity and prevent malicious activity.

### Asset Verification

* **Transfer Validation**: Sequencers verify that actual token transfers match the amounts specified in cross-chain messages. This prevents attempts to claim false transfer amounts or access unauthorized funds.

* **Metadata Consistency**: Token information and operation parameters are cross-referenced to ensure consistency throughout the validation process.

### Cryptographic Validation

<Tabs>
  <Tab title="Merkle Proofs">
    * **Inclusion Proofs**: Every executed message includes cryptographic proof of
      inclusion in a consensus-approved Merkle tree.
    * **Tamper Resistance**: Merkle proofs make it cryptographically impossible
      to modify messages after consensus without detection.
    * **Independent Verification**: Any party can verify message authenticity
      using the public Merkle proofs.
  </Tab>

  <Tab title="Consensus Signatures">
    * **Multi-Group Agreement**: Messages require agreement from multiple
      independent sequencer groups before execution.
    * **Economic Security**: Sequencer groups stake significant collateral, creating financial incentives
      for honest validation.
    * **Threshold Requirements**: The network requires sufficient group participation to ensure security while maintaining
      operational efficiency.
  </Tab>
</Tabs>

## Epoch-Based Processing

TAC organizes message processing into time-based epochs that provide structure and predictability to cross-chain operations.

### Epoch Structure

**Deterministic Timing**: Each epoch is calculated using a precise formula that ensures all sequencers work with the same time boundaries:

```
EpochId = (currentTime - protocolDeployTime) / epochDuration
```

**Processing Windows**: Messages are collected and processed within specific timeframes:

```
[protocolDeployTime + EpochId × epochDuration,
 protocolDeployTime + (EpochId + 1) × epochDuration]
```

### Benefits of Epoch Processing

* **Ordered Processing**: All sequencers process the same set of messages in each epoch, preventing timing-based attacks and ensuring consistency.

* **Batch Efficiency**: Processing messages in batches is more efficient than individual handling and provides better consensus guarantees.

* **Predictable Latency**: Users and applications can estimate processing times based on epoch duration and current network status.

## Message Types and Flows

Different types of cross-chain operations follow distinct patterns that affect how messages are structured and processed.

### One-Way Messages (TON → TAC and TAC → TON)

* **Simple Operations**: Basic token transfers, contract calls that don't require return values, or operations where results remain on the EVM side.

* **Message Flow**: TON or TAC EVM user → TON Adapter → Sequencer validation → TON or TAC EVM execution → Completion notification.

* **Use Cases**: Token bridges and deposits, simple contract interactions, or operations where users only need confirmation of completion.

* **Usage**:

  TAC → TON: [`bridgeTokensToTON`](https://github.com/TacBuild/tac-sdk/blob/main/docs/sdks/tac_sdk.md#bridgetokenstoton) in SDK

  TON → TAC: [`sendCrossChainTransaction`](https://github.com/TacBuild/tac-sdk/blob/main/docs/sdks/tac_sdk.md#sendcrosschaintransaction) in SDK

### Round-Trip Messages (TON → TAC → TON)

* **Complex Operations**: Operations that generate results or assets that need to be returned to the original TON user.

* **Extended Flow**: Includes an additional return path where EVM proxy contracts create new messages to send results back through the TON Adapter.

* **Use Cases**: Token swaps, liquidity operations, or any interaction where users expect to receive different assets or data back.

* **Usage**:

  TON → TAC → TON: [`sendCrossChainTransaction`](https://github.com/TacBuild/tac-sdk/blob/main/docs/sdks/tac_sdk.md#sendcrosschaintransaction) in SDK

### Rollback Operations

<Tip>
  When operations fail on the target chain, TAC automatically initiates rollback
  procedures to protect user assets.
</Tip>

* **Automatic Triggers**: Failed executions on either chain automatically trigger rollback message creation to return assets safely.

* **Asset Protection**: Rollback messages ensure that locked or transferred assets are returned to users when operations cannot complete successfully.
