# 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.

<div><figure><img src="/files/GHbBALO2jCFLjNwimF3N" alt=""><figcaption></figcaption></figure> <figure><img src="/files/qHwNq47pKd2B0deuQzrh" alt=""><figcaption></figcaption></figure> <figure><img src="/files/JdPv8Waa6uW6Fkx9p6Qx" alt=""><figcaption></figcaption></figure></div>

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.

```typescript
    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.

```shell
npm install --save @ton/cocos-sdk@beta
```

2. Initialize the TonConnectUI object

```typescript
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();
}
    
```

3. Connect to the wallet

```typescript
    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.

```typescript
 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
        });
    }
```

2. Call the methods in the cocosGameFi object to operate Ton chain-related transactions. For example, get the data of a JettonWallet

```typescript
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. Telegram Mini App related operations

#### 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:

```typescript
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 }
}
```

6. In the Cocos environment, refer to the following usage

```typescript
// 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

```typescript
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.

<figure><img src="/files/42EgNjt56lZNB80cUrWg" alt="" width="375"><figcaption></figcaption></figure>

### 7. Community communication

Telegram <https://t.me/CocosStudioCommunity>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cocosstudio.gitbook.io/cocosstudio-docs/ton/using-ton-in-cocos-creator.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
