Connect to App or Mini Wallet

UI#

In addition to SDK, we also provide a UI interface. If using the UI connection, and the DApp is operating in Telegram, users can choose to open the mobile App Wallet or stay in Telegram and launch the OKX Mini Wallet.

Installation and Initialization#

Make sure to update the OKX App to version 6.90.1 or later to start integrating OKX Connect into your DApp can be done using npm:

To integrate OKX Connect into your DApp, you can use npm:

npm install @okxconnect/ui
npm install @okxconnect/sui-provider

Before connecting to a wallet, you need to create an object that can provide a UI interface for subsequent operations such as connecting to the wallet and sending transactions.

OKXUniversalConnectUI.init(dappMetaData, actionsConfiguration, uiPreferences, language)

Request parameters

  • dappMetaData - object
    • name - string: The name of the application, will not be used as a unique representation.
    • icon - string: URL of the application icon, must be in PNG, ICO, etc. SVG icons are not supported. SVG icons are not supported. It is best to pass a url pointing to a 180x180px PNG icon.
  • actionsConfiguration - object
    • modals - ('before' | 'success' | 'error')[] | 'all' The modes of displaying alerts during transaction, defaults to 'before'.
    • returnStrategy -string 'none' | ${string}://${string}; for app wallet, specify the return strategy for the deep link when the user signs/rejects the request, if it is in telegram, you can configure tg://resolve
    • tmaReturnUrl -string 'back' | 'none' | ${string}://${string}; For Telegram Mini Wallet, specify the return policy of deep link when user signs/rejects the request, if it's in telegram, you can configure tg://resolve none means no processing after signing; default is back;
  • uiPreferences -object
    • theme - Theme can be: THEME.DARK, THEME.LIGHT, 'SYSTEM'.
  • language - 'en_US' | 'ru_RU' | 'zh_CN' | 'ar_AE' | 'cs_CZ' | 'de_DE' | 'es_ES' | 'es_LAT' | 'fr_FR' | 'id_ID' | 'it_IT' | 'nl_NL' | 'pl_PL' | 'pt_BR' | 'pt_PT' | 'ro_RO' | 'tr_TR' | 'uk_UA' | 'vi_VN'. , defaults to en_US

Return Value

  • OKXUniversalConnectUI

Example

import { OKXUniversalConnectUI } from "@okxconnect/ui";

const okxUniversalConnectUI = await OKXUniversalConnectUI.init({
    dappMetaData: {
        icon: "https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png",
        name: "OKX Connect Demo"
    },
    actionsConfiguration: {
        returnStrategy: 'tg://resolve',
        modals:"all"
    },
    language: "en_US",
    uiPreferences: {
        theme: THEME.LIGHT
    },
});

Connect to OKX Wallet#

Connecting to a wallet goes to get the wallet address, which serves as the identifier and the necessary parameters used to sign the transaction.

okxUniversalConnectUI.connect(connectParams: ConnectParams);

Request Parameters

  • connectParams - ConnectParams
    • namespaces - [namespace: string]: ConnectNamespace ; information necessary to request a connection, the key for Sui is 'sui'. If any of the requested chains are not supported by the wallet, the wallet will reject the connection;
      • chains: string[]; chain id information, the chain's key is 'sui', the wallet will reject the connection if any of the requested chains is not supported.
    • optionalNamespaces - [namespace: string]: ConnectNamespace; optional information for requesting connection, the key for EVM is 'eip155', the key for Sui is 'sui'. If the corresponding chain information is not supported by the wallet, the connection can still be made;
      • chains: string[]; chain id info
    • sessionConfig: object
      • redirect: string Jump parameter after successful connection, if it is Mini App in Telegram, here can be set to Telegram's deeplink: 'tg://resolve'

Return Value

  • Promise <SessionTypes.Struct | undefined>
    • topic: string; The session identifier;
    • namespaces: Record<string, Namespace>; namespace information for a successful connection;
      • chains: string[]; Chain information for the connection;
      • accounts: string[]; accounts information for the connection;
      • methods: string[]; Methods supported by the wallet in the current namespace;
      • defaultChain?: string; The default chain for the current session.
    • sessionConfig?: SessionConfig
      • dappInfo: object DApp information;
        • name: string
        • icon:string

Example

var session = await okxUniversalConnectUI.openModal({
  namespaces: {
        sui: {
            chains: ["sui:mainnet"]
        }
    }
})


## Connect to wallet and sign

Connect to the wallet to get the wallet address and sign the data; the result will be called back in the event ‘connect_signResponse’;

await okxUniversalConnectUI.openModalAndSign(connectParams: ConnectParams, signRequest: RequestParams[]);


**Request parameters**

- connectParams - ConnectParams
    - namespaces - [namespace: string]: ConnectNamespace ; information necessary to request a connection, the key for Sui is ‘sui’.
      If any of the requested chains are not supported by the wallet, the wallet will reject the connection;
        - chains: string[]; information about the chain ids, the name of the chain, the name of the wallet, and the name of the wallet.
    - optionalNamespaces - [namespace: string]: ConnectNamespace; optional information of the requested connection, the key of Sui is ‘sui’.
      If the corresponding chain information is not supported by the wallet, the connection can still be made;
        - chains: string[]; Chain id information, if the corresponding chain is not supported by the wallet, it can still be connected.
    - sessionConfig: object
        - redirect: string Jump parameter after successful connection, if it is a Mini App in Telegram, here you can set it to Telegram's deeplink: ‘tg://resolve’.
- signRequest - RequestParams[]; the method to request the connection and sign the request, at most one method can be supported at the same time;
    - method: string; the name of the requested method, Sui supports methods such as ‘sui_signMessage’ and ‘sui_signPersonalMessage’;
    - chainId: string; the ID of the chain where the method is executed, the chainId must be included in the namespaces above;
    - params: unknown[] | Record`<string, unknown>` | object | undefined; Parameters corresponding to the requested method;


**Return Value**

- Promise `<SessionTypes.Struct | undefined>`
    - topic: string; the session identifier;
    - namespaces: `Record<string, Namespace>`; namespace information for a successful connection;
        - chains: string[]; Chain information for the connection;
        - accounts: string[]; accounts information for the connection;
        - methods: string[]; Methods supported by the wallet in the current namespace;
        - defaultChain?: string; The default chain for the current session.
    - sessionConfig?: SessionConfig
        - dappInfo: object DApp information;
            - name: string
            - icon:string


**Example**

```typescript
// Add the signature result monitor first
okxUniversalConnectUI.on("connect_signResponse", (signResponse) => {
  console.log(signResponse);
});
let suiData = [
    76, 111, 103, 105, 110, 32, 119, 105, 116, 104, 32, 66, 108, 117, 101,
    109, 111, 118, 101,
];
let uint8Array = new Uint8Array(suiData);
var session = await okxUniversalConnectUI.openModalAndSign({
     namespaces: {
            sui: {
                chains: ["sui:mainnet"]
            }
    },
    sessionConfig: {
        redirect: "tg://resolve"
    }
},
    [
        {
        chainId: "sui:mainnet",
        method: "sui_signMessage",
        params: {
            message: uint8Array,
            }
        }
    ]
)

Determine if the wallet is connected#

Gets whether the wallet is currently connected.

Return Value

  • boolean

Example

okxUniversalConnectUI.connected();

Sending Signature and Transactions#

This method allows sending messages to the wallet, supporting signatures, transactions.

First create an OKXSuiProvider object, passing OKXUniversalProvider into the constructor.

import { OKXSuiProvider } from "@okxconnect/sui-provider"
let suiProvider = new OKXSuiProvider(okxUniversalConnectUI)

Get Account#

suiProvider.getAccount();

Returns the value.

  • Object
    • address: string wallet address
    • publicKey: string public key (requires App 6.92.0 or later support)

Example

let result = suiProvider.getAccount()

// Return structure
{
'address":0x7995ca23961fe06d8cea7da58ca751567ce820d7cba77b4a373249034eecca4a,
    'publicKey": “tUvCYrG22rHKR0c306MxgnhXOSf16Ot6H3GMO7btwDI=,
}

SignMessage#

suiProvider.signMessage(input: SuiSignMessageInput);

Request Parameters

  • SuiSignMessageInput - object
    • message: Uint8Array

Return Value

  • Promise - object
    • messageBytes: string
    • signature: string

SignPersonalMessage#

suiProvider.signPersonalMessage(input: SuiSignMessageInput);

Request Parameters

  • SuiSignMessageInput - object
    • message: Uint8Array

Return Value

  • Promise - object
    • bytes: string
    • signature: string

Example

const data = [76, 111, 103, 105, 110, 32, 119, 105, 116, 104, 32, 66, 108, 117, 101, 109, 111, 118, 101];
const uint8Array = new Uint8Array(data);
let input = {
    message: uint8Array
}
let signResult1 = await suiProvider.signMessage(input)
let signResult2 = await suiProvider.signPersonalMessage(input)

Sign Transaction#

suiProvider.signTransaction(input);

Request Parameters

// txBytes and txSerialize are the serialization of the transactionBlock.
// and transactionBlock can be passed in one way or the other, but not both.
interface SuiSignTransactionBlockInput {
    transactionBlock: TransactionBlock;
    chain: IdentifierString;
    txBytes: string?;
    txSerialize: string?
}

Return Value

  • Promise - object
    • signature: string,
    • transactionBlockBytes: string

Signs a transaction and broadcasts onchain#

suiProvider.signAndExecuteTransaction(input);

Request Parameters

// txBytes and txSerialize is Serialized from transactionBlock,
// if you pass transactionBlock, then no need to pass txBytes and txSerialize
interface SuiSignTransactionBlockInput {
    transactionBlock: TransactionBlock;
    chain: IdentifierString;
    txBytes: string?;
    txSerialize: string?;
}

Return Value

  • Promise - object
    • confirmedLocalExecution: bool,
    • digest: string,
    • txBytes: string

Example

// Define the amount to be transferred and the destination address
const amount = 109; // Amount to be transferred
const recipientAddress = '0x'; // destination address

/// Construct a transfer transaction
const tx = new Transaction();
const [coin] = tx.splitCoins(tx.gas, [amount]);
tx.transferObjects([coin], recipientAddress)
const input = {
    transactionBlock: tx,
    chain: 'sui:mainnet',
    options: {
        showEffects: true,
    }
}

let signResult1 = await suiProvider.signTransaction(input)
let signResult2 = await suiProvider.signAndExecuteTransaction(input)

Event#

// Generate universalLink
okxUniversalConnectUI.on("display_uri", (uri) => {
    console.log(uri);
}).
// Session information changes will trigger this event;
okxUniversalConnectUI.on("session_update", (session) => {
  console.log(JSON.stringify(session));
});
// Disconnecting triggers this event;
okxUniversalConnectUI.on("session_delete", ({topic}) => {
    console.log(topic);
});
// This event is triggered when a connection is made and the signature is signed.
okxUniversalConnectUI.on("connect_signResponse", (signResponse) => {
  console.log(signResponse);
});

Error codes#

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

Exception

Error CodeDescription
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
OKX_CONNECT_ERROR_CODES.CHAIN_NOT_SUPPORTEDChain Not Supported
OKX_CONNECT_ERROR_CODES.WALLET_NOT_SUPPORTEDWallet Not Supported
OKX_CONNECT_ERROR_CODES.CONNECTION_ERRORConnection Error
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,
    CHAIN_NOT_SUPPORTED = 500,
    WALLET_NOT_SUPPORTED = 600,
    CONNECTION_ERROR = 700
}