DEV Community

Gerus Lab
Gerus Lab

Posted on

How We Ship AI-Powered Telegram Mini Apps on TON — Architecture Patterns That Actually Work

Telegram Mini Apps (TMAs) are eating the web. With 950M+ Telegram users and TON blockchain native integration, TMAs have become the fastest distribution channel for crypto products in 2026. But adding AI to the mix? That's where most teams stumble.

Over the past year at Gerus Lab, we've shipped multiple production TMAs with AI and on-chain logic. This article breaks down the architecture patterns we use — with real code and real tradeoffs.

Why Telegram Mini Apps + AI + TON?

The thesis is simple: Telegram is where the users are. TON is where the money moves. AI is what makes the product smart.

But combining all three creates genuine architectural challenges:

  • TMA frontend runs inside Telegram's WebView (limited APIs, quirky lifecycle)
  • TON smart contracts need deterministic logic (no AI inside contracts)
  • AI inference is async and expensive (you can't block a wallet transaction on GPT)

The solution is a three-layer architecture we've battle-tested across projects like ITOhub (social asset marketplace on TON) and TON DCA (non-custodial dollar-cost averaging protocol).

The Architecture: Three Layers, Clear Boundaries

┌─────────────────────────────────┐
│  TMA Frontend (React/Next.js)   │
│  TonConnect · Mini App SDK      │
├─────────────────────────────────┤
│  Backend (NestJS)               │
│  BullMQ · AI Pipeline · Indexer │
├─────────────────────────────────┤
│  TON Smart Contracts (Tact/FunC)│
│  Vaults · FSM · Swaps           │
└─────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Layer 1 — TMA Frontend. React or Next.js app served inside Telegram's WebView. Handles UI, TonConnect wallet linking, and user interactions. Keep it thin.

Layer 2 — Backend orchestrator. This is where AI lives. NestJS with BullMQ for job queues, an indexer that watches on-chain events, and AI pipelines that process data asynchronously.

Layer 3 — Smart contracts. Pure deterministic logic. Tact or FunC. No AI here — contracts handle settlements, vaults, and state machines.

Pattern 1: AI as an Async Oracle

The biggest mistake teams make is trying to put AI in the critical path of a transaction. Don't.

Instead, treat AI as an async oracle — it observes, analyzes, and suggests, but never blocks on-chain execution.

Here's how we built this for ASHKA, our AI analytics dashboard:

// Backend: AI analysis runs as a BullMQ job
@Processor('ai-analysis')
export class AnalysisProcessor {
  constructor(
    private readonly openai: OpenAIService,
    private readonly cache: RedisService,
  ) {}

  @Process()
  async analyze(job: Job<AnalysisPayload>) {
    const { userId, dataPoints } = job.data;

    // AI inference — async, non-blocking
    const insight = await this.openai.chat({
      model: 'gpt-4o',
      messages: [{
        role: 'system',
        content: 'Analyze trading patterns. Return JSON with: trend, confidence, suggestion.'
      }, {
        role: 'user', 
        content: JSON.stringify(dataPoints)
      }],
      response_format: { type: 'json_object' }
    });

    // Cache result — frontend polls or uses WebSocket
    await this.cache.set(
      `insight:${userId}`, 
      insight, 
      { ttl: 300 }
    );

    return insight;
  }
}
Enter fullscreen mode Exit fullscreen mode

The TMA frontend polls or subscribes via WebSocket. The user sees real-time AI insights without ever waiting for a blockchain confirmation to include AI logic.

Result on ASHKA: API response <200ms, AI accuracy >90% on pattern detection.

Pattern 2: FSM-Driven Deal Lifecycle

For ITOhub — a marketplace where users buy and sell Telegram channels — we needed a deal flow that's partially on-chain, partially off-chain, and AI-assisted.

The answer: Finite State Machine (FSM) that spans both layers.

CREATED → FUNDED → ORACLE_CHECK → PROGRESS_CONFIRMED → COMPLETED
   ↓         ↓          ↓
CANCELLED  REFUNDED   DISPUTED
Enter fullscreen mode Exit fullscreen mode

The smart contract (FunC) handles CREATED → FUNDED and PROGRESS_CONFIRMED → COMPLETED — money movements only. The backend handles ORACLE_CHECK where AI verifies the asset transfer actually happened:

// Simplified oracle verification
async verifyChannelTransfer(dealId: string): Promise<boolean> {
  const deal = await this.dealRepo.findOne(dealId);

  // Check Telegram API: is the buyer now admin?
  const chatInfo = await this.telegram.getChatAdministrators(
    deal.channelId
  );

  const buyerIsAdmin = chatInfo.some(
    admin => admin.user.id === deal.buyerId
  );

  if (buyerIsAdmin) {
    // Trigger on-chain confirmation via oracle wallet
    await this.tonService.confirmDeal(dealId);
    return true;
  }

  return false;
}
Enter fullscreen mode Exit fullscreen mode

The on-chain vault holds funds in escrow. The off-chain oracle (our backend) confirms delivery. AI assists in dispute resolution by analyzing chat logs and transfer timestamps.

Pattern 3: O(1) Index Model for DCA

For TON DCA, we built a non-custodial dollar-cost averaging protocol. Users deposit TON, and the contract automatically swaps into target tokens at regular intervals via STON.fi v2.1.

The challenge: tracking rewards across thousands of users without iterating.

We used a MasterChef-style accumulator — O(1) complexity regardless of user count:

// Simplified Tact contract logic
contract DCAVault {
    accRewardPerShare: Int = 0;
    totalDeposited: Int = 0;

    receive(msg: Deposit) {
        let pending = (self.accRewardPerShare * msg.amount) / PRECISION;
        // Update user debt and global state
        self.totalDeposited += msg.amount;
    }

    // Called by keeper bot after each swap
    receive(msg: DistributeReward) {
        require(sender() == self.keeper, "Unauthorized");
        self.accRewardPerShare += (msg.reward * PRECISION) / self.totalDeposited;
    }
}
Enter fullscreen mode Exit fullscreen mode

The NestJS indexer watches for swap events and triggers the next DCA cycle. No AI in the contract — but the backend uses AI to optimize swap timing based on market volatility patterns.

Pattern 4: Proxy-TON for Gas Abstraction

One UX killer in TMAs: users need TON for gas even when they're swapping other tokens. For TON DCA, we implemented a proxy-ton mechanism — the backend sponsors gas for small transactions:

// Gas sponsorship for better UX
async sponsorTransaction(userOp: UserOperation) {
  if (userOp.estimatedGas < this.MAX_SPONSORED_GAS) {
    // Backend wallet pays gas, deducts from user's next reward
    const sponsoredTx = await this.tonWallet.sendWithSponsorship(
      userOp.to,
      userOp.payload,
      { gasFrom: this.sponsorWallet }
    );
    return sponsoredTx;
  }
  // Large txs: user pays own gas
  return userOp;
}
Enter fullscreen mode Exit fullscreen mode

This alone increased our conversion rate by 3x on first-time TMA users.

Lessons From Production

After shipping 5+ TMAs with varying degrees of AI and on-chain logic, here's what we know:

1. Never trust the WebView. Telegram's WebView has different behavior on iOS vs Android. Always test both. Viewport height changes when the keyboard opens — handle it or your UI breaks.

2. TonConnect is your friend. Don't build custom wallet connections. TonConnect handles session persistence, deep linking, and multi-wallet support.

3. Queue everything AI-related. BullMQ with Redis. Never call OpenAI synchronously in a request handler. Users will see timeouts on 3G connections.

4. Smart contracts should be boring. All the interesting logic belongs in the backend. Contracts handle money — that's it. The less code on-chain, the fewer attack surfaces.

5. Index, don't poll. Watch blockchain events with an indexer (we use a NestJS service with TON HTTP API v2). Polling is wasteful and slow.

The Stack We Keep Coming Back To

Layer Tech Why
Frontend Next.js + TonConnect SSR for SEO, great DX
Backend NestJS + BullMQ Type-safe, job queues built in
AI OpenAI API + Redis cache Structured outputs, fast cache
Contracts Tact (new) / FunC (legacy) Tact has better DX, FunC for complex stuff
DB PostgreSQL + Prisma Reliable, great ORM
Infra Docker + VPS Simple, predictable costs

What's Next

We're currently exploring MCP (Model Context Protocol) for connecting AI agents directly to on-chain data sources — imagine an AI that can read your DCA performance and suggest rebalancing, all inside a Telegram chat.

The convergence of AI + crypto + messaging is the most interesting design space in 2026. TMAs are the distribution layer. TON is the settlement layer. AI is the intelligence layer.

If you're building in this space, we've probably hit the same walls. Reach out — we love comparing architecture scars.


We're Gerus Lab — a dev shop that builds AI-powered Web3 products, Telegram Mini Apps, and blockchain protocols. Check our case studies or hit us up if you have an interesting problem to solve.

Top comments (0)