Telegram Mini App Slots Development
Telegram Mini Apps (TMA) — WebApp inside messenger with 900M+ user audience. TON blockchain natively integrated with Telegram via @wallet bot and TON Connect protocol. Slots in TMA — one of most common GameFi use cases in this ecosystem. Full stack: from TMA API to smart contract on TON.
Telegram Mini App: Technical Basics
TMA — regular web application (React/Vue), opening in Telegram's built-in browser. Interaction with Telegram via window.Telegram.WebApp object:
import WebApp from "@twa-dev/sdk";
// Initialization
WebApp.ready(); // inform Telegram app is loaded
WebApp.expand(); // expand to full screen
// User data (no additional login)
const user = WebApp.initDataUnsafe.user;
// { id: 123456789, first_name: "Alex", username: "alex123", ... }
// Verify data on server (HMAC-SHA256)
// initData contains signature from Telegram — never trust client
const isValid = await verifyTelegramData(WebApp.initData, BOT_TOKEN);
// Haptic feedback
WebApp.HapticFeedback.impactOccurred("medium"); // on win
WebApp.HapticFeedback.notificationOccurred("success");
// Main Button (native Telegram button)
WebApp.MainButton.setText("SPIN");
WebApp.MainButton.show();
WebApp.MainButton.onClick(() => spinReels());
Verify initData on Backend
import crypto from "crypto";
function verifyTelegramWebAppData(initData: string, botToken: string): boolean {
const urlParams = new URLSearchParams(initData);
const hash = urlParams.get("hash");
urlParams.delete("hash");
// Sort parameters alphabetically
const dataCheckString = Array.from(urlParams.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, value]) => `${key}=${value}`)
.join("\n");
const secretKey = crypto
.createHmac("sha256", "WebAppData")
.update(botToken)
.digest();
const computedHash = crypto
.createHmac("sha256", secretKey)
.update(dataCheckString)
.digest("hex");
return computedHash === hash;
}
TON Smart Contract for Slots
TON uses FunC or Tact (more modern, TypeScript-like syntax) for smart contracts. Slots on TON — contract accepting TON coins and paying prizes.
// Tact syntax
import "@stdlib/deploy";
struct SpinResult {
reel1: Int as uint8;
reel2: Int as uint8;
reel3: Int as uint8;
payout: Int as coins;
}
contract SlotMachine with Deployable {
owner: Address;
houseBalance: Int as coins = 0;
// Minimum and maximum bet
const MIN_BET: Int = ton("0.1");
const MAX_BET: Int = ton("10");
// Server public key for randomness verification
serverPublicKey: Int as uint256;
init(owner: Address, serverPublicKey: Int) {
self.owner = owner;
self.serverPublicKey = serverPublicKey;
}
// Accept bet
receive("spin") {
let ctx: Context = context();
require(ctx.value >= self.MIN_BET, "Bet too small");
require(ctx.value <= self.MAX_BET, "Bet too large");
// Emit event — server catches and returns signed result
emit(SpinRequested{
player: ctx.sender,
betAmount: ctx.value,
nonce: now()
}.toCell());
self.houseBalance += ctx.value;
}
// Server sends signed result
receive(msg: ClaimWin) {
// Verify server signature
let hash: Int = beginCell()
.storeAddress(msg.player)
.storeCoins(msg.betAmount)
.storeUint(msg.nonce, 64)
.storeUint(msg.reel1, 8)
.storeUint(msg.reel2, 8)
.storeUint(msg.reel3, 8)
.endCell()
.hash();
require(checkSignature(hash, msg.signature, self.serverPublicKey), "Invalid signature");
let payout: Int = self.calculatePayout(msg.reel1, msg.reel2, msg.reel3, msg.betAmount);
if (payout > 0) {
require(self.houseBalance >= payout, "Insufficient house balance");
self.houseBalance -= payout;
send(SendParameters{
to: msg.player,
value: payout,
mode: SendIgnoreErrors
});
}
}
fun calculatePayout(r1: Int, r2: Int, r3: Int, bet: Int): Int {
// Three sevens — jackpot
if (r1 == 7 && r2 == 7 && r3 == 7) { return bet * 100; }
// Three of a kind
if (r1 == r2 && r2 == r3) { return bet * 10; }
// Two of a kind
if (r1 == r2 || r2 == r3 || r1 == r3) { return bet * 2; }
// BAR combination
if (r1 == 6 && r2 == 6) { return bet * 3; }
return 0;
}
// Fund prize pool
receive("deposit") {
self.houseBalance += context().value;
}
get fun balance(): Int { return self.houseBalance; }
}
TON Connect: Wallet Connection
import TonConnect from "@tonconnect/sdk";
const connector = new TonConnect({
manifestUrl: "https://yourapp.com/tonconnect-manifest.json",
});
// tonconnect-manifest.json:
// { "url": "https://yourapp.com", "name": "Slots Game",
// "iconUrl": "https://yourapp.com/icon.png" }
// Connect wallet (opens @wallet bot or external wallet)
const walletsList = await connector.getWallets();
connector.connect({ universalLink: walletsList[0].universalLink, bridgeUrl: ... });
connector.onStatusChange((wallet) => {
if (wallet) {
console.log("Connected:", wallet.account.address);
initGame(wallet.account.address);
}
});
// Send transaction (bet in TON)
async function placeBet(amount: number) {
await connector.sendTransaction({
validUntil: Math.floor(Date.now() / 1000) + 300,
messages: [{
address: SLOT_CONTRACT_ADDRESS,
amount: String(amount * 1e9), // in nanoTON
payload: "spin", // text comment
}],
});
}
Game Flow and Animation
Slots — reel animation. Use CSS/Canvas animation or Pixi.js:
- Player hits "Spin" → send TON transaction
- While transaction pending → reels spin in "waiting" animation
- Game server notices transaction → generates random result → signs → calls
ClaimWinon contract - Frontend gets event via TON Center API or tonSDK → reels "decelerate" to final symbols
- If win — haptic feedback + coin effects
// Monitor contract events
async function watchSlotEvents(contractAddress: string) {
const client = new TonClient({ endpoint: "https://toncenter.com/api/v2/jsonRPC" });
setInterval(async () => {
const transactions = await client.getTransactions(Address.parse(contractAddress), {
limit: 10,
});
for (const tx of transactions) {
if (tx.inMessage?.body) {
// Parse reel result from transaction body
const result = parseSpinResult(tx.inMessage.body);
if (result && result.player === currentPlayerAddress) {
animateReels(result.reel1, result.reel2, result.reel3);
}
}
}
}, 2000);
}
Monetization and TON Ecosystem
TON provides several advantages for TMA slots:
- @wallet integration — Telegram users often have TON wallet via built-in @wallet
- Fees — TON transactions cost ~$0.003–0.01, acceptable for game microtransactions
- TON Stars — Telegram's internal currency (for non-crypto users)
-
Viral mechanics — native sharing of results to chats via
WebApp.openTelegramLink
RTP (Return to Player) for fair slots: 95–97%. House edge 3–5% ensures sustainable economy with sufficient game volume.







