Using Ton in Cocos Creator

1. Create a Telegram Mini App

1.1 How to create a Telegram Bot

  1. Search for @BotFather on Telegram, which is an official Bot administrator account.

  2. Send the /newbot command to @BotFather to create a new Bot.

  3. Enter your Bot name, which must end with "bot", such as "MyAwesomeBot".

  4. Enter the username for your Bot, which must be unique and end with "bot", such as "my_awesome_bot".

  5. If the name is available, @BotFather will return the access Token for your newly created Bot in the format: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11. Please keep this Token safe and do not disclose it to others.

1.2 Set the relevant parameters for the Mini App

  1. Send the /mybots command to @BotFather and select the Bot you just created.

  2. Click "Bot Settings" - "Menu Button" to set up the menu buttons for your Bot. You can set some quick action buttons.

  3. Send the /newapp command to @BotFather, select the Bot you just created, and make the following settings:

    • Set the Name of the Mini App, which will be displayed in Telegram.

    • Set the Description of the Mini App, briefly describing its functionality.

    • Set the Photo of the Mini App, with a size of 640x360 pixels.

    • Set the URL (https required) of the Mini App. This is the actual access address of the Mini App.

    After successful setup, you will receive a direct access link. Users can directly open the Mini App through this link. You can also find the newly created Mini App in the attachments menu of the chat interface.

2. Import the cocos-telegram-miniapps extension

  1. Create a new project in Cocos Creator, selecting a version above Creator 3.8.3.

  2. Install the cocos-telegram-miniapps extension in the project. Click Menu - Open Extension Manager Import the extension After successful import, the assets/cocos-telegram-miniapps/scripts/telegram-web.ts file will be automatically created.

  1. Initialize the cocos-telegram-miniapps extension in Cocos This method will automatically load telegram-web-app.js into the page, making it convenient to operate the window.Telegram.WebApp object.

    import { _decorator, Component, Node } from 'cc';
    import { TelegramWebApp } from './cocos-telegram-miniapps/scripts/telegram-web';
    const { ccclass, property } = _decorator;

    @ccclass('game')
    export class game extends Component {
        protected onLoad() {
            TelegramWebApp.Instance.init().then(res => {
                console.log("telegram web app init : ", res.success);
            });
        }
        start() {

        }


        update(deltaTime: number) {

        }
    }

3. Use TonConnectUI to connect to a wallet

  1. Install the @ton/cocos-sdk library In order to use TonConnectUI, you need to install the @ton/cocos-sdk library. This library has already packaged TonConnectUI and can be directly used in the Cocos game engine.

npm install --save @ton/cocos-sdk@beta
  1. Initialize the TonConnectUI object

async initTonConnect() {
        this.connectUI = new TonConnectUI({
            manifestUrl: 'https://ton-connect.github.io/demo-dapp-with-wallet/tonconnect-manifest.json'
        });
      

        // Listen for connection status changes
        this.connectUI.onModalStateChange(state => {
            console.log("model state changed! : ", state);
            this.updateConnect();
        });

        // Listen for wallet status changes
        this.connectUI.onStatusChange(info => {
            console.log("wallet info status changed : ", info);
            this.updateConnect();
        });
        this.updateConnect();
}
    
  1. Connect to the wallet

    onConnect() {
        if (this.isConnected()) {
            this.connectUI.disconnect();
        } else {
            this.connectUI.openModal();
        }
    }

    public isConnected(): boolean {
        if (!this.connectUI) {
            console.error("ton ui not inited!");
            return false;
        }
        return this.connectUI.connected;
    }

    // Get the wallet address after successful connection
    private updateConnect() {
        if (this.isConnected()) {
            const address = this.connectUI.account.address;
            this.connectLabel.string = Address.parseRaw(address).toString({ testOnly: true, bounceable: false }).substring(0, 6) + '...';
        } else {
            this.connectLabel.string = "Connect";
        }
    }

4. Send Ton transactions through TonConnectUI

  1. Initialize the GameFi object For the convenience of operating Jetton contracts on the Ton chain, the SDK has encapsulated methods that need to be initialized.

 async initTonConnect() {
        this.connectUI = new TonConnectUI({
            manifestUrl: 'https://ton-connect.github.io/demo-dapp-with-wallet/tonconnect-manifest.json'
        });
        this.cocosGameFi = await GameFi.create({
            connector: this.connectUI
        });
    }
  1. Call the methods in the cocosGameFi object to operate Ton chain-related transactions. For example, get the data of a JettonWallet

const jettonData = await this.cocosGameFi.openJettonWallet(Address.parse("")).getData()
console.log(jettonData.balance)

For more methods, please refer to https://github.com/ton-org/game-engines-sdk

5.1 Introduction to Telegram Mini App documentation

  • Documentation address: https://core.telegram.org/bots/webapps

5.2 Get current Telegram user information

  1. After importing the cocos-telegram-miniapps extension, the TelegramWebApp class will be generated in assets/cocos-telegram-miniapps/scripts/telegram-web.ts. Using this object, you can call the relevant capabilities of TelegramMiniAPP.

  2. If the page is opened in Telegram, the window.Telegram.WebApp object will be automatically initialized.

  3. Through the initData of this object, you can obtain a JSON value of type string, which contains the current user information.

  4. The backend interface needs to verify this value to ensure security.

  5. After successful verification, you can obtain the current user information and perform login operations.

For the verification logic, please refer to the documentation: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

For example, the TypeScript version of the verification is as follows:

import { createHmac } from 'crypto';

function hmac(data: string, key: string | Buffer): Buffer {
    return createHmac('sha256', key).update(data).digest();
}

export function processTelegramData(qs: string, token: string): { ok: false } | { ok: true, data: Record<string, string> } {
    const sk = hmac(token, 'WebAppData')
    const parts = qs.split('&').map(p => p.split('='))
    const hashpart = parts.splice(parts.findIndex(p => p[0] === 'hash'), 1)[0]
    const dcs = parts.sort((a, b) => a[0] > b[0] ? 1 : -1).map(p => decodeURIComponent(p.join('='))).join('\n')
    if (hmac(dcs, sk).toString('hex') !== hashpart[1]) return { ok: false }
    const o: Record<string, string> = {}
    for (const part of parts) {
        o[part[0]] = decodeURIComponent(part[1])
    }
    return { ok: true, data: o }
}
  1. In the Cocos environment, refer to the following usage

// Get user authentication information
const userInitData = TelegramWebApp.Instance.getTelegramInitData();
// The frontend submits userInitData to the backend through the login interface, and the backend verifies whether userInitData is valid and can perform login authentication logic

5.3 Call sharing

  1. Call the TelegramWebApp.Instance.share(url,text) method to open the link and implement the sharing functionality. Note: The text field will be automatically URL-encoded.

5.4 Call payment

In Telegram Mini App, in addition to using Ton chain tokens as a payment method, you can also use the official Telegram Stars as a payment channel.

Telegram Stars documentation address: https://core.telegram.org/bots/payments-stars

Here's a brief introduction to the Stars payment process. First, the backend needs to create an invoiceLink and return it to the frontend. The frontend calls the TelegramWebApp.Instance.openInvoice(invoiceLink) method to open the payment page. When the user clicks to pay, the Telegram bot will send a pre_checkout_query message to notify the backend. The backend needs to process whether to allow payment. After allowing, when the payment is successful, the Telegram bot will send a successful_payment message. The backend receives it and processes the payment order business flow.

For detailed business code, please refer to the demo project: https://github.com/CocosTechLabs/flappy-bird

5.5 Directly obtain the TelegramWebApp object

TelegramWebApp.Instance.getTelegramWebApp()

This method can directly return the TelegramWebApp object, making it convenient to use other capabilities. For specific methods, please refer to the official documentation: https://core.telegram.org/bots/webapps#initializing-mini-apps

6. Build

When building, you need to modify the compilation option settings and adjust Target Environments > 0.5%. Otherwise, you may encounter problems that cannot be loaded after packaging.

7. Community communication

Telegram https://t.me/CocosStudioCommunity

Last updated