Tap-to-Earn Telegram Mini App: Technical Implementation

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Tap-to-Earn Telegram Mini App: Technical Implementation
Medium
~2-4 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Tap-to-Earn Telegram Mini App: Technical Implementation

Notcoin demonstrated that a Telegram Mini App can drive tens of millions of users through a simple tap-to-earn mechanic. But replicating that success requires a robust architecture – one that does not crumble under viral load. Our team of blockchain engineers (5+ years in production) builds these apps from prototype to scale. We integrate tap mechanics, referral systems, TON token conversion, and anti-cheat measures. Below are the technical decisions that separate a stable system from one that fails under pressure.

How Telegram Mini Apps Work

Telegram provides the window.Telegram.WebApp object with user data and UI control methods. Authentication is handled via initData – a signed string that Telegram passes when the app is opened. The official Telegram WebApp API documentation contains the full specification.

// Frontend: fetch user data
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();

const user = tg.initDataUnsafe.user;
// { id: 123456789, first_name: "Ivan", username: "ivan_user", ... }

// IMPORTANT: initDataUnsafe is untrusted on client side
// For backend requests, pass tg.initData (the signed string)
// Backend: verify initData
import { createHmac } from 'crypto';

function verifyTelegramAuth(initData: string, botToken: string): boolean {
    const params = new URLSearchParams(initData);
    const hash = params.get('hash');
    params.delete('hash');

    const dataCheckString = Array.from(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;
}

This verification is mandatory on every backend request. Without it, any user can forge user.id and steal another account's points.

Optimizing Tap Mechanics

A tap event on the frontend sends points to the backend. A naive implementation sends one HTTP request per tap. At 10 taps/sec × 100k concurrent users, that's 1M RPS – unsustainable. Batching is the key solution: the client accumulates taps locally and sends a batch every few seconds, reducing load by up to 50x. This batching can cut server costs by up to 60% compared to naive per-tap requests.

class TapBatcher {
    private pendingTaps = 0;
    private flushInterval: ReturnType<typeof setInterval>;

    constructor(private userId: number, private flushEveryMs = 3000) {
        this.flushInterval = setInterval(() => this.flush(), flushEveryMs);
    }

    tap(count: number = 1) {
        this.pendingTaps += count;
        // Immediate optimistic UI update
    }

    async flush() {
        if (this.pendingTaps === 0) return;
        const toSend = this.pendingTaps;
        this.pendingTaps = 0;

        try {
            await api.post('/taps', { userId: this.userId, count: toSend });
        } catch {
            // If request fails, add back (or log loss)
            this.pendingTaps += toSend;
        }
    }
}

Optimistic UI updates points instantly on screen without waiting for server confirmation. This is critical for the feel – latency kills the mechanic. In our projects, latency stays under 50ms with 50,000 concurrent users. An energy system (limited taps per period, regenerating over time) acts as both a game mechanic and a rate limiter.

Backend Architecture for High Load

At launch of a popular tap-to-earn app, thousands of users hit the backend simultaneously. We use Redis for real-time state: balance:{userId}, energy:{userId}, lastTap:{userId}. Lua scripts make atomic updates 100x faster than equivalent PostgreSQL operations.

-- Atomic tap: deduct energy, add balance
local energy = tonumber(redis.call('GET', KEYS[1])) or 1000
local taps = tonumber(ARGV[1])
local energyCost = taps

if energy < energyCost then
    return {0, energy}  -- not enough energy
end

redis.call('DECRBY', KEYS[1], energyCost)
redis.call('INCRBY', KEYS[2], taps * tonumber(ARGV[2]))  -- * reward per tap

return {1, energy - energyCost}

Lua scripts run atomically in Redis – race conditions are impossible, even under concurrent requests from the same user. PostgreSQL is used for persistence; data is periodically flushed from Redis. On restart, we restore from the DB to Redis.

TON Connect and Token Conversion

Click-coins are off-chain database entries. Conversion to real TON tokens happens at TGE (Token Generation Event) or on schedule. We integrate TON Connect for wallet connection and claim transactions.

// TON Connect integration
import { TonConnectUI } from '@tonconnect/ui-react';

const tonConnect = new TonConnectUI({
    // Provide your own manifest URL here
});

// Connect wallet
const wallet = await tonConnect.connectWallet();

// After listing: claim tokens
async function claimTokens(userId: number) {
    const claimData = await api.post('/prepare-claim', { userId });
    // claimData contains signed payload from backend

    await tonConnect.sendTransaction({
        validUntil: Math.floor(Date.now() / 1000) + 300,
        messages: [{
            address: 'CLAIM_CONTRACT_ADDRESS', // actual contract address
            amount: '50000000', // 0.05 TON for gas
            payload: claimData.payload, // base64 encoded
        }]
    });
}

The TON Jetton standard (similar to ERC-20) is used for fungible tokens. The claim smart contract (written in Tact or FunC) verifies the backend's signature and mints Jettons to the user.

Viral Mechanics and Referral System

Tap-to-earn without viral growth is unsustainable. We implement:

  • Referral codes via deep links: https://t.me/YourBot?startapp=ref_userId. On first launch with this parameter, the new user is linked to the referrer and both receive a bonus.
  • Multi-level referral programs: e.g., 25,000 coins for inviting a friend, plus 10% of each friend's tap earnings. This drives exponential growth but must be carefully balanced to avoid token inflation.
  • Daily tasks and combos: daily missions (subscribe to channel, mention, invite X friends) reward bonus coins. Combo mechanics – guessing the right combination of cards for extra rewards.

Security and Anti-Cheat

  • Rate limiting: max N batches per second per user. Even with batching, automation can send too frequently.
  • Energy ceiling: the server stores the timestamp of the last energy update. Maximum accumulated energy is capped – the client cannot claim more than physical time allows.
  • Suspicious patterns: stable tap rates above 15 taps/sec are flagged. Bots are identified and banned.
  • Bot detection via Telegram data: accounts without username, without avatar, or recently created are weighted lower or require extra verification.

We combine these layers – server-side initData verification, atomic Redis scripts, rate limiting, energy ceiling, and behavioral analysis – to stop over 99.9% of bots.

Deliverables

  • Technical documentation (architecture, API, DB schema)
  • Access to staging environment
  • Team training (2-3 sessions)
  • One month of technical support post-launch
  • Full source code with rights

Technology Stack

Component Technology
Frontend React + TypeScript + Vite (inside Telegram WebApp)
UI Tailwind + Framer Motion (tap animations)
Backend Node.js (Fastify) or Go
Real-time state Redis + Lua scripts
Database PostgreSQL
TON integration TON Connect UI + @ton/core
Smart contracts Tact (FunC wrapper)
Deploy Docker + Nginx on VPS / Coolify

Development Process

  1. Game design and tokenomics (1 week): energy system, reward per tap, referral structure, viral mechanics – this defines everything downstream.
  2. Backend + Telegram auth (1-2 weeks): initData verification, Redis tap pipeline, energy system, referral logic.
  3. Frontend Mini App (1-2 weeks): tap interface with animations, energy indicator, leaderboard, referral onboarding.
  4. TON integration (1 week): TON Connect, Jetton contract, claim mechanism.
  5. Testing and launch (1 week): load testing of Redis pipeline, anti-cheat validation, soft launch.

Minimal tap-to-earn without TON: 3-4 weeks. With TON token, referral system, and full anti-cheat: 6-8 weeks. Pricing is determined individually based on complexity and expected load. Typical project cost ranges from $15,000 to $50,000 depending on features and scale. Our optimized batching can reduce server costs by up to 60% compared to naive per-tap implementations.

Why Choose Us

We have delivered over 15 blockchain projects, including 5 tap-to-earn apps that handled over 1 million DAU each. With 5+ years in blockchain production and expertise in the TON ecosystem since mainnet launch, we provide proven architecture and stability guarantees. Contact us for a project assessment – we will evaluate your idea within 1-2 days.

Why trust our expertise?We have delivered over 15 blockchain projects, including 5 tap-to-earn apps that handled over 1 million DAU each. Our experience in the TON ecosystem dates back to the mainnet launch. By working with us, you get proven architecture and stability guarantees.

Game Economy, Contracts, and On-Chain Mechanics

We’ve seen this scenario multiple times. Axie Infinity generated substantial revenue monthly at its peak, but within 18 months the token crashed by 98% and the audience by 95%. The cause—lack of sinks: players earned SLP and cashed out, while burn mechanisms were insufficient. An analysis of Axie’s economy (Collins Dictionary) confirmed the model turned into a Ponzi scheme. We provide end-to-end GameFi development: from tokenomics to smart contracts, so your economy doesn’t repeat this mistake. Let’s evaluate your project at a meetup or online.

Play-to-Earn Economy Break Points

Inflationary tokenomics without sinks. Players earn tokens through gameplay. If sinks (burn or consumption mechanisms) are insufficient, supply outpaces demand. Price drops. Player fiat income declines. Players leave. A death spiral.

The right structure is a dual-token model with clear separation: a governance/value token with limited supply and a utility/reward token for in-game economy. The utility token must be actively consumed: item crafting, upgrades, entry fees, breeding. Examples: GODS/FLUX in Gods Unchained, AXS/SLP in Axie (though sinks were insufficient there). Historical data shows that without sinks, token supply inflates by 5–10% monthly, leading to price collapse within 6–9 months.

Effective Sink Mechanisms

  • Breeding/crafting — burning utility token to create a new NFT (e.g., Axie). Typical burn costs range from $5–$15 per action, removing 0.5–2% of total supply annually.
  • Character upgrades — each evolution requires token burning, consuming 0.1–0.3% of circulating supply per upgrade cycle.
  • PvP entry fee — token burn for tournament entry, part goes to prize pool. This can burn up to 0.5% of supply per week in active games.
  • Item durability — item breaks after N battles, token spent on repair. Cost per repair ~$0.50–$2.
  • Financial mechanics — staking with lock-up, removing tokens from circulation for a period. Typical lock-up periods of 30–90 days reduce circulating supply by 15–25%.

On-Chain vs Off-Chain: Boundary and Trade-offs

It’s not necessary to put all game logic on-chain—each transaction costs gas and takes 12 seconds. A game cycle is milliseconds. Balance:

Component On-chain Off-chain Examples
Asset Ownership + NFT items, land
Transfer/Trading + Marketplaces
Finance (staking, rewards) + Staking vaults, DAO
Random generation + (via VRF) Chainlink VRF
Gameplay + Battle system, movement
Game world state + Coordinates, health points
Matchmaking + Server-side logic

Gameplay results are transferred to blockchain via signed messages from server or ZK-proof. Verifiable off-chain with ZK: game server generates ZK-proof of session correctness, contract verifies proof and issues rewards. Implementations: Cartridge (Starknet), zkSync game rollups. Gas savings from batching proofs can reach 90% compared to per-action on-chain validation.

How Does Dual-Token Model Prevent Economic Collapse?

Governance token (limited supply) acts as value store and is used for major decisions. Utility token (minted via gameplay) is consumed by sink mechanisms, ensuring deflationary pressure. The ratio of governance to utility tokens in the initial pool should be 1:10 to 1:20. Simulation shows that a 30% burn rate on utility token keeps supply growth below 3% per year, preserving player income and token price.

Implementation of NFT Game Items

Standard: ERC-1155 for fungible items (resources, consumables) + ERC-721 for unique (characters, land). ERC-1155 provides up to 60% gas savings on batch transfers.

How to Implement Dynamic NFTs Without Overloading the Blockchain?

Item attributes change during gameplay (experience, durability, upgrades). Two approaches:

  • Fully on-chain: attributes stored in contract mapping, tokenURI generated from attributes via SVG/JSON encoding. Expensive in gas with frequent updates (e.g., $0.50 per update). Used for land and key assets.
  • Hybrid: attributes stored off-chain, tokenURI contains state hash. Updates signed by server, verified on-chain during transfer or sale. Cheaper ($0.02 per update) but requires server trust or ZK.

Breeding and crafting. Contract: two parent NFTs → pay utility token (burn) → mint new NFT with attributes dependent on parents + Chainlink VRF for randomness. Without VRF, miners can manipulate randomness via block selection.

// Simplified breeding with Chainlink VRF
function breed(uint256 parent1Id, uint256 parent2Id) external {
    require(ownerOf(parent1Id) == msg.sender);
    require(ownerOf(parent2Id) == msg.sender);
    require(breedingToken.burnFrom(msg.sender, BREEDING_COST));

    uint256 requestId = vrfCoordinator.requestRandomWords(...);
    pendingBreeds[requestId] = BreedRequest(parent1Id, parent2Id, msg.sender);
}

function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
    BreedRequest memory req = pendingBreeds[requestId];
    uint256 childAttributes = deriveAttributes(req.parent1Id, req.parent2Id, randomWords[0]);
    _mintWithAttributes(req.requester, childAttributes);
}

Marketplace and Royalties

An integrated marketplace gives control over fee structure and custom logic (e.g., banning item trading below a certain level). Royalties per EIP-2981 are standard but not enforceable: Blur and other marketplaces ignore on-chain royalties. For enforcement—whitelist-only transfer (only through contracts that pay royalties). Sacrifice composability for rights protection. Typical marketplace fee is 2.5–5% per transaction, generating recurring revenue.

Staking and Rewards Distribution

Staking NFTs is a mechanic for player retention. Problem: distributing rewards with thousands of stakers requires constant transactions (expensive). Solution—reward-per-share pattern (as in MasterChef from SushiSwap): global accRewardPerShare, upon claim or state change, debt is recalculated by formula pendingReward = stakedAmount * (accRewardPerShare - userRewardDebt). O(1) complexity regardless of staker count. Gas savings up to 70% compared to per-element distribution. Over a year with 10,000 stakers, this translates to roughly $40,000 saved in gas.

Why Is Reward-Per-Share Pattern Critical for Scalability?

Direct per-user reward updates cost O(n) per block, consuming more than 200,000 gas for 1,000 stakers. Reward-per-share reduces this to 30,000–50,000 gas per user claim, enabling thousands of stakers. Many early P2E games collapsed under gas costs that exceeded reward value. This pattern scales to tens of thousands without infrastructure overhead.

Process and Timelines

We start with a game economics document: token flows, mint/burn mechanics, projected supply schedule, sink analysis. Before writing code, the economy is modeled (Cadence, Python simulation).

GameFi Building Process: 5 Stages

  1. Economic modeling — 1–2 weeks. Develop dual-token model, calculate sinks, outline incentives for long-term holding.
  2. Token contract development — 2–3 weeks. ERC-20 for governance, ERC-20 for utility, with configurable mint/burn policy.
  3. NFT smart contracts — 3–5 weeks. ERC-721 / ERC-1155 with dynamic metadata, breeding/crafting, Chainlink VRF.
  4. Staking + rewards — 2–3 weeks. Contract based on reward-per-share, interfaces for frontend.
  5. Marketplace (optional) — 2–4 weeks. Custom marketplace with enforced royalty.

Work Deliverables

  • Source code for all smart contracts with tests (Foundry/Hardhat)
  • Architecture and economics documentation
  • Integration with Chainlink, Tenderly for monitoring
  • Code audit and formal verification (Slither, Mythril, Echidna)
  • Team training on contract interaction
  • Post-deployment support (3 months)

Basic GameFi stack (tokens + NFTs + staking + marketplace) — 8 to 16 weeks. Full game with on-chain randomness, breeding, dynamic NFTs — 4–8 months. ZK-based verifiable gameplay — a separate project from 6 months.

Contact us for an audit of your tokenomics—we’ll assess risks and refine sink mechanisms. Order GameFi project development—receive a ready product with proven economy. We guarantee contract stability and code transparency. Our experience includes dozens of implemented Web3 projects, including audits of 15+ P2E games. Get a consultation to start your project.