Chains

BNB Smart Chain

Build web3 dApps effortlessly

BNB Beacon Chain

Sunset Complete

BNB ecosystem’s staking & governance layer

DocumentationGitHubFaucetStake BNBBscScanBSCTraceDev ToolsLearn more about FusionDocumentationBeacon Chain ExplorerToken Recovery ToolDocumentationGitHubFaucetBridgeGreenfieldScanDCellarDev ToolsDocumentationGitHubFaucetBridgeopBNBScanDev ToolsDocumentationGitHub

Developers


Submit dApps

BNB Smart ChainBNB GreenfieldopBNBzkBNBBNB HackBNB Incubation Alliance (BIA)Most Valuable Builder Accelerator Program (MVB)BNB Chain GrantsKickstartGas GrantsTVL Incentive ProgramMEME Coins InnovationSee All Programs

Ecosystem

Staking

Earn BNB and rewards effortlessly

Tokenization Solutions

Get Your Business Into Web3

Native StakingLiquid StakingCompany TokenizationReal World Assets TokenizationNFT Loyalty Program

Community

Contact UsGet Started
Contact UsGet Started

Building Telegram Mini-dApps on BNB Chain

2024.8.27  •  5 min read
Blog post image.

Web3 Telegram UX Challenges

Telegram mini-apps can be started as telegram bots, accessible directly through users' telegram accounts. Currently, users need to use their telegram TON wallet to purchase in-app virtual assets, therefore a bridge between TON and other EVM chains is a must. This could introduce two UX issues. 

  1. Not every telegram user has assets on their TON wallet. 
  2. Users need to trust the TON bridge and bridging cost could be high. 

Therefore, users ideally can use any wallet to purchase their assets, so they do not need to bridge their assets to TON and pay for the transaction fee of TON bridge. I will take the mini-game as a typical example to go through the whole process. 

Telegram Games Process

Deployment Architecture

Note: Frontend, backend and database are hosted by game developers. The walletConnect can be replaced by another wallet widget, like thirdweb, or any others.

Overall process

Like other kinds of telegram mini-apps, to have better UX, the mini-game usually has an off-chain database to manage the sessions and bind the on-chain address with app user ID. And most mini-games do not depend on the TON wallet, but be able to integrate with EVM chain wallets.

When telegram bot triggers the mini-game, the user`s information is included in the initData, from which, the mini-game can validate the authentication and retrieve user`s basic information, including the user`s telegram name, user id, etc. It can be used to bind the on-chain address therefore to index the on-chain activities to reach the eventual consistency.  All the details will be covered in the following sections. 

Authentication and Initialization

Like other types of games, Telegram Mini Games also requires authentication first. When Mini Game is launched by the game bot, the first step is the initialization, so the game front end could retrieve the gamer`s telegram user info through the initData through telegram SDK to generate the gamer`s in-game account and profile. 

Step 1: Retrieve Init Data

Developers can use the “retrieveLaunchParams” to read the initData, and it can be used to validate the authentication. The fact is that the data generated by the native Telegram application is signed with the secret key of the Telegram bot, after which the generated signature is placed next to the parameters themselves.

import { retrieveLaunchParams } from '@telegram-apps/sdk';

const { initDataRaw, initData } = retrieveLaunchParams();

Step 2: Validate Authentication 

Developers can send the initData to their game backend to validate. 

import { retrieveLaunchParams } from '@telegram-apps/sdk';

const { initDataRaw } = retrieveLaunchParams();

fetch('https://example.com/api', {
  method: 'POST',
  headers: {
    Authorization: `tma ${initDataRaw}`
  },
});

For servers to validate the initData, developers can use the init-data-node library 

import { validate } from '@telegram-apps/init-data-node';

const secretToken = 'xxxx';
const initData = 'xxxx';

validate(initData, secretToken);

Security consideration

By default, the function checks the expiration of the initialization data. The default expiration duration is set to 1 day (86,400 seconds). It is recommended to always check the expiration of the initialization data, as it could be stolen but still remain valid. To disable this feature, pass { expiresIn: 0 } as the third argument. It is recommended to use additional mechanisms for verifying initialization data. For example, add their expiration date. This check can be implemented using the auth_date parameter, which is responsible for the date when the parameters were created. This solution will allow in case of theft of initialization data to prevent their constant use by an attacker. 

Step 3: Gamer Profile Creation

If the validation succeeds, a gamer profile can be created in the backend and bind the gamer ID with the telegram user ID for session management. 

Session Management

After initData is verified to be valid, you can obtain the account ID and communicate with the server through a websocket. Here, the server can ensure that this user only has one websocket communication connection based on the account ID. Subsequent front-end and back-end data communications will all go through this connection. If the connection is disconnected, it will re-verify initData and re-establish a websocket connection.

Game off-chain balance management

To have better user experience, such as reduce the latency and also reduce the on-chain interaction cost, an in-game balance management system is necessary for telegram mini-game. For games on BNB Chain, you can directly use wallet connect widget to allow your gamers to purchase any in-game assets. 

Step 1: Polling in-game balance for gamers 

  1. A dedicated backend synchronization task is needed. Of course, the synchronization task needs an indexing service(Enhanced API) that can index your on-chain contract data and save it to the trade table. 
  2. After each login, or when set by a fixed polling time at the backend service, the synchronization task checks for pending orders, if there are records in the trade table, then updates relevant information and also updates the front end. 

Step 2: Order creation in asynchronous process

  1. When a gamer creates a new order, the frontend needs to call the backend to save the transaction information in the backend, which will be used to query the on-chain data. Game frontend does not need to wait for the finalization of transactions on chain. 
  2. Then the game front end sends the transaction to invoke wallet to sign the transaction, and wallet returns the transaction operation data to the frontend. After receiving the operation data from the wallet, the frontend can display pending transaction data to gamers. 
  3. The game backend keeps tracking the on-chain data through the indexer, after the on-chain transaction is confirmed, then the backend can notify the frontend through webhook or the frontend can periodically poll the transaction data from backend. 

Conclusion

Developing a telegram mini app on BNB Chain is very straightforward, and it can reduce the dependency on the TON wallet and bridge, and BNB Chain users can directly use their own wallet to purchase any virtual assets on your game. All the authentication, user validation and indexing service can depend on the telegram platform. 

Follow us to stay updated on everything BNB Chain

Website | Twitter | Telegram | Instagram | Facebook | dApp Store | YouTube | Discord | LinkedIn | Build N' Build Forum

Share