Learning Platform
Глоссарий Troubleshooting
Урок 13.01 · 18 мин
Продвинутый
MonitoringObservabilityIndexingAlertsIncident Response

Production Operations для TON

Observability Stack

TON Production Observability Stack
Data Sources
Indexer
Metrics
Alerts

Key Metrics для TON Systems

Contract Health

MetricDescriptionAlert Threshold
Contract balanceTON balance for storage/gas< 1 TON (low balance)
Tx throughputTransactions per minuteSudden drop (system issue)
Bounce rate% of bounced messages> 5% (error in flows)
Gas usageAverage gas per tx type> 2x baseline (regression)
State sizeCells count in contract stateGrowing unbounded

DeFi Metrics

MetricDescriptionAlert
TVLTotal Value LockedDrop > 10% in 1 hour
Pool reserves ratioreserve_a / reserve_bDeviation from expected
Swap volumeDaily swap volumeAnomaly detection
Health factorsMin health factor across positions< 1.2 (approaching liquidation)
Oracle stalenessTime since last price update> 5 minutes

Indexing & Event Tracking

On-chain Event Tracking

TON events: emit log messages (external out messages)

Contract emits:
  send_raw_message(beginCell()
    .storeUint(0, 2)  // external out message
    .storeUint(op::swap_event, 32)
    .storeUint(query_id, 64)
    .storeCoins(amount_in)
    .storeCoins(amount_out)
    .storeAddress(user)
    .endCell(), 0);

Indexer picks up external messages → stores in DB → powers:
  - Analytics dashboards
  - Transaction history API
  - Alert triggers

Incident Response

Runbook Template

Incident: [Contract Balance Low]
Severity: P1 (Critical)
On-call: @defi-team

Steps:
1. Verify: check contract balance via tonapi
2. Assess: is contract at risk of freeze?
3. Immediate: top-up contract via admin multisig
4. Root cause: why balance dropped?
   - Increased storage (unbounded growth?)
   - High gas usage (new feature?)
   - Missing fee collection?
5. Fix: address root cause
6. Post-mortem: document and preventive action

Emergency Actions

Emergency Pause:
  Admin → Contract: set_paused(true)
  Contract: reject all non-admin messages when paused
  
  Use when: security vulnerability discovered, anomalous behavior

Emergency Upgrade:
  Admin → Contract: set_code(patched_code)
  Immediate effect, no timelock
  
  Use when: critical vulnerability, active exploit
  
  [WARN] Emergency upgrade = trust in admin
  → Post-emergency: audit + post-mortem required

SDK и Indexer Landscape (2026)

SDK эволюция: tonweb deprecated → @ton/core + @ton/ton

В 2020-2023 основным JS/TS SDK для TON был tonweb. Сейчас tonweb deprecated в пользу современной модульной экосистемы:

SDK эволюция:

[deprecated]  tonweb              -- одна большая библиотека, legacy
[modern]      @ton/core           -- core types: Cell, Address, BoC, BitString
              @ton/ton            -- Wallet contracts, providers, helpers
              @ton/crypto         -- крипто примитивы (key derivation, signing)
              @ton/test-utils     -- testing helpers

Что использовать в 2026:

ЗадачаПакет
Парсинг/построение Cell, BoC, Address@ton/core
Wallet operations, RPC client@ton/ton
Mnemonic, key derivation, signing@ton/crypto
Тесты контрактов@ton/sandbox + @ton/test-utils
// Современный stack:
import { Address, beginCell, Cell } from "@ton/core";
import { TonClient, WalletContractV5R1 } from "@ton/ton";
import { mnemonicToPrivateKey } from "@ton/crypto";

const client = new TonClient({ endpoint: "https://toncenter.com/api/v2/jsonRPC" });
WARNING

Не пишите новый код на tonweb

Если у вас существующий проект на tonweb — он продолжит работать, но миграция на @ton/core + @ton/ton рекомендуется при следующем major refactor. Все новые tutorials, examples, blueprints используют @ton/*. Найти TypeScript-разработчика с опытом tonweb становится всё сложнее.

Highload Wallet v5: для bulk operations

Для операций, которые требуют массовой отправки (airdrops, batch payouts, indexer-bots) нужен специализированный wallet contract:

WalletUse caseStatus
W5 (regular)User wallets, до 255 outputs/tx, gasless support (Battery)Default для новых установок
Highload V3Production-grade bulk operations (airdrop, payout)Stable, рекомендуется
Highload V2Legacy bulk walletDeprecated
V3R2/V4R2Legacy regular walletsMaintenance only

Highload v5 (Wallet V5) объединяет regular и highload pattern: до 255 outgoing messages в одной транзакции, plugin система, gasless via W5. Для большинства случаев в 2026 — это default.

Highload airdrop pattern (W5 / Highload V3):

Off-chain:
  recipients = load_recipients()  // 1M addresses
  batch_size = 250  // up to 255 outputs per W5 tx
  for batch in chunks(recipients, batch_size):
    msgs = build_outputs(batch)
    tx = wallet.createTransfer({ messages: msgs })
    sign and send

Throughput: ~250 transfers per ~1-2 seconds (Catchain 2.0)
1M transfers: ~4000 batches → ~2-3 hours total

Indexer landscape

Production dApp нуждается в индексере — backend, который парсит блоки TON и предоставляет structured query API. На рынке несколько решений:

Indexer & API провайдеры:

[Hosted, public API]
  TON Center v2/v3      -- Foundation-supported, public RPC + indexer
  TonAPI v2             -- Tonkeeper, high-level abstractions (Jetton/NFT objects)
  
[Self-hosted, open-source]
  ton-index-go          -- TON Center's Go-based indexer (используется toncenter.com)
  Anton                 -- Apache 2.0 Go indexer (anton.tools)
  OpenTonAPI            -- open-source variant TonAPI v2 (от Tonkeeper)
  ton-indexer (Python)  -- legacy reference indexer

Сравнение для системного дизайна

РешениеLicenseКогда выбирать
TON Center (hosted)Public free + paidСтартап, MVP — никакой инфраструктуры
TonAPI (hosted)Free tier + paidHigh-level objects: Jetton, NFT, transactions с decoded payloads
ton-index-go (self-hosted)Open-sourceКастомные SQL-запросы, высокий RPS, полный контроль
Anton (self-hosted)Apache 2.0Альтернатива ton-index-go, активная community
OpenTonAPI (self-hosted)Open-sourceХочется TonAPI semantics, но on-prem

Когда переходить на self-hosted

Stage-by-stage migration:

Phase 1 (MVP, < 100 RPS):
  Hosted TON Center / TonAPI public endpoints
  Free tier достаточен
  
Phase 2 (Growth, 100-1000 RPS):
  Hosted с paid plan (TON Center pro / TonAPI pro)
  Дешевле, чем self-hosted
  
Phase 3 (Scale, > 1000 RPS):
  Self-hosted ton-index-go или Anton
  Custom SQL-индексы под ваши queries
  Контроль над latency
  
Phase 4 (Critical infrastructure):
  Multi-region self-hosted + fallback на public API
  Disaster recovery
TIP

Indexer vs Liteclient — разные слои

Liteclient читает текущее состояние контракта (балансы, get-методы). Indexer хранит историю транзакций и сообщений. Для аналитики и user-facing dashboards нужен indexer; для real-time get-методов — liteclient. Production dApp использует оба.

TonAPI v2: high-level abstractions

В отличие от raw RPC (TON Center), TonAPI v2 предоставляет высокоуровневые объекты:

RPC (low-level, TON Center):
  GET /getTransactions?address=EQ...&limit=10
  → возвращает raw transactions с base64 cells
  → нужно парсить cell вручную для понимания "это Jetton transfer"

TonAPI v2 (high-level):
  GET /v2/blockchain/accounts/EQ.../events?limit=10
  → возвращает decoded events:
    {
      "type": "JettonTransfer",
      "from": "EQ...alice",
      "to": "EQ...bob",
      "amount": "1000000",
      "jetton_master": "EQ...usdt"
    }

Когда выбирать TonAPI: Mini App / dashboard, где нужна быстрая разработка и понятные events. Когда выбирать TON Center: low-level контроль, когда нужно парсить сложный custom protocol.

Deployment Checklist

PhaseChecks
Pre-deployAudit complete, testnet verified, gas estimates correct
DeployContract deployed, initial state verified, admin set
Post-deployMonitoring active, alerts configured, balance sufficient
OperationalRegular balance top-up, metric review, upgrade planning
Проверка знанийKnowledge check
ОтветAnswer

Production-операции опираются на конкретный набор API-провайдеров (TON Center v2/v3, TonAPI, self-hosted ноды) и SDK. Базовый разбор API-стека и trade-offs между провайдерами — в курсе по TON.

TON APIs и SDK

Проверьте понимание

Результат: 0 из 0
Аналитический
Вопрос 1 из 1. Какой metric наиболее критичен для мониторинга TON smart contract в production?

Закончили урок?

Отметьте его как пройденный, чтобы отслеживать свой прогресс

Войдите чтобы оценить урок

Прогресс модуля
0 из 1