LIVE PORTAL Telegram v11.8 API Synchronized Free Animated Stickers
translate Translated
admin_panel_settings ADMIN CONTROLS Guide #18471 • Beginner Basics

Web3 DApp Integration: TON Connect, Wallet Signing & Smart Contract Calls

[Telegram 198] Web3 DApp Integration: TON Connect, Wallet Signing & Smart Contract Calls
Module 08: Bots, TMA Mini Apps & Web3 TON Ecosystem

Step 098: Web3 DApp Integration: TON Connect, Wallet Signing & Smart Contract Calls

98% Complete (98/100)

The true convergence of Telegram's 950-million-user reach and decentralized finance lives inside The Open Network (TON). Through TON Connect 2.0, Telegram Mini Apps (TMA) bridge seamlessly into non-custodial Web3 wallets (Tonkeeper, Telegram Wallet @wallet, MyTonWallet) without exposing private seed phrases or forcing users out of the chat client. In Telegram 198, we dissect the end-to-end Web3 DApp stack: implementing the cryptographic ton_proof authentication handshake to eliminate server replay attacks, constructing binary Bag of Cells (BOC) payloads for Jetton transfers (USDT, NOT, DOGS), and executing on-chain smart contract transactions with real-time explorer trace verification.

Web3 DApp Integration & TON Connect Banner
Figure 98.1: TON Connect 2.0 Universal Bridge, Cryptographic Proofs & BOC Smart Contract Pipelines. TELEGRAM 198 • TON CONNECT 2.0

1. Architectural Foundation: The TON Connect 2.0 Universal Bridge

TON Connect 2.0 establishes a secure, bi-directional communication channel between a web-based DApp and a non-custodial crypto wallet. When running inside a Telegram Mini App on mobile, connection requests dispatch native deep links (tc://...); in desktop browsers, communication relays over an encrypted HTTP Server-Sent Events (SSE) bridge server using ephemeral Curve25519 keypairs:

Layer 1

TonConnect UI SDK

React/Vite integration with @tonconnect/ui-react. Renders native connect modal, displays wallet address, and auto-restores active sessions on reload.

Layer 2

SSE Cryptographic Bridge

DApp and Wallet negotiate shared secrets via Curve25519 ECDH. Messages relay across bridge endpoints with zero plaintext visibility to bridge operators.

Layer 3

Zero-Trust Signing

Your DApp never sees private keys. The wallet prompts the user with the exact recipient, Jetton amount, and network gas fee before cryptographic authorization.

2. The ton_proof Handshake: Cryptographic On-Chain Authentication

Never authenticate users by trusting their wallet address sent in a client request. Malicious users can send any address. Instead, enforce ton_proof:

ton_proof_backend.py (Ed25519 Verification) FastAPI / TonLib
import hashlib
import time
from nacl.signing import VerifyKey

def verify_ton_proof(proof_data: dict, app_domain: str, server_payload: str) -> bool:
    # 1. Validate payload matches dynamic nonce issued by backend
    if proof_data['payload'] != server_payload:
        return False

    # 2. Check 15-minute TTL expiration
    timestamp = proof_data['timestamp']
    if abs(time.time() - timestamp) > 900:
        return False

    # 3. Reconstruct signed message buffer
    # buffer = 'ton-proof-item-v2/' + wc + addr_hash + domain_len + domain + timestamp + payload
    domain_bytes = app_domain.encode('utf-8')
    prefix = b"ton-proof-item-v2/"
    wc_byte = proof_data['workchain'].to_bytes(4, 'little', signed=True)
    addr_hash = bytes.fromhex(proof_data['address'])
    domain_len = len(domain_bytes).to_bytes(4, 'little')
    ts_bytes = timestamp.to_bytes(8, 'little')
    payload_bytes = server_payload.encode('utf-8')

    msg = prefix + wc_byte + addr_hash + domain_len + domain_bytes + ts_bytes + payload_bytes
    msg_hash = hashlib.sha256(msg).digest()
    full_msg_hash = hashlib.sha256(b"\xff\xff" + b"ton-connect" + msg_hash).digest()

    # 4. Verify Ed25519 signature against wallet public key
    public_key_bytes = bytes.fromhex(proof_data['public_key'])
    signature_bytes = bytes.fromhex(proof_data['signature'])

    try:
        verify_key = VerifyKey(public_key_bytes)
        verify_key.verify(full_msg_hash, signature_bytes)
        return True # Authenticated! Mint JWT session token.
    except Exception:
        return False

3. Bag of Cells (BOC) Construction & Smart Contract Calls

Everything in TON data structures is serialized as a Bag of Cells (BOC). When initiating token transfers or interacting with custom Tact / FunC smart contracts (such as Jetton transfers conforming to TEP-74), you build binary cell trees:

transferJetton.ts (@ton/core & @tonconnect/ui) TEP-74 Standard
import { beginCell, toNano, Address } from '@ton/core';
import { tonConnectUI } from './tonConnect';

async function sendJettonPayment(jettonWallet: string, recipient: string, amountUnits: bigint) {
  // 1. Build TEP-74 Jetton transfer BOC cell
  const forwardPayload = beginCell()
    .storeUint(0, 32) // 0 means simple text comment follows
    .storeStringTail("TGWAY VIP Subscription #198")
    .endCell();

  const bodyCell = beginCell()
    .storeUint(0x0f8a7ea5, 32)           // opcode: transfer
    .storeUint(0, 64)                   // query_id
    .storeCoins(amountUnits)            // Jetton amount (e.g. 50 USDT = 50,000,000)
    .storeAddress(Address.parse(recipient)) // destination address
    .storeAddress(Address.parse(recipient)) // response_destination for excess TON
    .storeBit(0)                        // custom_payload (null)
    .storeCoins(toNano('0.02'))          // forward_ton_amount (triggers notification)
    .storeBit(1)                        // forward_payload stored as cell reference
    .storeRef(forwardPayload)
    .endCell();

  // 2. Dispatch transaction via TON Connect UI
  const tx = {
    validUntil: Math.floor(Date.now() / 1000) + 360,
    messages: [{
      address: jettonWallet,
      amount: toNano('0.05').toString(), // attached gas fee
      payload: bodyCell.toBoc().toString('base64')
    }]
  };

  const result = await tonConnectUI.sendTransaction(tx);
  console.log("Transaction BOC signed & dispatched:", result.boc);
}

4. Interactive Lab: TON Connect 2.0 DApp & Wallet Signing Simulator

Experience the entire Web3 DApp flow inside Telegram. Select your preferred wallet, perform the ton_proof cryptographic handshake, compile a serialized Jetton BOC payload, and broadcast to the blockchain:

TON CONNECT v2.0 Web3 DApp Signing Simulator
WALLET DISCONNECTED
TON CONNECT 2.0 EVENT STREAM MAINNET READY
[DAPP CORE] Initialized TonConnectUI instance. Select provider and click 'Connect Wallet'.

5. Master Architectural Blueprint & Web3 Stack

Inspect the complete Web3 DApp blueprint showing TON Connect 2.0 layers, the 4-step cryptographic ton_proof handshake sequence, and TEP-74 Jetton BOC serialization:

TON Connect Web3 Blueprint (2:3)
🔍 Click the blueprint to launch interactive high-resolution lightbox inspector

6. Web3 Production FAQs & Security Directives

Q1: Why is ton_proof mandatory if the client already provides the wallet address?

Any client can forge an HTTP request claiming to own a whale wallet address (e.g. holding 100,000 TON). ton_proof proves possession of the private key by signing a dynamic backend-generated nonce over your domain with an Ed25519 cryptographic signature.

Q2: What is the difference between raw TON transfer and a Jetton transfer?

A simple TON transfer sends native coin directly to the recipient's address. A Jetton transfer (such as USDT or NOT) requires sending an internal smart contract message to the sender's Jetton Wallet contract with opcode 0x0f8a7ea5, which burns/updates balance and dispatches an internal notification to the recipient.

Q3: How do I verify on-chain that a transaction actually completed successfully?

When sendTransaction returns the signed BOC, extract the transaction hash or poll TON Center API v2 (or TON Access) for incoming transactions on your receiving address with matching forward_payload memo string.

Q4: Where must the tonconnect-manifest.json file be hosted?

It must be served over HTTPS on a publicly accessible domain with valid CORS headers (Access-Control-Allow-Origin: *). It contains your DApp name, high-res icon URL, and terms of service link shown inside wallet authorization sheets.

Q5: Why do Jetton transactions attach 0.05 TON if paying in USDT?

Smart contracts on TON require execution gas and storage rent. The attached 0.05 TON pays validator computational fees. Any unused gas is automatically refunded back to the sender's address via the response_destination parameter.

MODULE 08 • THE PENULTIMATE STEP Next Architecture Milestone: Step 099

Advancing to Step 099: Developer Roadmap: AI Agents, LangChain & Autonomous Ecosystem

You are standing at the threshold of the 100-step summit! In Step 099, we unite modern Large Language Models with the Telegram platform: architecting autonomous AI Agents with LangChain, function calling tools, vector search RAG memory, and multi-agent supervisory networks.

Continue to Step 099 (AI Agents & LangChain) →
← Prev: [Telegram 197] Enterprise Customer Support Ticketing Bot: Threading, CRM & Analytics Next: [Telegram 199] Developer Roadmap: AI Agents, LangChain & Autonomous Telegram Ecosystem →
admin_panel_settings ADMIN Guide #18471 Actions
Enlarged Preview
Click anywhere outside or press ESC to close viewer
smart_display Telegram Video Short
1080p HD
Official Source: @TelegramTips Post #44 Press ESC or click outside to close