Connect to Mobile Wallet
SDK

SDK#

SDK Installation#

The SDK can be installed via cdn or npm.

Using CDN Add the following script tag to your HTML file. You can replace latest with a specific version, e.g., 1.2.5.

<script src="https://unpkg.com/@okxconnect/tonsdk@latest/dist/okxconnect_tonsdk.min.js"></script>

After adding the script, you can create a new instance of the SDK:

<script> const connector = new OKXTonConnectSDK.OKXTonConnect(); </script>

Using npm

npm install @okxconnect/tonsdk

Initialization#

Before connecting to the wallet, create an instance of the SDK:

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

Request Parameters

  • metaData - object
    • name - string: Application name (not unique).
    • icon - string: URL for the application icon (PNG, ICO formats; best as 180x180px PNG).

Return Value

  • okxTonConnect - OKXTonConnect

Example

import { OKXTonConnect } from "@okxconnect/tonsdk";

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

Connect to Wallet#

Connect to the wallet to get the wallet address as an identifier and the necessary parameters used to sign the transaction.

connect(request): Promise<string>;

Request Parameters

  • request - object (optional)
    • tonProof - string (optional): signature information;
    • redirect - string (optional) : After processing the wallet event, the app will return the required deeplink, e.g. in Telegram environment, this field needs to pass the Telegram deeplink, when the wallet signing is done, OKX App will open the Telegram program through this deeplink, it is not recommended to set it in non-Telegram environment;
    • openUniversalLink - boolean (可选) : When connecting to the wallet, whether to call up the OKX App client via Universal link; if set to true, when the user initiates the connection to the wallet, the OKX App client will be pulled up and a confirmation page will pop up, and if the OKX App client is not installed on the cell phone, it will be redirected to the download page;

Return Value

  • Promise - string: PC web side can generate QR code according to this field, OKX App client can scan the generated QR code in web3 and connect to DApp;

Recommendations

  • Set openUniversalLink to true in your mobile browser or mobile Telegram environment;
  • Set openUniversalLink to false in PC browser environment, and generate QR code according to the returned universalLink, you can use OKX App client to scan the code to connect to it, and cancel the QR code pop-up window after successful connection;

Example

import { OKXConnectError } from "@okxconnect/tonsdk";

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 has previously connected their wallet, use this method to restore the connection state:

restoreConnection(): Promise<void>

Request parameters

None

Return Value

None

Example

okxTonConnect.restoreConnection()

Disconnect#

Disconnects the connected wallet and deletes the current session. If you want to switch connected wallets, disconnect the current wallet first.

Example

import { OKX_CONNECT_ERROR_CODES } from "@okxconnect/tonsdk";

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');
    }
}

Connected#

Get whether there is currently a connected wallet

Example

var connect: boolean = okxTonConnect.connected()

Send transaction#

Method for sending a message to a wallet:

sendTransaction(transaction, options): Promise<SendTransactionResponse>

Request Parameters

  • transaction - object
    • validUntil - number :unix timestamp. Transactions will be invalid after this point
    • from - string(optional): the sender address to which the DApp sends transactions, 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 out 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 : The 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 is called when the signature request is sent;

Return Value

  • Promise - {boc: string}: signed result

Example

import { OKXConnectError } from "@okxconnect/tonsdk";

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');
    }
}

Monitor wallet state changes#

The wallet statuses are: successful connection, successful restoration of connection, disconnection, etc. You can use this method to get the status.

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

Request Parameters

  • callback - (walletInfo) => void : This callback is called when the wallet state changes;

    • walletinfo - object
      • device - object
        • appName - string : the name of the wallet
        • platform - string : the platform of the wallet, (android,ios)
        • appVersion - string : the version number of the wallet
        • maxProtocolVersion - number : the version of the wallet, (android,ios)
        • features - string[] : supported methods, current version is sendTransaction
      • account - Account
        • address - string : TON address raw (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 is called when an exception occurs due to a change in the wallet state;

    • err - TonConnectError
      • code - number
      • message - string

Return Value

  • () => void : Execute this method to save resources when there is no longer a need to listen for updates.

Example

import { Wallet } from "@okxconnect/tonsdk";

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

Call unsubscribe to save resources when you no longer need to listen for updates.

unsubscribe()

Monitor Event#

When the following events occur, corresponding event notifications will be sent, and the Dapp can add listeners as needed to handle the corresponding logic;

event

event nametrigger timing
OKX_TON_CONNECTION_STARTEDWhen the user starts to connect to the wallet
OKX_TON_CONNECTION_COMPLETEDWhen the user successfully connects to the wallet
OKX_TON_CONNECTION_ERRORWhen the user canceled the connection or there was an error during the connection process
OKX_TON_CONNECTION_RESTORING_STARTEDWhen the dApp starts to resume 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 to disconnect from the wallet
OKX_TON_TRANSACTION_SENT_FOR_SIGNATUREWhen the user sends a transaction for signature
OKX_TON_TRANSACTION_SIGNEDWhen the user successfully signs a transaction
OKX_TON_TRANSACTION_SIGNING_FAILEDWhen the user canceled the transaction signing or there was an error during the signing process

Example

import { OKX_TON_CONNECTION_AND_TRANSACTION_EVENT } from "@okxconnect/tonsdk";

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

Get account information#

Get the currently connected account

example

import { Account } from "@okxconnect/tonsdk";

var connect: Account = okxTonConnect.account()

Get wallet information#

Get the currently connected wallet

Example

import { Wallet } from "@okxconnect/tonsdk";

var connect: Wallet = okxTonConnect.wallet()

Error codes#

Exceptions that may be thrown during connection, transaction, resumption of connection, and disconnection.

Exception

Error Codedescription
OKX_CONNECT_ERROR_CODES.UNKNOWN_ERRORUnknown Exception
OKX_CONNECT_ERROR_CODES.ALREADY_CONNECTED_ERRORWallet 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,
}