How to Verify TON Crypto Payments Safely in Node.js & TypeScript (Address Normalization & Replay Protection)

2026-11-28来源 dev.toEnglish

Accepting native TON payments inside a Telegram Mini App looks simple until you hit real-world edge cases on the backend:

  • A user sends TON from a bounceable (EQ...) vs non-bounceable (UQ...) vs raw (0:...) wallet format
  • A client fakes a "paid" redirect without waiting for on-chain settlement
  • An attacker tries to reuse the same txHash across two orders
  • Floating-point math breaks nanoton (10^-9) comparisons

Here is how we handle server-side TON payment matching cleanly in TypeScript before unlocking any paid plan.

The 5 Backend Checks for Reliable TON Verification

  1. Normalize every TON address to raw workchain:hex: User-friendly TON addresses (EQ... / UQ...) are Base64URL payloads with a 2-byte CRC16-CCITT checksum. Verify the checksum and convert both your configured wallet and the incoming transaction destination to lowercase workchain:hex before comparing.
  2. Generate a unique random memo per order: Create a server-side memo (for example, TMA- + 10 random bytes in hex) with a strict expiration window (e.g., 30 minutes).
  3. Compare amounts using BigInt nanotons: Never compare TON amounts with JavaScript floating-point numbers. Parse nanoton strings/numbers into BigInt and check tx.valueNano >= expectedNano.
  4. Filter out aborted or failed compute phases: Make sure the transaction was not aborted and its compute phase did not fail before accepting it.
  5. Enforce unique txHash and orderId indexes in MongoDB: Always guard settlement with unique database indexes so the same transaction hash can never confirm two orders, even under concurrent poller or user clicks.

Core TypeScript Implementation (normalizeTonAddressToRaw & Matching)

 ts const RAW_TON_ADDRESS_REGEX = /^(-?\d+):([0-9a-fA-F]{64})$/; function crc16Ccitt(data: Uint8Array): number { let crc = 0; for (const byte of data) { crc ^= byte << 8; for (let i = 0; i < 8; i += 1) { if ((crc & 0x8000) !== 0) { crc = ((crc << 1) ^ 0x1021) & 0xffff; } else { crc = (crc << 1) & 0xffff; } } } return crc; } export function normalizeTonAddressToRaw(address: string): string | null { const trimmed = address.trim(); if (!trimmed) return null; const rawMatch = RAW_TON_ADDRESS_REGEX.exec(trimmed); if (rawMatch) { const workchain = Number(rawMatch[1]); const hexPart = rawMatch[2]; if (!Number.isInteger(workchain) || !hexPart) return null; return `${workchain}:${hexPart.toLowerCase()}`; } const base64Standard = trimmed.replace(/-/g, '+').replace(/_/g, '/'); if (base64Standard.length !== 48) return null; let bytes: Buffer; try { bytes = Buffer.from(base64Standard, 'base64'); } catch { return null; } if (bytes.length !== 36) return null; const payload = bytes.subarray(0, 34); const checksum = bytes.readUInt16BE(34); if (crc16Ccitt(payload) !== checksum) return null; const rawWorkchain = bytes.readInt8(1); const accountHex = bytes.subarray(2, 34).toString('hex').toLowerCase(); return `${rawWorkchain}:${accountHex}`; } Once both addresses are normalized, each candidate transaction goes through strict matching: export interface NormalizedTonTransaction { txHash: string; destinationRaw: string; comment: string | null; valueNano: bigint; confirmed: boolean; } export function findMatchingTonTransaction(params: { transactions: NormalizedTonTransaction[]; walletAddress: string; memo: string; expectedNano: bigint; usedTxHashes: Set<string>; }): NormalizedTonTransaction | null { const targetWalletRaw = normalizeTonAddressToRaw(params.walletAddress); if (!targetWalletRaw) return null; for (const tx of params.transactions) { if (!tx.confirmed) continue; if (tx.destinationRaw !== targetWalletRaw) continue; if (tx.comment !== params.memo) continue; if (tx.valueNano < params.expectedNano) continue; if (params.usedTxHashes.has(tx.txHash)) continue; return tx; } return null; } (Tip: Always test your indexer parsing with mocked unit tests and verify a small live transfer on your target TON network before accepting live customer payments.) Want the Complete Telegram Mini App Starter Architecture? Free initData Verification Snippet + 6 Tests: https://github.com/Arvelius-Agency/telegram-initdata-guard-ts (apps/api, apps/web, tools/): If you want a ready TypeScript + Fastify 5 + React 18 monorepo combining initData HMAC auth, Stripe Checkout (raw-body webhooks + replay guard), TonCenter v3 / TonAPI v2 indexing, plan entitlements, allowlisted Admin panel, 18 automated backend tests, and dr.mjs CLI, check out :https://arvelius.gumroad.com/l/secure-tma-devkit 

原文:https://www.a8q9.cn/en/article/how-to-verify-ton-crypto-payments-safely-in-node-js-typescript-address-normaliza-1ce853.html

相关文章