Connect to Mobile Wallet
TON

TON#

TON chain, fully known as The Open Network, aims to provide fast and efficient transaction processing capabilities, while supporting smart contracts and decentralized applications. TON uses an innovative design called "multi-chain architecture," enabling high scalability and allowing multiple blockchains to run in parallel, thus improving the throughput and performance of the entire network.

Installation and Initialization#

Please ensure that your OKX App is updated to version 6.84.0 or later before integration. To integrate OKX Connect into your DApp, you can install it using npm:

npm install okxconnect

Before connecting to the wallet, you need to create an object for future operations such as wallet connection and transaction sending.

new OKXTonConnect({metaData: {name, icon}})

Request Parameters

  • metaData - object
    • name - string: Application name, not used as a unique identifier
    • icon - string: The URL of the application icon. Must be in PNG, ICO, or other formats. SVG icons are not supported. It is recommended to pass a URL pointing to a 180x180px PNG icon.

Return Value

  • okxTonConnect - OKXTonConnect

Example

import {OKXTonConnect} from "okxconnect";

const okxTonConnect = new OKXTonConnect({
    metaData: {
        name: "application name",
        icon: "application icon url"
    }
});

Connect Wallet#

Connect to the wallet to obtain the wallet address, which serves as an identifier and is a necessary parameter for signing transactions.

connect(request): Promise<string>;

Request Parameters

  • request - object (optional)

  • tonProof - string (optional): Signature information;

  • redirect - string (optional): Deeplink to return to the app after the wallet event is processed. For example, in the Telegram environment, this field should pass Telegram's deeplink. After signing is completed in the wallet, the OKX App will use this deeplink to open Telegram;

  • openUniversalLink - boolean (optional): Whether to invoke the OKX App client through a Universal Link when connecting the wallet. When set to true, the OKX App client will be launched, and a confirmation page will be displayed. If the OKX App client is not installed, it will redirect to the download page;

Return Value

  • Promise - string: On the PC web end, this field can be used to generate a QR code. The OKX App client scans the generated QR code in web3 to connect to the DApp.

Recommendations

  • Set openUniversalLink to true in mobile browsers or mobile Telegram environments.

  • Set openUniversalLink to false in PC browser environments. Generate a QR code based on the returned universalLink. Users can scan this QR code with the OKX App client to connect. Once the connection is successful, dismiss the QR code popup.

Example

import {OkxConnectError} from "okxconnect";

try {
    okxTonConnect.connect({
        tonProof: "signmessage",
        redirect: "tg://resolve",
        openUniversalLink: true
    })
} catch (error) {
    if (error instanceof OkxConnectError) {
        if (error.code === OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR) {
            alert('User reject');
        } else if (error.code === OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERROR) {
            alert('Already connected');
        } else {
            alert('Unknown error happened');
        }
    } else {
        alert('Unknown error happened');
    }
}

Restore Connection#

If the user previously connected a wallet, this method can be called to restore the previous connection state when re-entering or refreshing the page.

restoreConnection(): Promise<void>

Request Parameters

None

Return Value

None

Example

okxTonConnect.restoreConnection()

Disconnect Wallet#

Disconnect the connected wallet and delete the current session. If you need to switch wallets, disconnect the current wallet first.

Example

import {OKX_CONNECT_ERROR_CODES} from "okxconnect";

try {
    await okxTonConnect.disconnect()
} catch (error) {
    if (error instanceof OkxConnectError) {
        switch (error.code) {
            case OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR:
                alert('Not connected');
                break;
            default:
                alert('Unknown error happened');
                break;
        }
    } else {
        alert('Unknown error happened');
    }
}

Check if Currently Connected#

Check if the wallet is currently connected.

Example

var connect: boolean = okxTonConnect.connected()

Send Transaction#

Method to send a message to the wallet:

sendTransaction(transaction, options): Promise<SendTransactionResponse>

Request Parameters

  • transaction - object
    • validUntil - number: Unix timestamp. The transaction will be invalid after this time.
    • from - string (optional): Address of the sender sending the transaction from the DApp. Defaults to the currently connected wallet address.
    • messages - object[]: (Array of messages): 1-4 output messages from the wallet contract to other accounts. All messages are sent in order, but the wallet cannot guarantee that the messages will be delivered and executed in the same order.
      • address - string: Destination of the message
      • amount - string: Amount to be sent
      • stateInit - string (optional): Base64-encoded raw cell BoC
      • payload - string (optional): Base64-encoded raw cell BoC
  • options - object
    • onRequestSent - () => void: This method will be called when the signing request is sent.

Return Value

Promise - {boc: string}: Signed result

Example

import {OkxConnectError} from "okxconnect";

let transactionRequest = {
    "validUntil": Date.now() / 1000 + 360,
    "from": "0:348bcf827469c5fc38541c77fdd91d4e347eac200f6f2d9fd62dc08885f0415f",
    "messages": [
        {
            "address": "0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F",
            "amount": "20000000",
            "stateInit": "base64bocblahblahblah==" //deploy contract
        }, {
            "address": "0:E69F10CC84877ABF539F83F879291E5CA169451BA7BCE91A37A5CED3AB8080D3",
            "amount": "60000000",
            "payload": "base64bocblahblahblah==" //transfer nft to new deployed account 0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F
        }
    ]
}

let requestOptions = {
    onRequestSent: () => {
        //requestMsgSend
    }
}
try {
    const result = await okxTonConnect.sendTransaction(transactionRequest, requestOptions);
} catch (error) {
    if (error instanceof OkxConnectError) {
        switch (error.code) {
            case OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERROR:
                alert('You rejected the transaction.');
                break;
            case OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERROR:
                alert('Not connected');
                break;
            default:
                alert('Unknown error happened');
                break;
        }
    } else {
        alert('Unknown error happened');
    }
}

Listen to Wallet Status Changes#

Wallet statuses such as connection success, reconnection success, and disconnection can all be tracked using this method.

onStatusChange( callback: (walletInfo) => void, errorsHandler?: (err) => void ): () => void;

Request Parameters

- callback - (walletInfo) => void: This callback will be triggered when the wallet status changes;
    - walletInfo - object
        - device - object
            - appName - string: Wallet name
            - platform - string: Wallet platform (android, iOS)
            - appVersion - string: Wallet version number
            - maxProtocolVersion - number:
            - features - string[]: Supported methods, current version supports sendTransaction
        - account - Account
            - address - string: TON address in raw form (`0:<hex>`)
            - chain - "-239"
            - walletStateInit - string: Base64 (not URL safe) encoded stateinit cell for the wallet contract
            - publicKey - string: HEX string without 0x
        - connectItems - object
            - name - string: "ton_proof"
            - proof - object
                - timestamp - number: Timestamp
                - domain - object
                    - lengthBytes - number: AppDomain Length
                    - value - string: App domain name (as URL part, without encoding)
                - payload - string: Base64-encoded signature
                - signature - string: Payload from the request

- errorsHandler - (err: OkxConnectError) => void: This errorsHandler will be called when an error occurs during wallet status changes;
    - err - TonConnectError
        - code - number
        - message - string

Return Value

  • () => void: Call this function when you no longer need to listen for updates to save resources.

Example

import {Wallet} from "okxconnect";

const unsubscribe = okxTonConnect.onStatusChange((walletInfo: Wallet | null) => {
        console.log('Connection status:', walletInfo);
    }, (err: OkxConnectError) => {
        console.log('Connection status:', err);
    }
)
unsubscribe()

Listen to Event#

Notifications for corresponding events will be sent when the following events occur. Dapp can add listeners as needed to handle the corresponding logic.

Event List

Event NameTrigger Timing
OKX_TON_CONNECTION_STARTEDWhen the user starts connecting to the wallet
OKX_TON_CONNECTION_COMPLETEDWhen the user successfully connects to the wallet
OKX_TON_CONNECTION_ERRORWhen the user cancels the connection or an error occurs during the connection process
OKX_TON_CONNECTION_RESTORING_STARTEDWhen the dApp starts restoring the connection
OKX_TON_CONNECTION_RESTORING_COMPLETEDWhen the dApp successfully restores the connection
OKX_TON_CONNECTION_RESTORING_ERRORWhen the dApp fails to restore the connection
OKX_TON_DISCONNECTIONWhen the user starts disconnecting the wallet
OKX_TON_TRANSACTION_SENT_FOR_SIGNATUREWhen the user sends a transaction for signing
OKX_TON_TRANSACTION_SIGNEDWhen the user successfully signs the transaction
OKX_TON_TRANSACTION_SIGNING_FAILEDWhen the user cancels the transaction signing or an error occurs during the signing process

Example

import {OKX_TON_CONNECTION_AND_TRANSACTION_EVENT} from "okxconnect";

window.addEventListener(OKX_TON_CONNECTION_AND_TRANSACTION_EVENT.OKX_TON_CONNECTION_STARTED, (event) => {
    if (event instanceof CustomEvent) {
        console.log('Transaction init', event.detail);
    }
});

Retrieve Account Information#

Retrieve the currently connected account.#

Example

import {Account} from "okxconnect";

var connect: Account = okxTonConnect.account()
Retrieve Wallet Information
Retrieve the currently connected wallet.

Example

import {Wallet} from "okxconnect";

var connect: Wallet = okxTonConnect.wallet()

Error Codes#

Exceptions that may be thrown during connection, transaction, restoring connection, or disconnection processes.

Exceptions

ErrorcodeDes
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERRORUnknown error
OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERRORWallet already connected
OKX_CONNECT_ERROR_CODES.NOT_CONNECTED_ERRORWallet not connected
OKX_CONNECT_ERROR_CODES.USER_REJECTS_ERRORUser rejected
OKX_CONNECT_ERROR_CODES.METHOD_NOT_SUPPORTEDMethod not supported
export enum OKX_CONNECT_ERROR_CODES {
    UNKNOWN_ERROR = 0,
    ALREADY_CONNECTED_ERROR = 11,
    NOT_CONNECTED_ERROR = 12,
    USER_REJECTS_ERROR = 300,
    METHOD_NOT_SUPPORTED = 400,
}