Crypto Casino Telegram Mini App Integration
Telegram Mini App for crypto casino is three separate technical tasks in one: Telegram WebApp API, TON Connect for wallet, and game logic with fair results. Most common mistake is building "randomness" on server without verifiable proof. Player can't verify if server honestly picked the result. For trust, need either Chainlink VRF (on-chain random), commit-reveal scheme, or provably fair system (Provably Fair) with HMAC-SHA256.
Fair Random Architecture
Provably Fair (Off-chain, No Gas)
Classic scheme for casinos: server generates server_seed and publishes SHA-256 hash before round start. Player provides client_seed. Result = HMAC_SHA256(server_seed, client_seed + nonce). After round, server reveals server_seed—player verifies hash matches published one.
// server-side: before round
const serverSeed = crypto.randomBytes(32).toString('hex')
const serverSeedHash = SHA256(serverSeed).toString()
// publish serverSeedHash to player
// after round: compute result
function getResult(serverSeed: string, clientSeed: string, nonce: number): number {
const hmac = createHmac('sha256', serverSeed)
hmac.update(`${clientSeed}:${nonce}`)
const hash = hmac.digest('hex')
// take first 8 chars as hex number
const decimal = parseInt(hash.slice(0, 8), 16)
return (decimal % 10000) / 100 // 0-99.99
}
Player can verify result independently—this is provably fair.
On-chain Random via VRF (For High Stakes)
For large payouts, Chainlink VRF on TON or EVM makes sense. Random request is on-chain transaction, result published to contract. Can't fake, can't replay.
Telegram Mini App Infrastructure
Initialization and Validation
// Telegram WebApp SDK
const tg = window.Telegram.WebApp
tg.ready()
tg.expand() // expand to full screen
// User data
const initData = tg.initData // string to validate on server
const user = tg.initDataUnsafe.user
Server validation is mandatory—initData contains HMAC-SHA256 signature from Bot Token:
// server: validate initData
import { createHmac } from 'crypto'
function validateTelegramWebAppData(initData: string, botToken: string): boolean {
const params = new URLSearchParams(initData)
const hash = params.get('hash')
params.delete('hash')
const dataCheckString = [...params.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => `${k}=${v}`)
.join('\n')
const secretKey = createHmac('sha256', 'WebAppData').update(botToken).digest()
const expectedHash = createHmac('sha256', secretKey).update(dataCheckString).digest('hex')
return hash === expectedHash
}
Never trust user.id without hash verification—this is the main Mini App backend vulnerability.
TON Connect and Deposits
import { TonConnectUIProvider, TonConnectButton, useTonConnectUI, useTonAddress } from '@tonconnect/ui-react'
import { toNano } from '@ton/ton'
function DepositButton({ amount }: { amount: number }) {
const [tonConnectUI] = useTonConnectUI()
const address = useTonAddress(false) // raw address for verification
async function deposit() {
const tx = {
validUntil: Math.floor(Date.now() / 1000) + 300,
messages: [{
address: CASINO_CONTRACT_ADDRESS,
amount: toNano(amount.toString()).toString(),
payload: buildDepositPayload(address), // BOC with user_id
}]
}
const result = await tonConnectUI.sendTransaction(tx)
// Wait for confirmation via TON API
await waitForTx(result.boc)
}
}
Deposit to contract, not regular wallet—contract tracks player balances on-chain. Withdrawal via contract with player signature.
UI/UX Specific to Telegram Mini App
Native Components
Telegram provides native UI elements via WebApp API:
// Main button at bottom of screen
tg.MainButton.setText('Place Bet')
tg.MainButton.show()
tg.MainButton.onClick(() => placeBet())
// Haptic feedback on win/loss
tg.HapticFeedback.notificationOccurred('success') // win
tg.HapticFeedback.notificationOccurred('error') // loss
tg.HapticFeedback.impactOccurred('medium') // normal action
// Back button
tg.BackButton.show()
tg.BackButton.onClick(() => navigate(-1))
Haptic feedback is a small detail that significantly improves game feel on mobile.
Color Scheme
Mini App inherits Telegram user theme:
const { colorScheme, themeParams } = tg
// colorScheme: 'light' | 'dark'
// themeParams.bg_color, .text_color, .button_color etc.
// To CSS variables
document.documentElement.style.setProperty('--tg-bg', tg.themeParams.bg_color)
Result Animations
For slots/roulette—CSS animations with requestAnimationFrame. No heavy canvas libraries—Mini App should load in < 2 seconds. GSAP for animations is acceptable, Three.js is overkill.
Backend Architecture
Telegram Bot (node-telegram-bot-api)
├── Handle commands (/start, /balance)
└── Webhook → Mini App URL
Mini App Backend (Node.js/Fastify)
├── POST /validate — validate initData
├── POST /bet — bet logic
├── GET /history — round history
└── POST /withdraw — withdrawal request
TON API (tonapi.io / toncenter.com)
└── Monitor transactions to contract
WebSocket for real-time balance and round result updates—standard ws or socket.io. Polling as fallback if WebSocket is blocked by corporate networks.
Regulatory Risks
Crypto casinos operate in gray jurisdiction almost everywhere. Telegram can block Mini App for TOS violation (gambling prohibited in most regions). Practice: geoblocking by IP for prohibited jurisdictions, no direct gambling mentions in Bot/App description, work through licensed jurisdictions (Curaçao, Isle of Man). This is legal, but technically implemented at middleware level.







